목차

  1. 1 소개
  2. 2 공통 인프라
  3. 3 HTML 문서의 의미론, 구조, 및 API
  4. 4 HTML 요소
  5. 5 마이크로데이터
  6. 6 사용자 상호작용
  7. 7 웹 페이지 로딩
  8. 8 웹 애플리케이션 API
  9. 9 통신
  10. 10 웹 워커
  11. 11 워클릿
  12. 12 웹 저장소
  13. 13 HTML 구문
  14. 14 XML 구문
  15. 15 렌더링
  16. 16 폐기된 기능
  17. 17 IANA 고려사항
  18. 색인
  19. 참조
  20. 감사의 말
  21. 지적 재산권

전체 목차

  1. 1 소개
    1. 1.1 이 명세는 어디에 적합합니까?
    2. 1.2 이것은 HTML5인가요?
    3. 1.3 배경
    4. 1.4 대상
    5. 1.5 범위
    6. 1.6 역사
    7. 1.7 설계 노트
      1. 1.7.1 스크립트 실행의 직렬화 가능성
      2. 1.7.2 다른 명세와의 준수
      3. 1.7.3 확장성
    8. 1.8 HTML 대 XML 구문
    9. 1.9 이 명세의 구조
      1. 1.9.1 이 명세를 읽는 방법
      2. 1.9.2 타이포그래픽 규칙
    10. 1.10 HTML의 간략한 소개
      1. 1.10.1 HTML로 안전한 애플리케이션 작성
      2. 1.10.2 스크립팅 API를 사용할 때 피해야 할 일반적인 실수
      3. 1.10.3 HTML 작성 시 실수를 잡는 방법: 유효성 검사기와 적합성 검사기
    11. 1.11 저자에 대한 적합성 요구사항
      1. 1.11.1 표현적 마크업
      2. 1.11.2 구문 오류
      3. 1.11.3 콘텐츠 모델 및 속성 값에 대한 제한
    12. 1.12 추천 읽기
  2. 2 공통 인프라
    1. 2.1 용어
      1. 2.1.1 병렬 처리
      2. 2.1.2 리소스
      3. 2.1.3 XML 호환성
      4. 2.1.4 DOM 트리
      5. 2.1.5 스크립팅
      6. 2.1.6 플러그인
      7. 2.1.7 문자 인코딩
      8. 2.1.8 준수 클래스
      9. 2.1.9 종속성
      10. 2.1.10 확장성
      11. 2.1.11 XPath 및 XSLT와의 상호작용
    2. 2.2 정책 제어 기능
    3. 2.3 공통 마이크로 구문
      1. 2.3.1 공통 구문 분석 관용구
      2. 2.3.2 불리언 속성
      3. 2.3.3 키워드 및 열거형 속성
      4. 2.3.4 숫자
        1. 2.3.4.1 부호 있는 정수
        2. 2.3.4.2 비음수 정수
        3. 2.3.4.3 부동 소수점 숫자
        4. 2.3.4.4 백분율 및 길이
        5. 2.3.4.5 0이 아닌 백분율 및 길이
        6. 2.3.4.6 부동 소수점 숫자 목록
        7. 2.3.4.7 길이 목록
      5. 2.3.5 날짜 및 시간
        1. 2.3.5.1
        2. 2.3.5.2 날짜
        3. 2.3.5.3 연도 없는 날짜
        4. 2.3.5.4 시간
        5. 2.3.5.5 로컬 날짜 및 시간
        6. 2.3.5.6 시간대
        7. 2.3.5.7 전세계 날짜 및 시간
        8. 2.3.5.8
        9. 2.3.5.9 기간
        10. 2.3.5.10 모호한 시간
      6. 2.3.6 색상
      7. 2.3.7 공백으로 구분된 토큰
      8. 2.3.8 쉼표로 구분된 토큰
      9. 2.3.9 참조
      10. 2.3.10 미디어 쿼리
      11. 2.3.11 고유한 내부 값
    4. 2.4 URL
      1. 2.4.1 용어
      2. 2.4.2 URL 구문 분석
      3. 2.4.3 기본 URL의 동적 변경
    5. 2.5 리소스 가져오기
      1. 2.5.1 용어
      2. 2.5.2 리소스 유형 결정
      3. 2.5.3 meta 요소에서 문자 인코딩 추출
      4. 2.5.4 CORS 설정 속성
      5. 2.5.5 리퍼러 정책 속성
      6. 2.5.6 넌스 속성
      7. 2.5.7 지연 로딩 속성
      8. 2.5.8 차단 속성
      9. 2.5.9 가져오기 우선 순위 속성
    6. 2.6 공통 DOM 인터페이스
      1. 2.6.1 콘텐츠 속성의 IDL 속성 반영
      2. 2.6.2 명세서에서 reflect 사용
      3. 2.6.3 컬렉션
        1. 2.6.3.1 HTMLAllCollection 인터페이스
          1. 2.6.3.1.1 [[Call]] ( thisArgument, argumentsList )
        2. 2.6.3.2 HTMLFormControlsCollection 인터페이스
        3. 2.6.3.3 HTMLOptionsCollection 인터페이스
      4. 2.6.4 DOMStringList 인터페이스
    7. 2.7 구조화된 데이터의 안전한 전달
      1. 2.7.1 직렬화 가능한 객체
      2. 2.7.2 전송 가능한 객체
      3. 2.7.3 StructuredSerializeInternal ( value, forStorage [ , memory ] )
      4. 2.7.4 StructuredSerialize ( value )
      5. 2.7.5 StructuredSerializeForStorage ( value )
      6. 2.7.6 StructuredDeserialize ( serialized, targetRealm [ , memory ] )
      7. 2.7.7 StructuredSerializeWithTransfer ( value, transferList )
      8. 2.7.8 StructuredDeserializeWithTransfer ( serializeWithTransferResult, targetRealm )
      9. 2.7.9 다른 명세서에서 직렬화 및 전송 수행
      10. 2.7.10 구조화된 클로닝 API
  3. 3 HTML 문서의 의미, 구조 및 API
    1. 3.1 문서
      1. 3.1.1 Document 객체
      2. 3.1.2 DocumentOrShadowRoot 인터페이스
      3. 3.1.3 리소스 메타데이터 관리
      4. 3.1.4 문서 로딩 상태 보고
      5. 3.1.5 렌더 차단 메커니즘
      6. 3.1.6 DOM 트리 접근자
    2. 3.2 요소
      1. 3.2.1 의미론
      2. 3.2.2 DOM의 요소
      3. 3.2.3 HTML 요소 생성자
      4. 3.2.4 요소 정의
        1. 3.2.4.1 속성
      5. 3.2.5 콘텐츠 모델
        1. 3.2.5.1 "nothing" 콘텐츠 모델
        2. 3.2.5.2 콘텐츠의 종류
          1. 3.2.5.2.1 메타데이터 콘텐츠
          2. 3.2.5.2.2 흐름 콘텐츠
          3. 3.2.5.2.3 섹션 콘텐츠
          4. 3.2.5.2.4 헤딩 콘텐츠
          5. 3.2.5.2.5 구문 콘텐츠
          6. 3.2.5.2.6 임베디드 콘텐츠
          7. 3.2.5.2.7 인터랙티브 콘텐츠
          8. 3.2.5.2.8 실체 콘텐츠
          9. 3.2.5.2.9 스크립트 지원 요소
        3. 3.2.5.3 투명 콘텐츠 모델
        4. 3.2.5.4 문단
      6. 3.2.6 전역 속성
        1. 3.2.6.1 title 속성
        2. 3.2.6.2 langxml:lang 속성
        3. 3.2.6.3 translate 속성
        4. 3.2.6.4 dir 속성
        5. 3.2.6.5 style 속성
        6. 3.2.6.6 data-* 속성을 사용하여 비가시적 데이터를 포함하기
      7. 3.2.7 innerTextouterText 속성
      8. 3.2.8 양방향 알고리즘 관련 요구사항
        1. 3.2.8.1 양방향 알고리즘 서식 문자에 대한 작성 적합성 기준
        2. 3.2.8.2 사용자 에이전트 적합성 기준
      9. 3.2.9 ARIA 및 플랫폼 접근성 API 관련 요구사항
  4. 4 HTML의 요소들
    1. 4.1 문서 요소
      1. 4.1.1 html 요소
    2. 4.2 문서 메타데이터
      1. 4.2.1 head 요소
      2. 4.2.2 title 요소
      3. 4.2.3 base 요소
      4. 4.2.4 link 요소
        1. 4.2.4.1 media 속성 처리
        2. 4.2.4.2 type 속성 처리
        3. 4.2.4.3 link 요소에서 리소스 가져오기 및 처리
        4. 4.2.4.4 `Link` 헤더 처리
        5. 4.2.4.5 초기 힌트
        6. 4.2.4.6 link 요소를 사용하여 생성된 하이퍼링크를 따라갈 수 있는 수단 제공
      5. 4.2.5 meta 요소
        1. 4.2.5.1 표준 메타데이터 이름
        2. 4.2.5.2 기타 메타데이터 이름
        3. 4.2.5.3 프라그마 지시문
        4. 4.2.5.4 문서의 문자 인코딩 지정
      6. 4.2.6 style 요소
      7. 4.2.7 스타일링과 스크립팅의 상호작용
    3. 4.3 섹션
      1. 4.3.1 body 요소
      2. 4.3.2 article 요소
      3. 4.3.3 section 요소
      4. 4.3.4 nav 요소
      5. 4.3.5 aside 요소
      6. 4.3.6 h1, h2, h3, h4, h5, h6 요소
      7. 4.3.7 hgroup 요소
      8. 4.3.8 header 요소
      9. 4.3.9 footer 요소
      10. 4.3.10 address 요소
      11. 4.3.11 제목과 개요
        1. 4.3.11.1 샘플 개요
        2. 4.3.11.2 개요를 사용자에게 노출하기
      12. 4.3.12 사용 요약
        1. 4.3.12.1 Article 또는 Section?
    4. 4.4 콘텐츠 그룹화
      1. 4.4.1 p 요소
      2. 4.4.2 hr 요소
      3. 4.4.3 pre 요소
      4. 4.4.4 blockquote 요소
      5. 4.4.5 ol 요소
      6. 4.4.6 ul 요소
      7. 4.4.7 menu 요소
      8. 4.4.8 li 요소
      9. 4.4.9 dl 요소
      10. 4.4.10 dt 요소
      11. 4.4.11 dd 요소
      12. 4.4.12 figure 요소
      13. 4.4.13 figcaption 요소
      14. 4.4.14 main 요소
      15. 4.4.15 search 요소
      16. 4.4.16 div 요소
    5. 4.5 텍스트 수준의 의미론
      1. 4.5.1 a 요소
      2. 4.5.2 em 요소
      3. 4.5.3 strong 요소
      4. 4.5.4 small 요소
      5. 4.5.5 s 요소
      6. 4.5.6 cite 요소
      7. 4.5.7 q 요소
      8. 4.5.8 dfn 요소
      9. 4.5.9 abbr 요소
      10. 4.5.10 ruby 요소
      11. 4.5.11 rt 요소
      12. 4.5.12 rp 요소
      13. 4.5.13 data 요소
      14. 4.5.14 time 요소
      15. 4.5.15 code 요소
      16. 4.5.16 var 요소
      17. 4.5.17 samp 요소
      18. 4.5.18 kbd 요소
      19. 4.5.19 subsup 요소
      20. 4.5.20 i 요소
      21. 4.5.21 b 요소
      22. 4.5.22 u 요소
      23. 4.5.23 mark 요소
      24. 4.5.24 bdi 요소
      25. 4.5.25 bdo 요소
      26. 4.5.26 span 요소
      27. 4.5.27 br 요소
      28. 4.5.28 wbr 요소
      29. 4.5.29 사용 요약
    6. 4.6 링크
      1. 4.6.1 소개
      2. 4.6.2 aarea 요소에 의해 생성된 링크
      3. 4.6.3 aarea 요소에 대한 API
      4. 4.6.4 하이퍼링크 따르기
      5. 4.6.5 리소스 다운로드
      6. 4.6.6 하이퍼링크 감사
        1. 4.6.6.1 `Ping-From` 및 `Ping-To` 헤더
      7. 4.6.7 링크 유형
        1. 4.6.7.1 링크 유형 "alternate"
        2. 4.6.7.2 링크 유형 "author"
        3. 4.6.7.3 링크 유형 "bookmark"
        4. 4.6.7.4 링크 유형 "canonical"
        5. 4.6.7.5 링크 유형 "dns-prefetch"
        6. 4.6.7.6 링크 유형 "expect"
        7. 4.6.7.7 링크 유형 "external"
        8. 4.6.7.8 링크 유형 "help"
        9. 4.6.7.9 링크 유형 "icon"
        10. 4.6.7.10 링크 유형 "license"
        11. 4.6.7.11 링크 유형 "manifest"
        12. 4.6.7.12 링크 유형 "modulepreload"
        13. 4.6.7.13 링크 유형 "nofollow"
        14. 4.6.7.14 링크 유형 "noopener"
        15. 4.6.7.15 링크 유형 "noreferrer"
        16. 4.6.7.16 링크 유형 "opener"
        17. 4.6.7.17 링크 유형 "pingback"
        18. 4.6.7.18 링크 유형 "preconnect"
        19. 4.6.7.19 링크 유형 "prefetch"
        20. 4.6.7.20 링크 유형 "preload"
        21. 4.6.7.21 링크 유형 "privacy-policy"
        22. 4.6.7.22 링크 유형 "search"
        23. 4.6.7.23 링크 유형 "stylesheet"
        24. 4.6.7.24 링크 유형 "tag"
        25. 4.6.7.25 링크 유형 "terms-of-service"
        26. 4.6.7.26 순차적 링크 유형
          1. 4.6.7.26.1 링크 유형 "next"
          2. 4.6.7.26.2 링크 유형 "prev"
        27. 4.6.7.27 기타 링크 유형
    7. 4.7 편집
      1. 4.7.1 ins 요소
      2. 4.7.2 del 요소
      3. 4.7.3 insdel 요소에 공통된 속성
      4. 4.7.4 편집과 단락
      5. 4.7.5 편집과 목록
      6. 4.7.6 편집과 표
    8. 4.8 내장 콘텐츠
      1. 4.8.1 picture 요소
      2. 4.8.2 source 요소
      3. 4.8.3 img 요소
      4. 4.8.4 이미지
        1. 4.8.4.1 소개
          1. 4.8.4.1.1 적응형 이미지
        2. 4.8.4.2 source, img, link 요소에 공통된 속성
          1. 4.8.4.2.1 Srcset 속성
          2. 4.8.4.2.2 Sizes 속성
        3. 4.8.4.3 처리 모델
          1. 4.8.4.3.1 이미지를 가져올 시기
          2. 4.8.4.3.2 DOM 변경에 반응하기
          3. 4.8.4.3.3 사용 가능한 이미지 목록
          4. 4.8.4.3.4 이미지 디코딩
          5. 4.8.4.3.5 이미지 데이터 업데이트
          6. 4.8.4.3.6 이미지를 프레젠테이션에 대비
          7. 4.8.4.3.7 이미지 소스 선택
          8. 4.8.4.3.8 속성에서 소스 세트 생성
          9. 4.8.4.3.9 소스 세트 업데이트
          10. 4.8.4.3.10 Srcset 속성 파싱
          11. 4.8.4.3.11 Sizes 속성 파싱
          12. 4.8.4.3.12 소스 밀도 정규화
          13. 4.8.4.3.13 환경 변화에 반응
        4. 4.8.4.4 이미지의 대체 텍스트를 제공하기 위한 요구사항
          1. 4.8.4.4.1 일반 지침
          2. 4.8.4.4.2 이미지 외에는 아무것도 포함하지 않는 링크 또는 버튼
          3. 4.8.4.4.3 대체 그래픽 표현이 있는 문구 또는 단락: 차트, 다이어그램, 그래프, 지도, 일러스트레이션
          4. 4.8.4.4.4 대체 그래픽 표현이 있는 짧은 문구 또는 레이블: 아이콘, 로고
          5. 4.8.4.4.5 타이포그래피 효과를 위해 그래픽으로 렌더링된 텍스트
          6. 4.8.4.4.6 주변 텍스트의 일부에 대한 그래픽 표현
          7. 4.8.4.4.7 보조 이미지
          8. 4.8.4.4.8 정보를 추가하지 않는 순수하게 장식적인 이미지
          9. 4.8.4.4.9 링크 없이 단일 큰 그림을 구성하는 이미지 그룹
          10. 4.8.4.4.10 링크가 있는 단일 큰 그림을 구성하는 이미지 그룹
          11. 4.8.4.4.11 콘텐츠의 핵심 부분
          12. 4.8.4.4.12 사용자를 대상으로 하지 않은 이미지
          13. 4.8.4.4.13 이미지를 볼 수 있는 것으로 알려진 특정인을 대상으로 한 이메일 또는 개인 문서에 포함된 이미지
          14. 4.8.4.4.14 마크업 생성기를 위한 지침
          15. 4.8.4.4.15 준수 검사기를 위한 지침
      5. 4.8.5 iframe 요소
      6. 4.8.6 embed 요소
      7. 4.8.7 object 요소
      8. 4.8.8 video 요소
      9. 4.8.9 audio 요소
      10. 4.8.10 track 요소
      11. 4.8.11 미디어 요소
        1. 4.8.11.1 오류 코드
        2. 4.8.11.2 미디어 리소스의 위치
        3. 4.8.11.3 MIME 유형
        4. 4.8.11.4 네트워크 상태
        5. 4.8.11.5 미디어 리소스 로드
        6. 4.8.11.6 미디어 리소스의 오프셋
        7. 4.8.11.7 준비 상태
        8. 4.8.11.8 미디어 리소스 재생
        9. 4.8.11.9 탐색
        10. 4.8.11.10 다중 미디어 트랙이 있는 미디어 리소스
          1. 4.8.11.10.1 AudioTrackListVideoTrackList 객체
          2. 4.8.11.10.2 선언적으로 특정 오디오 및 비디오 트랙 선택
        11. 4.8.11.11 시간 지정된 텍스트 트랙
          1. 4.8.11.11.1 텍스트 트랙 모델
          2. 4.8.11.11.2 인밴드 텍스트 트랙 소싱
          3. 4.8.11.11.3 아웃밴드 텍스트 트랙 소싱
          4. 4.8.11.11.4 다양한 형식의 큐를 텍스트 트랙 큐로 노출시키는 지침
          5. 4.8.11.11.5 텍스트 트랙 API
          6. 4.8.11.11.6 텍스트 트랙 API 객체에 대한 이벤트 핸들러
          7. 4.8.11.11.7 메타데이터 텍스트 트랙에 대한 모범 사례
        12. 4.8.11.12 URL을 통해 트랙 종류 식별
        13. 4.8.11.13 사용자 인터페이스
        14. 4.8.11.14 시간 범위
        15. 4.8.11.15 TrackEvent 인터페이스
        16. 4.8.11.16 이벤트 요약
        17. 4.8.11.17 보안 및 개인정보 보호 고려사항
        18. 4.8.11.18 미디어 요소를 사용하는 저자에 대한 모범 사례
        19. 4.8.11.19 미디어 요소 구현자에 대한 모범 사례
      12. 4.8.12 map 요소
      13. 4.8.13 area 요소
      14. 4.8.14 이미지 맵
        1. 4.8.14.1 작성
        2. 4.8.14.2 처리 모델
      15. 4.8.15 MathML
      16. 4.8.16 SVG
      17. 4.8.17 차원 속성
    9. 4.9 표 형식 데이터
      1. 4.9.1 table 요소
        1. 4.9.1.1 표 설명 기법
        2. 4.9.1.2 표 디자인 기법
      2. 4.9.2 caption 요소
      3. 4.9.3 colgroup 요소
      4. 4.9.4 col 요소
      5. 4.9.5 tbody 요소
      6. 4.9.6 thead 요소
      7. 4.9.7 tfoot 요소
      8. 4.9.8 tr 요소
      9. 4.9.9 td 요소
      10. 4.9.10 th 요소
      11. 4.9.11 tdth 요소에 공통된 속성
      12. 4.9.12 처리 모델
        1. 4.9.12.1 표 구성
        2. 4.9.12.2 데이터 셀과 헤더 셀 간의 관계 형성
      13. 4.9.13 예제
    10. 4.10 양식
      1. 4.10.1 소개
        1. 4.10.1.1 양식의 사용자 인터페이스 작성
        2. 4.10.1.2 양식에 대한 서버 측 처리 구현
        3. 4.10.1.3 서버와 통신하도록 양식 구성
        4. 4.10.1.4 클라이언트 측 양식 유효성 검사
        5. 4.10.1.5 클라이언트 측 자동 양식 채우기 활성화
        6. 4.10.1.6 모바일 장치에서의 사용자 경험 개선
        7. 4.10.1.7 필드 유형, 자동 채우기 필드 이름 및 입력 방식 간의 차이
        8. 4.10.1.8 날짜, 시간 및 숫자 형식
      2. 4.10.2 범주
      3. 4.10.3 form 요소
      4. 4.10.4 label 요소
      5. 4.10.5 input 요소
        1. 4.10.5.1 type 속성의 상태
          1. 4.10.5.1.1 숨김 상태 (type=hidden)
          2. 4.10.5.1.2 텍스트 (type=text) 상태 및 검색 상태 (type=search)
          3. 4.10.5.1.3 전화 상태 (type=tel)
          4. 4.10.5.1.4 URL 상태 (type=url)
          5. 4.10.5.1.5 이메일 상태 (type=email)
          6. 4.10.5.1.6 비밀번호 상태 (type=password)
          7. 4.10.5.1.7 날짜 상태 (type=date)
          8. 4.10.5.1.8 월 상태 (type=month)
          9. 4.10.5.1.9 주 상태 (type=week)
          10. 4.10.5.1.10 시간 상태 (type=time)
          11. 4.10.5.1.11 로컬 날짜 및 시간 상태 (type=datetime-local)
          12. 4.10.5.1.12 숫자 상태 (type=number)
          13. 4.10.5.1.13 범위 상태 (type=range)
          14. 4.10.5.1.14 색상 상태 (type=color)
          15. 4.10.5.1.15 체크박스 상태 (type=checkbox)
          16. 4.10.5.1.16 라디오 버튼 상태 (type=radio)
          17. 4.10.5.1.17 파일 업로드 상태 (type=file)
          18. 4.10.5.1.18 제출 버튼 상태 (type=submit)
          19. 4.10.5.1.19 이미지 버튼 상태 (type=image)
          20. 4.10.5.1.20 리셋 버튼 상태 (type=reset)
          21. 4.10.5.1.21 버튼 상태 (type=button)
        2. 4.10.5.2 양식 컨트롤의 로컬라이제이션에 대한 구현 노트
        3. 4.10.5.3 일반 input 요소 속성
          1. 4.10.5.3.1 maxlengthminlength 속성
          2. 4.10.5.3.2 size 속성
          3. 4.10.5.3.3 readonly 속성
          4. 4.10.5.3.4 required 속성
          5. 4.10.5.3.5 multiple 속성
          6. 4.10.5.3.6 pattern 속성
          7. 4.10.5.3.7 minmax 속성
          8. 4.10.5.3.8 step 속성
          9. 4.10.5.3.9 list 속성
          10. 4.10.5.3.10 placeholder 속성
        4. 4.10.5.4 일반 input 요소 API
        5. 4.10.5.5 일반 이벤트 동작
      6. 4.10.6 button 요소
      7. 4.10.7 select 요소
      8. 4.10.8 datalist 요소
      9. 4.10.9 optgroup 요소
      10. 4.10.10 option 요소
      11. 4.10.11 textarea 요소
      12. 4.10.12 output 요소
      13. 4.10.13 progress 요소
      14. 4.10.14 meter 요소
      15. 4.10.15 fieldset 요소
      16. 4.10.16 legend 요소
      17. 4.10.17 양식 컨트롤 인프라
        1. 4.10.17.1 양식 컨트롤의 값
        2. 4.10.17.2 변경 가능성
        3. 4.10.17.3 컨트롤과 양식의 연결
      18. 4.10.18 양식 컨트롤에 공통된 속성
        1. 4.10.18.1 양식 컨트롤 명명: name 속성
        2. 4.10.18.2 제출 요소 방향성: dirname 속성
        3. 4.10.18.3 사용자 입력 길이 제한: maxlength 속성
        4. 4.10.18.4 최소 입력 길이 요구사항 설정: minlength 속성
        5. 4.10.18.5 양식 컨트롤 활성화 및 비활성화: disabled 속성
        6. 4.10.18.6 양식 제출 속성
        7. 4.10.18.7 자동 채우기
          1. 4.10.18.7.1 양식 컨트롤 자동 채우기: autocomplete 속성
          2. 4.10.18.7.2 처리 모델
      19. 4.10.19 텍스트 컨트롤 선택에 대한 API
      20. 4.10.20 제약 조건
        1. 4.10.20.1 정의
        2. 4.10.20.2 제약 조건 유효성 검사
        3. 4.10.20.3 제약 조건 유효성 검사 API
        4. 4.10.20.4 보안
      21. 4.10.21 양식 제출
        1. 4.10.21.1 소개
        2. 4.10.21.2 암시적 제출
        3. 4.10.21.3 양식 제출 알고리즘
        4. 4.10.21.4 항목 목록 구성
        5. 4.10.21.5 양식 제출 인코딩 선택
        6. 4.10.21.6 항목 목록을 이름-값 쌍 목록으로 변환
        7. 4.10.21.7 URL-인코딩된 양식 데이터
        8. 4.10.21.8 멀티파트 양식 데이터
        9. 4.10.21.9 일반 텍스트 양식 데이터
        10. 4.10.21.10 SubmitEvent 인터페이스
        11. 4.10.21.11 FormDataEvent 인터페이스
      22. 4.10.22 양식 재설정
    11. 4.11 대화형 요소
      1. 4.11.1 details 요소
      2. 4.11.2 summary 요소
      3. 4.11.3 명령
        1. 4.11.3.1 Facets
        2. 4.11.3.2 a 요소를 사용하여 명령 정의
        3. 4.11.3.3 button 요소를 사용하여 명령 정의
        4. 4.11.3.4 input 요소를 사용하여 명령 정의
        5. 4.11.3.5 option 요소를 사용하여 명령 정의
        6. 4.11.3.6 legend 요소에 accesskey 속성을 사용하여 명령 정의
        7. 4.11.3.7 다른 요소에 명령을 정의하기 위해 accesskey 속성을 사용
      4. 4.11.4 dialog 요소
    12. 4.12 스크립팅
      1. 4.12.1 script 요소
        1. 4.12.1.1 처리 모델
        2. 4.12.1.2 스크립팅 언어
        3. 4.12.1.3 script 요소의 내용에 대한 제한
        4. 4.12.1.4 외부 스크립트에 대한 인라인 문서화
        5. 4.12.1.5 script 요소와 XSLT의 상호작용
      2. 4.12.2 noscript 요소
      3. 4.12.3 template 요소
        1. 4.12.3.1 template 요소와 XSLT 및 XPath의 상호작용
      4. 4.12.4 slot 요소
      5. 4.12.5 canvas 요소
        1. 4.12.5.1 2D 렌더링 컨텍스트
          1. 4.12.5.1.1 구현 노트
          2. 4.12.5.1.2 캔버스 상태
          3. 4.12.5.1.3 선 스타일
          4. 4.12.5.1.4 텍스트 스타일
          5. 4.12.5.1.5 경로 만들기
          6. 4.12.5.1.6 Path2D 객체
          7. 4.12.5.1.7 변형
          8. 4.12.5.1.8 2D 렌더링 컨텍스트를 위한 이미지 소스
          9. 4.12.5.1.9 채우기 및 선 스타일
          10. 4.12.5.1.10 비트맵에 사각형 그리기
          11. 4.12.5.1.11 비트맵에 텍스트 그리기
          12. 4.12.5.1.12 캔버스에 경로 그리기
          13. 4.12.5.1.13 포커스 링 그리기
          14. 4.12.5.1.14 이미지 그리기
          15. 4.12.5.1.15 픽셀 조작
          16. 4.12.5.1.16 합성
          17. 4.12.5.1.17 이미지 스무딩
          18. 4.12.5.1.18 그림자
          19. 4.12.5.1.19 필터
          20. 4.12.5.1.20 외부에서 정의된 SVG 필터 작업
          21. 4.12.5.1.21 그리기 모델
          22. 4.12.5.1.22 모범 사례
          23. 4.12.5.1.23 예제
        2. 4.12.5.2 ImageBitmap 렌더링 컨텍스트
          1. 4.12.5.2.1 소개
          2. 4.12.5.2.2 ImageBitmapRenderingContext 인터페이스
        3. 4.12.5.3 OffscreenCanvas 인터페이스
          1. 4.12.5.3.1 오프스크린 2D 렌더링 컨텍스트
        4. 4.12.5.4 색상 공간 및 색상 공간 변환
        5. 4.12.5.5 비트맵을 파일로 직렬화
        6. 4.12.5.6 canvas 요소와 보안
        7. 4.12.5.7 사전 멀티플라이 알파 및 2D 렌더링 컨텍스트
    13. 4.13 커스텀 요소
      1. 4.13.1 소개
        1. 4.13.1.1 자율 사용자 정의 요소 만들기
        2. 4.13.1.2 양식 연관 사용자 정의 요소 만들기
        3. 4.13.1.3 기본 접근 가능 역할, 상태 및 속성이 있는 커스텀 요소 만들기
        4. 4.13.1.4 사용자 정의 내장 요소 만들기
        5. 4.13.1.5 자율 커스텀 요소의 단점
        6. 4.13.1.6 생성 후 요소 업그레이드
        7. 4.13.1.7 커스텀 요소 상태 노출
      2. 4.13.2 커스텀 요소 생성자 및 반응에 대한 요구사항
      3. 4.13.3 핵심 개념
      4. 4.13.4 CustomElementRegistry 인터페이스
      5. 4.13.5 업그레이드
      6. 4.13.6 커스텀 요소 반응
      7. 4.13.7 요소 내부
        1. 4.13.7.1 ElementInternals 인터페이스
        2. 4.13.7.2 섀도우 루트 액세스
        3. 4.13.7.3 양식 연관 사용자 정의 요소
        4. 4.13.7.4 접근성 의미
        5. 4.13.7.5 사용자 정의 상태 가상 클래스
    14. 4.14 전용 요소가 없는 일반적인 관용구
      1. 4.14.1 브레드크럼 내비게이션
      2. 4.14.2 태그 클라우드
      3. 4.14.3 대화
      4. 4.14.4 각주
    15. 4.15 비활성화된 요소
    16. 4.16 선택기 및 CSS를 사용하여 HTML 요소 일치시키기
      1. 4.16.1 CSS 'attr()' 함수의 대소문자 구분
      2. 4.16.2 선택기의 대소문자 구분
      3. 4.16.3 가상 클래스
  5. 5 마이크로데이터
    1. 5.1 소개
      1. 5.1.1 개요
      2. 5.1.2 기본 구문
      3. 5.1.3 유형 항목
      4. 5.1.4 항목에 대한 전역 식별자
      5. 5.1.5 어휘를 정의할 때 이름 선택
    2. 5.2 마이크로데이터 인코딩
      1. 5.2.1 마이크로데이터 모델
      2. 5.2.2 항목
      3. 5.2.3 이름: itemprop 속성
      4. 5.2.4
      5. 5.2.5 항목과 이름 연결
      6. 5.2.6 마이크로데이터 및 기타 네임스페이스
    3. 5.3 샘플 마이크로데이터 어휘
      1. 5.3.1 vCard
        1. 5.3.1.1 vCard로 변환
        2. 5.3.1.2 예시
      2. 5.3.2 vEvent
        1. 5.3.2.1 iCalendar로 변환
        2. 5.3.2.2 예시
      3. 5.3.3 저작물 라이선싱
        1. 5.3.3.1 예시
    4. 5.4 HTML을 다른 형식으로 변환
      1. 5.4.1 JSON
  6. 6 사용자 상호작용
    1. 6.1 hidden 속성
    2. 6.2 페이지 가시성
      1. 6.2.1 VisibilityStateEntry 인터페이스
    3. 6.3 비활성 하위 트리
      1. 6.3.1 모달 대화 상자와 비활성 하위 트리
      2. 6.3.2 inert 속성
    4. 6.4 사용자 활성화 추적
      1. 6.4.1 데이터 모델
      2. 6.4.2 처리 모델
      3. 6.4.3 사용자 활성화로 제한된 API
      4. 6.4.4 UserActivation 인터페이스
      5. 6.4.5 사용자 에이전트 자동화
    5. 6.5 요소의 활성화 동작
      1. 6.5.1 ToggleEvent 인터페이스
    6. 6.6 포커스
      1. 6.6.1 소개
      2. 6.6.2 데이터 모델
      3. 6.6.3 tabindex 속성
      4. 6.6.4 처리 모델
      5. 6.6.5 순차적 포커스 탐색
      6. 6.6.6 포커스 관리 API
      7. 6.6.7 autofocus 속성
    7. 6.7 키보드 단축키 할당
      1. 6.7.1 소개
      2. 6.7.2 accesskey 속성
      3. 6.7.3 처리 모델
    8. 6.8 편집
      1. 6.8.1 문서 영역을 편집 가능하게 만들기: contenteditable 속성
      2. 6.8.2 전체 문서를 편집 가능하게 만들기: designMode 접근자 및 설정자
      3. 6.8.3 페이지 내 편집기를 위한 모범 사례
      4. 6.8.4 편집 API
      5. 6.8.5 맞춤법 및 문법 검사
      6. 6.8.6 쓰기 제안
      7. 6.8.7 자동 대문자화
      8. 6.8.8 입력 방식: inputmode 속성
      9. 6.8.9 입력 방식: enterkeyhint 속성
    9. 6.9 페이지 내 찾기
      1. 6.9.1 소개
      2. 6.9.2 detailshidden=until-found와의 상호작용
      3. 6.9.3 선택과의 상호작용
    10. 6.10 닫기 요청 및 닫기 감시자
      1. 6.10.1 닫기 요청
      2. 6.10.2 닫기 감시자 인프라
      3. 6.10.3 CloseWatcher 인터페이스
    11. 6.11 드래그 앤 드롭
      1. 6.11.1 소개
      2. 6.11.2 드래그 데이터 저장소
      3. 6.11.3 DataTransfer 인터페이스
        1. 6.11.3.1 DataTransferItemList 인터페이스
        2. 6.11.3.2 DataTransferItem 인터페이스
      4. 6.11.4 DragEvent 인터페이스
      5. 6.11.5 처리 모델
      6. 6.11.6 이벤트 요약
      7. 6.11.7 draggable 속성
      8. 6.11.8 드래그 앤 드롭 모델의 보안 위험
    12. 6.12 popover 속성
      1. 6.12.1 popover 타겟 속성
      2. 6.12.2 Popover 가벼운 해제
  7. 7 웹 페이지 로드
    1. 7.1 지원 개념
      1. 7.1.1 원점
        1. 7.1.1.1 사이트
        2. 7.1.1.2 동일 출처 제한 완화
      2. 7.1.2 원점별 에이전트 클러스터
      3. 7.1.3 크로스 오리진 오프너 정책
        1. 7.1.3.1 헤더
        2. 7.1.3.2 크로스 오리진 오프너 정책에 따른 브라우징 컨텍스트 그룹 전환
        3. 7.1.3.3 보고
      4. 7.1.4 크로스 오리진 임베더 정책
        1. 7.1.4.1 헤더
        2. 7.1.4.2 임베더 정책 검사
      5. 7.1.5 샌드박싱
      6. 7.1.6 정책 컨테이너
    2. 7.2 탐색 및 세션 기록 관련 API
      1. 7.2.1 Window, WindowProxy, Location 객체에 대한 보안 인프라
        1. 7.2.1.1 IDL과의 통합
        2. 7.2.1.2 공유 내부 슬롯: [[CrossOriginPropertyDescriptorMap]]
        3. 7.2.1.3 공유 추상 연산
          1. 7.2.1.3.1 CrossOriginProperties ( O )
          2. 7.2.1.3.2 CrossOriginPropertyFallback ( P )
          3. 7.2.1.3.3 IsPlatformObjectSameOrigin ( O )
          4. 7.2.1.3.4 CrossOriginGetOwnPropertyHelper ( O, P )
          5. 7.2.1.3.5 CrossOriginGet ( O, P, Receiver )
          6. 7.2.1.3.6 CrossOriginSet ( O, P, V, Receiver )
          7. 7.2.1.3.7 CrossOriginOwnPropertyKeys ( O )
      2. 7.2.2 Window 객체
        1. 7.2.2.1 창 열기 및 닫기
        2. 7.2.2.2 Window 객체에서 인덱싱된 접근
        3. 7.2.2.3 Window 객체의 이름별 접근
        4. 7.2.2.4 관련 창에 접근하기
        5. 7.2.2.5 역사적인 브라우저 인터페이스 요소 API
        6. 7.2.2.6 Window 객체에 대한 스크립트 설정
      3. 7.2.3 WindowProxy 이색 객체
        1. 7.2.3.1 [[GetPrototypeOf]] ( )
        2. 7.2.3.2 [[SetPrototypeOf]] ( V )
        3. 7.2.3.3 [[IsExtensible]] ( )
        4. 7.2.3.4 [[PreventExtensions]] ( )
        5. 7.2.3.5 [[GetOwnProperty]] ( P )
        6. 7.2.3.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.2.3.7 [[Get]] ( P, Receiver )
        8. 7.2.3.8 [[Set]] ( P, V, Receiver )
        9. 7.2.3.9 [[Delete]] ( P )
        10. 7.2.3.10 [[OwnPropertyKeys]] ( )
      4. 7.2.4 Location 인터페이스
        1. 7.2.4.1 [[GetPrototypeOf]] ( )
        2. 7.2.4.2 [[SetPrototypeOf]] ( V )
        3. 7.2.4.3 [[IsExtensible]] ( )
        4. 7.2.4.4 [[PreventExtensions]] ( )
        5. 7.2.4.5 [[GetOwnProperty]] ( P )
        6. 7.2.4.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.2.4.7 [[Get]] ( P, Receiver )
        8. 7.2.4.8 [[Set]] ( P, V, Receiver )
        9. 7.2.4.9 [[Delete]] ( P )
        10. 7.2.4.10 [[OwnPropertyKeys]] ( )
      5. 7.2.5 History 인터페이스
      6. 7.2.6 탐색 API
        1. 7.2.6.1 소개
        2. 7.2.6.2 Navigation 인터페이스
        3. 7.2.6.3 핵심 인프라
        4. 7.2.6.4 항목 목록 초기화 및 업데이트
        5. 7.2.6.5 NavigationHistoryEntry 인터페이스
        6. 7.2.6.6 기록 항목 목록
        7. 7.2.6.7 탐색 시작
        8. 7.2.6.8 진행 중인 탐색 추적
        9. 7.2.6.9 NavigationActivation 인터페이스
        10. 7.2.6.10 navigate 이벤트
          1. 7.2.6.10.1 NavigateEvent 인터페이스
          2. 7.2.6.10.2 NavigationDestination 인터페이스
          3. 7.2.6.10.3 이벤트 발생
          4. 7.2.6.10.4 스크롤 및 포커스 동작
      7. 7.2.7 이벤트 인터페이스
        1. 7.2.7.1 NavigationCurrentEntryChangeEvent 인터페이스
        2. 7.2.7.2 PopStateEvent 인터페이스
        3. 7.2.7.3 HashChangeEvent 인터페이스
        4. 7.2.7.4 PageSwapEvent 인터페이스
        5. 7.2.7.5 PageRevealEvent 인터페이스
        6. 7.2.7.6 PageTransitionEvent 인터페이스
        7. 7.2.7.7 BeforeUnloadEvent 인터페이스
      8. 7.2.8 NotRestoredReasons 인터페이스
    3. 7.3 문서 시퀀스를 위한 인프라
      1. 7.3.1 탐색 가능 항목
        1. 7.3.1.1 트래버서블 탐색 가능 항목
        2. 7.3.1.2 최상위 트래버서블
        3. 7.3.1.3 하위 탐색 가능 항목
        4. 7.3.1.4 제이크 다이어그램
        5. 7.3.1.5 관련 탐색 가능 컬렉션
        6. 7.3.1.6 탐색 가능 항목 제거
        7. 7.3.1.7 탐색 가능 타겟 이름
      2. 7.3.2 브라우징 컨텍스트
        1. 7.3.2.1 브라우징 컨텍스트 생성
        2. 7.3.2.2 관련 브라우징 컨텍스트
        3. 7.3.2.3 브라우징 컨텍스트 그룹화
      3. 7.3.3 완전히 활성화된 문서
    4. 7.4 탐색 및 세션 기록
      1. 7.4.1 세션 기록
        1. 7.4.1.1 세션 기록 항목
        2. 7.4.1.2 문서 상태
        3. 7.4.1.3 세션 기록의 중앙화된 수정
        4. 7.4.1.4 세션 기록에 대한 저수준 작업
      2. 7.4.2 탐색
        1. 7.4.2.1 지원 개념
        2. 7.4.2.2 탐색 시작
        3. 7.4.2.3 탐색 종료
          1. 7.4.2.3.1 일반적인 크로스 도큐멘트 탐색 케이스
          2. 7.4.2.3.2 javascript: URL 특별 케이스
          3. 7.4.2.3.3 조각 탐색
          4. 7.4.2.3.4 비 페치 스킴 및 외부 소프트웨어
        4. 7.4.2.4 탐색 방지
        5. 7.4.2.5 탐색 중단
      3. 7.4.3 다시 로드 및 트래버싱
      4. 7.4.4 비조각 동기화 "탐색"
      5. 7.4.5 세션 기록 항목 채우기
      6. 7.4.6 기록 단계를 적용
        1. 7.4.6.1 트래버서블 업데이트
        2. 7.4.6.2 문서 업데이트
        3. 7.4.6.3 문서 공개
        4. 7.4.6.4 조각으로 스크롤
        5. 7.4.6.5 기록 항목 상태 복원
    5. 7.5 문서 생명주기
      1. 7.5.1 공유 문서 생성 인프라
      2. 7.5.2 HTML 문서 로드
      3. 7.5.3 XML 문서 로드
      4. 7.5.4 텍스트 문서 로드
      5. 7.5.5 multipart/x-mixed-replace 문서 로드
      6. 7.5.6 미디어 문서 로드
      7. 7.5.7 DOM이 없는 인라인 콘텐츠용 문서 로드
      8. 7.5.8 로드 프로세스 완료
      9. 7.5.9 문서 언로드
      10. 7.5.10 문서 삭제
      11. 7.5.11 문서 로드 중단
    6. 7.6 X-Frame-Options 헤더
    7. 7.7 Refresh 헤더
    8. 7.8 브라우저 사용자 인터페이스 고려사항
  8. 8 웹 애플리케이션 API
    1. 8.1 스크립팅
      1. 8.1.1 소개
      2. 8.1.2 에이전트와 에이전트 클러스터
        1. 8.1.2.1 자바스크립트 에이전트 공식화와의 통합
        2. 8.1.2.2 자바스크립트 에이전트 클러스터 공식화와의 통합
      3. 8.1.3 렐름과 그 대응물
        1. 8.1.3.1 환경
        2. 8.1.3.2 환경 설정 객체
        3. 8.1.3.3 렐름, 설정 객체 및 글로벌 객체
          1. 8.1.3.3.1 엔트리
          2. 8.1.3.3.2 인컴번트
          3. 8.1.3.3.3 현재
          4. 8.1.3.3.4 관련
        4. 8.1.3.4 스크립팅 활성화 및 비활성화
        5. 8.1.3.5 안전한 컨텍스트
      4. 8.1.4 스크립팅 처리 모델
        1. 8.1.4.1 스크립트
        2. 8.1.4.2 스크립트 가져오기
        3. 8.1.4.3 스크립트 생성
        4. 8.1.4.4 스크립트 호출
        5. 8.1.4.5 스크립트 종료
        6. 8.1.4.6 런타임 스크립트 오류
        7. 8.1.4.7 처리되지 않은 프로미스 거부
        8. 8.1.4.8 임포트 맵 파싱 결과
      5. 8.1.5 모듈 지정자 해결
        1. 8.1.5.1 해결 알고리즘
        2. 8.1.5.2 임포트 맵
        3. 8.1.5.3 임포트 맵 처리 모델
      6. 8.1.6 자바스크립트 사양 호스트 훅
        1. 8.1.6.1 HostEnsureCanAddPrivateElement 구현(O)
        2. 8.1.6.2 HostEnsureCanCompileStrings(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg)
        3. 8.1.6.3 HostGetCodeForEval(argument)
        4. 8.1.6.4 HostPromiseRejectionTracker(promise, operation)
        5. 8.1.6.5 HostSystemUTCEpochNanoseconds(global)
        6. 8.1.6.6 자바스크립트 작업과의 통합
          1. 8.1.6.6.1 HostCallJobCallback(callback, V, argumentsList)
          2. 8.1.6.6.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)
          3. 8.1.6.6.3 HostEnqueueGenericJob(job, realm)
          4. 8.1.6.6.4 HostEnqueuePromiseJob(job, realm)
          5. 8.1.6.6.5 HostEnqueueTimeoutJob(job, realm, milliseconds)
          6. 8.1.6.6.6 HostMakeJobCallback(callable)
        7. 8.1.6.7 모듈 관련 호스트 훅
          1. 8.1.6.7.1 HostGetImportMetaProperties(moduleRecord)
          2. 8.1.6.7.2 HostGetSupportedImportAttributes()
          3. 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload)
      7. 8.1.7 이벤트 루프
        1. 8.1.7.1 정의
        2. 8.1.7.2 작업 큐
        3. 8.1.7.3 처리 모델
        4. 8.1.7.4 일반 작업 소스
        5. 8.1.7.5 다른 사양에서 이벤트 루프 처리
      8. 8.1.8 이벤트
        1. 8.1.8.1 이벤트 핸들러
        2. 8.1.8.2 요소, Document 객체 및 Window 객체의 이벤트 핸들러
          1. 8.1.8.2.1 IDL 정의
        3. 8.1.8.3 이벤트 발생
    2. 8.2 WindowOrWorkerGlobalScope 믹스인
    3. 8.3 Base64 유틸리티 메서드
    4. 8.4 동적 마크업 삽입
      1. 8.4.1 입력 스트림 열기
      2. 8.4.2 입력 스트림 닫기
      3. 8.4.3 document.write()
      4. 8.4.4 document.writeln()
    5. 8.5 DOM 파싱 및 직렬화 API
      1. 8.5.1 DOMParser 인터페이스
      2. 8.5.2 안전하지 않은 HTML 파싱 메서드
      3. 8.5.3 HTML 직렬화 메서드
      4. 8.5.4 innerHTML 속성
      5. 8.5.5 outerHTML 속성
      6. 8.5.6 insertAdjacentHTML() 메서드
      7. 8.5.7 createContextualFragment() 메서드
    6. 8.6 타이머
    7. 8.7 마이크로태스크 큐잉
    8. 8.8 사용자 프롬프트
      1. 8.8.1 간단한 대화 상자
      2. 8.8.2 인쇄
    9. 8.9 시스템 상태 및 기능
      1. 8.9.1 Navigator 객체
        1. 8.9.1.1 클라이언트 식별
        2. 8.9.1.2 언어 설정
        3. 8.9.1.3 브라우저 상태
        4. 8.9.1.4 사용자 정의 스킴 핸들러: registerProtocolHandler() 메서드
          1. 8.9.1.4.1 보안 및 개인정보 보호
          2. 8.9.1.4.2 사용자 에이전트 자동화
        5. 8.9.1.5 쿠키
        6. 8.9.1.6 PDF 보기 지원
    10. 8.10 이미지
    11. 8.11 애니메이션 프레임
  9. 9 통신
    1. 9.1 MessageEvent 인터페이스
    2. 9.2 서버 전송 이벤트
      1. 9.2.1 소개
      2. 9.2.2 EventSource 인터페이스
      3. 9.2.3 처리 모델
      4. 9.2.4 `Last-Event-ID` 헤더
      5. 9.2.5 이벤트 스트림 파싱
      6. 9.2.6 이벤트 스트림 해석
      7. 9.2.7 작성 참고 사항
      8. 9.2.8 연결 없는 푸시 및 기타 기능
      9. 9.2.9 가비지 컬렉션
      10. 9.2.10 구현 조언
    3. 9.3 문서 간 메시징
      1. 9.3.1 소개
      2. 9.3.2 보안
        1. 9.3.2.1 작성자
        2. 9.3.2.2 사용자 에이전트
      3. 9.3.3 메시지 게시
    4. 9.4 채널 메시징
      1. 9.4.1 소개
        1. 9.4.1.1 예제
        2. 9.4.1.2 포트를 웹의 객체-능력 모델의 기반으로 사용하기
        3. 9.4.1.3 포트를 서비스 구현 추상의 기반으로 사용하기
      2. 9.4.2 메시지 채널
      3. 9.4.3 메시지 포트
      4. 9.4.4 포트와 가비지 컬렉션
    5. 9.5 다른 브라우징 컨텍스트로 방송하기
  10. 10 웹 워커
    1. 10.1 소개
      1. 10.1.1 범위
      2. 10.1.2 예제
        1. 10.1.2.1 배경 작업으로 수치 계산을 수행하는 워커
        2. 10.1.2.2 JavaScript 모듈을 워커로 사용하기
        3. 10.1.2.3 공유 워커 소개
        4. 10.1.2.4 공유 워커를 사용한 상태 공유
        5. 10.1.2.5 위임
        6. 10.1.2.6 라이브러리 제공
      3. 10.1.3 튜토리얼
        1. 10.1.3.1 전용 워커 생성
        2. 10.1.3.2 전용 워커와의 통신
        3. 10.1.3.3 공유 워커
    2. 10.2 인프라
      1. 10.2.1 전역 스코프
        1. 10.2.1.1 WorkerGlobalScope 공통 인터페이스
        2. 10.2.1.2 전용 워커와 DedicatedWorkerGlobalScope 인터페이스
        3. 10.2.1.3 공유 워커와 SharedWorkerGlobalScope 인터페이스
      2. 10.2.2 이벤트 루프
      3. 10.2.3 워커의 수명
      4. 10.2.4 처리 모델
      5. 10.2.5 런타임 스크립트 오류
      6. 10.2.6 워커 생성
        1. 10.2.6.1 AbstractWorker 믹스인
        2. 10.2.6.2 워커의 스크립트 설정
        3. 10.2.6.3 전용 워커와 Worker 인터페이스
        4. 10.2.6.4 공유 워커와 SharedWorker 인터페이스
      7. 10.2.7 동시 하드웨어 성능
    3. 10.3 워커에서 사용 가능한 API
      1. 10.3.1 스크립트와 라이브러리 가져오기
      2. 10.3.2 WorkerNavigator 인터페이스
      3. 10.3.3 WorkerLocation 인터페이스
  11. 11 워클릿
    1. 11.1 소개
      1. 11.1.1 동기
      2. 11.1.2 코드 아이템포턴스
      3. 11.1.3 추측 평가
    2. 11.2 예시
      1. 11.2.1 스크립트 로딩
      2. 11.2.2 클래스 등록 및 메서드 호출
    3. 11.3 인프라스트럭처
      1. 11.3.1 전역 범위
        1. 11.3.1.1 에이전트 및 이벤트 루프
        2. 11.3.1.2 생성 및 종료
        3. 11.3.1.3 워클릿 스크립트 설정
      2. 11.3.2 Worklet 클래스
      3. 11.3.3 워클릿의 수명
  12. 12 웹 스토리지
    1. 12.1 소개
    2. 12.2 API
      1. 12.2.1 Storage 인터페이스
      2. 12.2.2 sessionStorage getter
      3. 12.2.3 localStorage getter
      4. 12.2.4 StorageEvent 인터페이스
    3. 12.3 프라이버시
      1. 12.3.1 사용자 추적
      2. 12.3.2 데이터 민감도
    4. 12.4 보안
      1. 12.4.1 DNS 스푸핑 공격
      2. 12.4.2 교차 디렉토리 공격
      3. 12.4.3 구현 리스크
  13. 13 HTML 문법
    1. 13.1 HTML 문서 작성
      1. 13.1.1 DOCTYPE
      2. 13.1.2 요소
        1. 13.1.2.1 시작 태그
        2. 13.1.2.2 종료 태그
        3. 13.1.2.3 속성
        4. 13.1.2.4 선택적 태그
        5. 13.1.2.5 콘텐츠 모델에 대한 제한
        6. 13.1.2.6 원시 텍스트 및 이스케이프 가능한 원시 텍스트 요소 내용에 대한 제한
      3. 13.1.3 텍스트
        1. 13.1.3.1 줄바꿈
      4. 13.1.4 문자 참조
      5. 13.1.5 CDATA 섹션
      6. 13.1.6 주석
    2. 13.2 HTML 문서 파싱
      1. 13.2.1 파싱 모델 개요
      2. 13.2.2 파싱 오류
      3. 13.2.3 입력 바이트 스트림
        1. 13.2.3.1 알려진 문자 인코딩으로 파싱
        2. 13.2.3.2 문자 인코딩 결정
        3. 13.2.3.3 문자 인코딩
        4. 13.2.3.4 파싱 중 인코딩 변경
        5. 13.2.3.5 입력 스트림 전처리
      4. 13.2.4 파싱 상태
        1. 13.2.4.1 삽입 모드
        2. 13.2.4.2 열린 요소의 스택
        3. 13.2.4.3 활성 포맷 요소 목록
        4. 13.2.4.4 요소 포인터
        5. 13.2.4.5 기타 파싱 상태 플래그
      5. 13.2.5 토큰화
        1. 13.2.5.1 데이터 상태
        2. 13.2.5.2 RCDATA 상태
        3. 13.2.5.3 RAWTEXT 상태
        4. 13.2.5.4 스크립트 데이터 상태
        5. 13.2.5.5 PLAINTEXT 상태
        6. 13.2.5.6 태그 열기 상태
        7. 13.2.5.7 종료 태그 열기 상태
        8. 13.2.5.8 태그 이름 상태
        9. 13.2.5.9 RCDATA 미만 기호 상태
        10. 13.2.5.10 RCDATA 종료 태그 열기 상태
        11. 13.2.5.11 RCDATA 종료 태그 이름 상태
        12. 13.2.5.12 RAWTEXT 미만 기호 상태
        13. 13.2.5.13 RAWTEXT 종료 태그 열기 상태
        14. 13.2.5.14 RAWTEXT 종료 태그 이름 상태
        15. 13.2.5.15 스크립트 데이터 미만 기호 상태
        16. 13.2.5.16 스크립트 데이터 종료 태그 열기 상태
        17. 13.2.5.17 스크립트 데이터 종료 태그 이름 상태
        18. 13.2.5.18 스크립트 데이터 이스케이프 시작 상태
        19. 13.2.5.19 스크립트 데이터 이스케이프 시작 대시 상태
        20. 13.2.5.20 스크립트 데이터 이스케이프 상태
        21. 13.2.5.21 스크립트 데이터 이스케이프 대시 상태
        22. 13.2.5.22 스크립트 데이터 이스케이프 대시 대시 상태
        23. 13.2.5.23 스크립트 데이터 이스케이프 미만 기호 상태
        24. 13.2.5.24 스크립트 데이터 이스케이프 종료 태그 열기 상태
        25. 13.2.5.25 스크립트 데이터 이스케이프 종료 태그 이름 상태
        26. 13.2.5.26 스크립트 데이터 이중 이스케이프 시작 상태
        27. 13.2.5.27 스크립트 데이터 이중 이스케이프 상태
        28. 13.2.5.28 스크립트 데이터 이중 이스케이프 대시 상태
        29. 13.2.5.29 스크립트 데이터 이중 이스케이프 대시 대시 상태
        30. 13.2.5.30 스크립트 데이터 이중 이스케이프 미만 기호 상태
        31. 13.2.5.31 스크립트 데이터 이중 이스케이프 종료 상태
        32. 13.2.5.32 속성 이름 이전 상태
        33. 13.2.5.33 속성 이름 상태
        34. 13.2.5.34 속성 이름 이후 상태
        35. 13.2.5.35 속성 값 이전 상태
        36. 13.2.5.36 속성 값 (큰따옴표) 상태
        37. 13.2.5.37 속성 값 (작은따옴표) 상태
        38. 13.2.5.38 속성 값 (따옴표 없음) 상태
        39. 13.2.5.39 속성 값 이후 (따옴표 있음) 상태
        40. 13.2.5.40 자가 종료 시작 태그 상태
        41. 13.2.5.41 가짜 주석 상태
        42. 13.2.5.42 마크업 선언 열기 상태
        43. 13.2.5.43 주석 시작 상태
        44. 13.2.5.44 주석 시작 대시 상태
        45. 13.2.5.45 주석 상태
        46. 13.2.5.46 주석 미만 기호 상태
        47. 13.2.5.47 주석 미만 기호 느낌표 상태
        48. 13.2.5.48 주석 미만 기호 느낌표 대시 상태
        49. 13.2.5.49 주석 미만 기호 느낌표 대시 대시 상태
        50. 13.2.5.50 주석 종료 대시 상태
        51. 13.2.5.51 주석 종료 상태
        52. 13.2.5.52 주석 종료 느낌표 상태
        53. 13.2.5.53 DOCTYPE 상태
        54. 13.2.5.54 DOCTYPE 이름 이전 상태
        55. 13.2.5.55 DOCTYPE 이름 상태
        56. 13.2.5.56 DOCTYPE 이름 이후 상태
        57. 13.2.5.57 DOCTYPE 공개 키워드 이후 상태
        58. 13.2.5.58 DOCTYPE 공개 식별자 이전 상태
        59. 13.2.5.59 DOCTYPE 공개 식별자 (큰따옴표) 상태
        60. 13.2.5.60 DOCTYPE 공개 식별자 (작은따옴표) 상태
        61. 13.2.5.61 DOCTYPE 공개 식별자 이후 상태
        62. 13.2.5.62 DOCTYPE 공개 및 시스템 식별자 사이 상태
        63. 13.2.5.63 DOCTYPE 시스템 키워드 이후 상태
        64. 13.2.5.64 DOCTYPE 시스템 식별자 이전 상태
        65. 13.2.5.65 DOCTYPE 시스템 식별자 (큰따옴표) 상태
        66. 13.2.5.66 DOCTYPE 시스템 식별자 (작은따옴표) 상태
        67. 13.2.5.67 DOCTYPE 시스템 식별자 이후 상태
        68. 13.2.5.68 가짜 DOCTYPE 상태
        69. 13.2.5.69 CDATA 섹션 상태
        70. 13.2.5.70 CDATA 섹션 대괄호 상태
        71. 13.2.5.71 CDATA 섹션 종료 상태
        72. 13.2.5.72 문자 참조 상태
        73. 13.2.5.73 명명된 문자 참조 상태
        74. 13.2.5.74 모호한 앰퍼샌드 상태
        75. 13.2.5.75 숫자 문자 참조 상태
        76. 13.2.5.76 16진수 문자 참조 시작 상태
        77. 13.2.5.77 10진수 문자 참조 시작 상태
        78. 13.2.5.78 16진수 문자 참조 상태
        79. 13.2.5.79 10진수 문자 참조 상태
        80. 13.2.5.80 숫자 문자 참조 종료 상태
      6. 13.2.6 트리 구성
        1. 13.2.6.1 노드 생성 및 삽입
        2. 13.2.6.2 텍스트만 포함하는 요소 파싱
        3. 13.2.6.3 암시적 종료 태그가 있는 요소 닫기
        4. 13.2.6.4 HTML 콘텐츠에서 토큰을 파싱하는 규칙
          1. 13.2.6.4.1 "초기" 삽입 모드
          2. 13.2.6.4.2 "html 이전" 삽입 모드
          3. 13.2.6.4.3 "head 이전" 삽입 모드
          4. 13.2.6.4.4 "head에서" 삽입 모드
          5. 13.2.6.4.5 "head noscript에서" 삽입 모드
          6. 13.2.6.4.6 "head 이후" 삽입 모드
          7. 13.2.6.4.7 "body에서" 삽입 모드
          8. 13.2.6.4.8 "텍스트" 삽입 모드
          9. 13.2.6.4.9 "테이블에서" 삽입 모드
          10. 13.2.6.4.10 "테이블 텍스트에서" 삽입 모드
          11. 13.2.6.4.11 "캡션에서" 삽입 모드
          12. 13.2.6.4.12 "컬럼 그룹에서" 삽입 모드
          13. 13.2.6.4.13 "테이블 본문에서" 삽입 모드
          14. 13.2.6.4.14 "행에서" 삽입 모드
          15. 13.2.6.4.15 "셀에서" 삽입 모드
          16. 13.2.6.4.16 "선택에서" 삽입 모드
          17. 13.2.6.4.17 "테이블에서 선택" 삽입 모드
          18. 13.2.6.4.18 "템플릿에서" 삽입 모드
          19. 13.2.6.4.19 "body 이후" 삽입 모드
          20. 13.2.6.4.20 "프레임셋에서" 삽입 모드
          21. 13.2.6.4.21 "프레임셋 이후" 삽입 모드
          22. 13.2.6.4.22 "body 이후 이후" 삽입 모드
          23. 13.2.6.4.23 "프레임셋 이후 이후" 삽입 모드
        5. 13.2.6.5 외국 콘텐츠에서 토큰을 파싱하는 규칙
      7. 13.2.7 종료
      8. 13.2.8 사전 HTML 파싱
      9. 13.2.9 HTML DOM을 정보 집합으로 강제 변환
      10. 13.2.10 파서에서의 오류 처리 및 이상한 경우에 대한 소개
        1. 13.2.10.1 잘못 중첩된 태그: <b><i></b></i>
        2. 13.2.10.2 잘못 중첩된 태그: <b><p></b></p>
        3. 13.2.10.3 테이블에서 예상치 못한 마크업
        4. 13.2.10.4 파싱 중 페이지를 수정하는 스크립트
        5. 13.2.10.5 여러 문서에서 이동 중인 스크립트 실행
        6. 13.2.10.6 닫히지 않은 포맷 요소
    3. 13.3 HTML 조각 직렬화
    4. 13.4 HTML 조각 파싱
    5. 13.5 명명된 문자 참조
  14. 14 XML 문법
    1. 14.1 XML 문법으로 문서 작성하기
    2. 14.2 XML 문서 구문 분석
    3. 14.3 XML 조각 직렬화
    4. 14.4 XML 조각 구문 분석
  15. 15 렌더링
    1. 15.1 소개
    2. 15.2 CSS 사용자 에이전트 스타일 시트와 프레젠테이션 힌트
    3. 15.3 대체되지 않는 요소
      1. 15.3.1 숨겨진 요소
      2. 15.3.2 페이지
      3. 15.3.3 흐름 콘텐츠
      4. 15.3.4 구문 콘텐츠
      5. 15.3.5 양방향 텍스트
      6. 15.3.6 섹션 및 제목
      7. 15.3.7 목록
      8. 15.3.8
      9. 15.3.9 여백 병합 특성
      10. 15.3.10 양식 컨트롤
      11. 15.3.11 hr 요소
      12. 15.3.12 fieldsetlegend 요소
    4. 15.4 대체된 요소
      1. 15.4.1 포함된 콘텐츠
      2. 15.4.2 이미지
      3. 15.4.3 포함된 콘텐츠 및 이미지의 속성
      4. 15.4.4 이미지 맵
    5. 15.5 위젯
      1. 15.5.1 기본 모양
      2. 15.5.2 쓰기 모드
      3. 15.5.3 버튼 레이아웃
      4. 15.5.4 button 요소
      5. 15.5.5 detailssummary 요소
      6. 15.5.6 텍스트 입력 위젯으로서의 input 요소
      7. 15.5.7 도메인 특정 위젯으로서의 input 요소
      8. 15.5.8 범위 제어로서의 input 요소
      9. 15.5.9 색상 선택으로서의 input 요소
      10. 15.5.10 체크박스 및 라디오 버튼 위젯으로서의 input 요소
      11. 15.5.11 파일 업로드 컨트롤로서의 input 요소
      12. 15.5.12 버튼으로서의 input 요소
      13. 15.5.13 marquee 요소
      14. 15.5.14 meter 요소
      15. 15.5.15 progress 요소
      16. 15.5.16 select 요소
      17. 15.5.17 textarea 요소
    6. 15.6 프레임 및 프레임셋
    7. 15.7 대화형 미디어
      1. 15.7.1 링크, 양식 및 탐색
      2. 15.7.2 title 속성
      3. 15.7.3 호스트 편집
      4. 15.7.4 네이티브 사용자 인터페이스에 렌더링된 텍스트
    8. 15.8 인쇄 미디어
    9. 15.9 스타일이 적용되지 않은 XML 문서
  16. 16 사용 중단된 기능
    1. 16.1 사용 중단되었지만 준수하는 기능
      1. 16.1.1 사용 중단되었지만 준수하는 기능에 대한 경고
    2. 16.2 준수하지 않는 기능
    3. 16.3 구현 요구사항
      1. 16.3.1 marquee 요소
      2. 16.3.2 프레임
      3. 16.3.3 기타 요소, 속성 및 API
  17. 17 IANA 고려사항
    1. 17.1 text/html
    2. 17.2 multipart/x-mixed-replace
    3. 17.3 application/xhtml+xml
    4. 17.4 text/ping
    5. 17.5 application/microdata+json
    6. 17.6 text/event-stream
    7. 17.7 web+ 접두사 스킴
  18. 색인
    1. 요소
    2. 요소 내용 범주
    3. 속성
    4. 요소 인터페이스
    5. 모든 인터페이스
    6. 이벤트
    7. HTTP 헤더
    8. MIME 타입
  19. 참고 문헌
  20. 감사의 글
  21. 지적 재산권

1 소개

1.1 이 명세는 어디에 적합합니까?

이 명세는 웹 플랫폼의 큰 부분을 상세하게 정의합니다. 다른 명세들과의 관계에서 이 명세의 위치를 다음과 같이 요약할 수 있습니다:

CSS SVG MathML 서비스 워커 IDB Fetch CSP AV1 Opus PNG 이 명세서 HTTP TLS DOM Unicode Web IDL MIME URL XML JavaScript Encoding

1.2 이것이 HTML5인가요?

이 섹션은 비규범적입니다.

간단히 말하면: 네.

좀 더 길게 설명하자면: "HTML5"라는 용어는 현대 웹 기술을 지칭하는 유행어로 널리 사용됩니다. 이들 중 많은 부분이 (물론 전부는 아니지만) WHATWG에서 개발되었습니다. 이 문서는 그런 문서 중 하나입니다. 다른 문서는 WHATWG 표준 개요에서 확인할 수 있습니다.

1.3 배경

이 섹션은 비규범적입니다.

HTML은 월드 와이드 웹의 핵심 마크업 언어입니다. 원래 HTML은 과학 문서를 의미론적으로 설명하기 위한 언어로 설계되었습니다. 그러나 그 일반적인 설계는 시간이 지나면서 여러 종류의 문서 및 심지어 응용 프로그램을 설명할 수 있도록 적응되었습니다.

1.4 대상 독자

이 섹션은 비규범적입니다.

이 명세서는 이 명세서에 정의된 기능을 사용하는 문서와 스크립트의 작성자, 이 명세서에 정의된 기능을 사용하는 페이지에서 작동하는 도구의 구현자, 그리고 이 명세서의 요구 사항에 따라 문서 또는 구현의 정확성을 확인하려는 사람들을 대상으로 합니다.

이 문서는 웹 기술에 대한 최소한의 기본 지식이 없는 독자에게는 적합하지 않을 수 있습니다. 일부 내용은 명확성을 희생하고 정확성을 위해, 또는 완전성을 위해 간결성을 희생하기 때문입니다. 더 다가가기 쉬운 튜토리얼과 저술 가이드가 주제를 더 부드럽게 소개할 수 있습니다.

특히, 이 명세서의 기술적인 부분을 완전히 이해하려면 DOM 기본에 대한 친숙함이 필요합니다. Web IDL, HTTP, XML, 유니코드, 문자 인코딩, 자바스크립트, CSS에 대한 이해도 일부에서는 도움이 되지만 필수는 아닙니다.

1.5 범위

이 섹션은 비규범적입니다.

이 명세서는 정적 문서부터 동적 응용 프로그램에 이르는 접근 가능한 페이지를 작성하기 위한 의미 수준의 마크업 언어 및 관련 의미 수준의 스크립팅 API를 제공하는 것으로 제한됩니다.

이 명세서의 범위에는 프레젠테이션의 매체별 사용자 정의를 제공하는 메커니즘이 포함되지 않습니다(웹 브라우저의 기본 렌더링 규칙은 이 명세서의 끝에 포함되어 있으며, 언어의 일부로서 CSS에 연결하는 몇 가지 메커니즘이 제공됩니다).

이 명세서의 범위는 전체 운영 체제를 설명하는 것이 아닙니다. 특히, 하드웨어 구성 소프트웨어, 이미지 편집 도구, 고급 워크스테이션에서 사용자가 매일 사용하는 응용 프로그램은 범위에 포함되지 않습니다. 응용 프로그램의 경우, 이 명세서는 사용자가 가끔 또는 다양한 위치에서 정기적으로 사용할 것으로 예상되며, 낮은 CPU 요구 사항을 가지는 응용 프로그램을 대상으로 합니다. 이러한 응용 프로그램의 예로는 온라인 구매 시스템, 검색 시스템, 게임(특히 멀티플레이어 온라인 게임), 공개 전화번호부 또는 주소록, 통신 소프트웨어(이메일 클라이언트, 인스턴트 메시징 클라이언트, 토론 소프트웨어), 문서 편집 소프트웨어 등이 있습니다.

1.6 역사

이 섹션은 비규범적입니다.

HTML은 첫 5년(1990-1995) 동안 여러 번의 개정을 거쳤고, 주로 처음에는 CERN에서, 이후에는 IETF에서 여러 확장을 경험했습니다.

W3C의 창립과 함께, HTML의 개발은 다시 장소를 옮겼습니다. 1995년 HTML 3.0으로 알려진 HTML 확장의 첫 시도가 중단된 후, 1997년에 완료된 보다 실용적인 접근 방식인 HTML 3.2로 이어졌습니다. 같은 해 말 HTML4가 빠르게 뒤따랐습니다.

그 다음 해, W3C 회원들은 HTML의 진화를 중단하고 XML 기반의 동등한 표현인 XHTML의 작업을 시작하기로 결정했습니다. 이 작업은 새 직렬화만 추가된 HTML4의 XML 재구성인 XHTML 1.0으로 시작되었으며, 2000년에 완료되었습니다. XHTML 1.0 이후, W3C는 XHTML 모듈화라는 배너 아래 다른 작업 그룹이 XHTML을 확장하기 쉽게 만드는 데 초점을 맞추었습니다. 이와 동시에, W3C는 이전의 HTML 및 XHTML 언어와 호환되지 않는 새로운 언어를 개발하는 작업도 진행했으며, 이를 XHTML2라고 불렀습니다.

1998년 HTML의 진화가 중단된 시점에, 브라우저 벤더에 의해 개발된 HTML의 일부 API가 DOM Level 1(1998년)이라는 이름으로 지정되어 공개되었고, DOM Level 2 Core 및 DOM Level 2 HTML(2000년 시작하여 2003년에 완성됨)로 이어졌습니다. 이러한 노력은 이후 일부 DOM Level 3 명세가 2004년에 발표되었지만, Level 3 초안이 모두 완료되기 전에 작업 그룹이 종료되면서 점차 사라졌습니다.

2003년, 차세대 웹 양식으로 자리 잡은 기술인 XForms의 발표는 HTML 자체를 발전시키려는 새로운 관심을 불러일으켰습니다. 이 관심은 XML이 웹 기술로서 기존 배포된 기술(예: HTML)을 대체하기보다는 완전히 새로운 기술(예: RSS 및 이후의 Atom)로서만 제한적으로 배포된다는 인식에서 비롯되었습니다.

XForms 1.0이 도입한 많은 기능을 브라우저가 기존 HTML 웹 페이지와 호환되지 않는 렌더링 엔진을 구현하지 않고도 제공할 수 있도록 HTML4의 양식을 확장할 수 있다는 것을 보여주는 개념 증명이 이 새로운 관심의 첫 결과였습니다. 이 초기 단계에서 초안은 이미 공개적으로 사용 가능했으며, 모든 출처로부터 입력을 이미 요청받고 있었지만, 명세는 오페라 소프트웨어의 저작권 하에 있었습니다.

HTML의 진화가 다시 열려야 한다는 생각은 2004년 W3C 워크숍에서 테스트되었으며, 그 자리에서 HTML5 작업을 뒷받침하는 몇 가지 원칙(아래에 설명됨)과 이전에 언급된 양식 관련 기능만을 다룬 초기 초안 제안서가 모질라와 오페라에 의해 W3C에 공동으로 제시되었습니다. 제안서는 웹의 진화에 대해 이전에 선택된 방향과 충돌한다는 이유로 거부되었습니다. W3C 직원과 회원들은 XML 기반 대체 기술을 계속 개발하기로 투표했습니다.

그 후 얼마 지나지 않아 Apple, Mozilla, Opera는 WHATWG라는 새로운 장소에서 작업을 계속할 의도를 공동으로 발표했습니다. 공개 메일링 리스트가 만들어졌고, 초안은 WHATWG 사이트로 이동되었습니다. 저작권은 이후 세 벤더가 공동으로 소유하고, 명세의 재사용을 허용하도록 수정되었습니다.

WHATWG는 특히 기술이 이전 버전과 호환되어야 한다는 원칙, 명세와 구현이 일치해야 하며 이를 위해 명세를 변경해야 한다면 그렇게 해야 한다는 원칙, 그리고 명세가 구현이 상호 운용성을 완전히 달성할 수 있도록 충분히 상세해야 한다는 원칙에 기반을 두고 있었습니다.

특히 마지막 요구 사항은 HTML5 명세의 범위에 이전에 세 개의 별도 문서로 지정되었던 HTML4, XHTML1, DOM2 HTML이 포함되어야 한다는 것을 의미했습니다. 또한 이전에는 표준으로 간주되지 않았던 것보다 훨씬 더 많은 세부 사항을 포함해야 한다는 것을 의미했습니다.

2006년 W3C는 결국 HTML5 개발에 참여할 의향을 나타냈고, 2007년 WHATWG와 협력하여 HTML5 명세를 개발하기 위해 작업 그룹을 구성했습니다. Apple, Mozilla, Opera는 W3C가 W3C 저작권 하에 명세를 게시할 수 있도록 허용하면서도, WHATWG 사이트에 제한이 적은 라이선스를 가진 버전을 유지했습니다.

수년간 두 그룹은 함께 작업했습니다. 그러나 2011년, 두 그룹은 목표가 다르다는 결론에 도달했습니다: W3C는 "완성된" 버전의 "HTML5"를 발표하기를 원했지만, WHATWG는 계속해서 HTML의 현행 표준을 작업하여 명세를 동결하지 않고, 문제를 수정하며, 필요에 따라 새로운 기능을 추가하여 플랫폼을 발전시키고자 했습니다.

2019년 WHATWG와 W3C는 협력 계약을 체결하여 앞으로 HTML의 단일 버전으로 협력하기로 합의했습니다: 이 문서가 그것입니다.

1.7 디자인 노트

이 섹션은 비규범적입니다.

HTML의 많은 측면이 처음에는 비합리적이고 일관성이 없는 것처럼 보인다는 점을 인정해야 합니다.

HTML, 이를 지원하는 DOM API, 그리고 많은 지원 기술들은 여러 우선순위를 가진 다양한 사람들이 수십 년에 걸쳐 개발한 것이며, 많은 경우 서로의 존재를 알지 못했습니다.

따라서 여러 출처에서 기능이 발생했으며, 항상 일관되게 설계된 것은 아닙니다. 더욱이 웹의 독특한 특성으로 인해, 구현 버그가 실제로 사실상의 표준이 되었고, 이제는 공식적인 표준이 되었으며, 이는 콘텐츠가 수정되기 전에 의도치 않게 이러한 버그에 의존하여 작성되었기 때문입니다.

이 모든 것에도 불구하고 특정 설계 목표를 준수하려는 노력이 있었습니다. 이들은 다음 몇 개의 하위 섹션에서 설명됩니다.

1.7.1 스크립트 실행의 직렬화 가능성

이 섹션은 비규범적입니다.

웹 저자가 멀티스레딩의 복잡성에 노출되지 않도록 HTML과 DOM API는 어떤 스크립트도 다른 스크립트의 동시 실행을 감지할 수 없도록 설계되었습니다. 심지어 워커와 함께 사용하더라도, 모든 글로벌에서 모든 스크립트의 실행을 완전히 직렬화하는 것으로 구현의 동작을 생각할 수 있습니다.

이 일반적인 설계 원칙의 예외는 JavaScript SharedArrayBuffer 클래스입니다. SharedArrayBuffer 객체를 사용하면 다른 에이전트에서 스크립트가 동시에 실행되고 있음을 관찰할 수 있습니다. 또한, JavaScript 메모리 모델로 인해 이러한 스크립트 간의 직렬화된 스크립트 실행뿐만 아니라 직렬화된 실행을 통해서도 나타낼 수 없는 상황이 발생할 수 있습니다.

1.7.2 다른 명세와의 호환성

이 섹션은 비규범적입니다.

이 명세서는 다양한 다른 명세와 상호작용하고 이를 기반으로 합니다. 불행히도, 특정 상황에서는 상충되는 요구로 인해 이 명세서가 다른 명세서의 요구 사항을 위반하게 되었습니다. 이러한 경우, 위반 사항은 각각 "의도적 위반"으로 표시되었으며, 위반 이유가 기록되었습니다.

1.7.3 확장성

이 섹션은 비규범적입니다.

HTML에는 안전한 방식으로 의미를 추가할 수 있는 다양한 확장 메커니즘이 있습니다:

1.8 HTML 대 XML 문법

이 섹션은 비규범적입니다.

이 명세서는 문서와 응용 프로그램을 설명하는 추상 언어와 이 언어를 사용하는 리소스의 메모리 내 표현과 상호작용하기 위한 일부 API를 정의합니다.

메모리 내 표현은 "DOM HTML" 또는 간단히 "DOM"으로 알려져 있습니다.

이 추상 언어를 사용하는 리소스를 전송하는 데 사용할 수 있는 다양한 구체적인 문법이 있으며, 이 명세서에서는 그중 두 가지를 정의합니다.

첫 번째 구체적인 문법은 HTML 문법입니다. 이것은 대부분의 작성자에게 권장되는 형식입니다. 이는 대부분의 기존 웹 브라우저와 호환됩니다. 문서가 text/html MIME 유형으로 전송되면 웹 브라우저에서 HTML 문서로 처리됩니다. 이 명세서는 단순히 "HTML"로 알려진 최신 HTML 문법을 정의합니다.

두 번째 구체적인 문법은 XML입니다. 문서가 XML MIME 유형으로, 예를 들어 application/xhtml+xml로 전송되면, 웹 브라우저에서 XML 문서로 처리되어 XML 프로세서에 의해 파싱됩니다. 작성자는 XML과 HTML의 처리가 다르다는 점을 상기해야 합니다. 특히, 사소한 구문 오류라도 XML로 레이블이 지정된 문서가 완전히 렌더링되는 것을 방지할 수 있지만, HTML 문법에서는 무시될 수 있습니다.

HTML의 XML 문법은 이전에 "XHTML"로 불렸지만, 이 명세서는 이 용어를 사용하지 않습니다(다른 이유 중 하나는 MathML 및 SVG의 HTML 문법에 대해 이러한 용어가 사용되지 않기 때문입니다).

DOM, HTML 문법 및 XML 문법은 동일한 콘텐츠를 모두 표현할 수 없습니다. 예를 들어, 네임스페이스는 HTML 문법을 사용하여 표현할 수 없지만, DOM 및 XML 문법에서는 지원됩니다. 유사하게, noscript 기능을 사용하는 문서는 HTML 문법을 사용하여 표현할 수 있지만, DOM이나 XML 문법으로는 표현할 수 없습니다. "-->" 문자열을 포함하는 주석은 HTML 및 XML 문법에서는 표현할 수 없지만, DOM에서는 표현할 수 있습니다.

1.9 이 명세서의 구조

이 섹션은 비규범적입니다.

이 명세서는 다음과 같은 주요 섹션으로 나뉩니다:

소개
HTML 표준의 배경을 제공하는 비규범적 자료입니다.
공통 인프라
준수 클래스, 알고리즘, 정의, 그리고 명세서의 나머지 부분의 공통 기반을 정의합니다.
HTML 문서의 의미, 구조 및 API
문서는 요소로 구성됩니다. 이 요소들은 DOM을 사용하여 트리를 형성합니다. 이 섹션에서는 이 DOM의 기능을 정의하고 모든 요소에 공통된 기능과 요소를 정의하는 데 사용되는 개념을 소개합니다.
HTML 요소
각 요소에는 미리 정의된 의미가 있으며, 이 섹션에서 설명됩니다. 요소를 사용하는 방법에 대한 작성자 규칙과 각 요소를 처리하는 방법에 대한 사용자 에이전트 요구 사항도 제공됩니다. 여기에는 비디오 재생 및 자막, 폼 컨트롤 및 폼 제출, HTML 캔버스로 알려진 2D 그래픽 API와 같은 HTML의 주요 기능이 포함됩니다.
마이크로데이터
이 명세서는 문서에 기계 판독 가능한 주석을 추가하는 메커니즘을 도입하여 도구가 문서에서 이름-값 쌍의 트리를 추출할 수 있도록 합니다. 이 섹션에서는 이 메커니즘과 HTML 문서를 다른 형식으로 변환하는 데 사용할 수 있는 몇 가지 알고리즘을 설명합니다. 이 섹션에서는 연락처 정보, 캘린더 이벤트 및 라이선스 작업에 대한 몇 가지 샘플 마이크로데이터 어휘도 정의합니다.
사용자 상호작용
HTML 문서는 사용자가 콘텐츠와 상호작용하고 수정할 수 있는 여러 메커니즘을 제공할 수 있으며, 이 섹션에서는 포커스 작동 방식 및 드래그 앤 드롭과 같은 기능을 설명합니다.
웹 페이지 로드
HTML 문서는 진공 상태에 존재하지 않으며, 이 섹션에서는 웹 브라우저와 같이 여러 페이지를 다루는 환경에 영향을 미치는 많은 기능을 정의합니다.
웹 애플리케이션 API
이 섹션에서는 HTML에서 애플리케이션을 스크립팅하는 기본 기능을 소개합니다.
웹 워커
이 섹션에서는 JavaScript의 백그라운드 스레드를 위한 API를 정의합니다.
워크릿
이 섹션에서는 메인 JavaScript 실행 환경과 분리하여 JavaScript를 실행해야 하는 API를 위한 인프라를 정의합니다.
통신 API
이 섹션에서는 HTML로 작성된 애플리케이션이 동일한 클라이언트에서 실행되는 다른 도메인의 애플리케이션과 통신할 수 있는 몇 가지 메커니즘을 설명합니다. 또한 서버 푸시 이벤트 스트림 메커니즘인 Server Sent Events 또는 EventSource와 Web Sockets로 알려진 스크립트를 위한 양방향 풀 듀플렉스 소켓 프로토콜을 소개합니다.
웹 스토리지
이 섹션에서는 이름-값 쌍을 기반으로 한 클라이언트 측 스토리지 메커니즘을 정의합니다.
HTML 문법
XML 문법
이러한 모든 기능이 직렬화된 형식으로 표현되어 다른 사람에게 전송될 수 없다면 무의미할 것입니다. 따라서 이 섹션에서는 HTML 및 XML의 문법과 해당 문법을 사용하여 콘텐츠를 파싱하는 방법에 대한 규칙을 정의합니다.
렌더링
이 섹션에서는 웹 브라우저의 기본 렌더링 규칙을 정의합니다.

또한 폐기된 기능IANA 고려사항을 나열한 부록과 여러 색인이 있습니다.

1.9.1 이 명세서를 읽는 방법

이 명세서는 다른 모든 명세서와 마찬가지로 읽어야 합니다. 먼저, 처음부터 끝까지 여러 번 읽어야 합니다. 그런 다음, 최소한 한 번은 거꾸로 읽어야 합니다. 그 후에는 목차에서 무작위로 섹션을 선택하고 모든 교차 참조를 따라 읽어야 합니다.

아래의 준수 요구 사항 섹션에 설명된 것처럼, 이 명세서는 다양한 준수 클래스에 대한 준수 기준을 설명합니다. 특히, 작성자와 작성된 문서와 같은 생산자에게 적용되는 준수 요구 사항과 웹 브라우저와 같은 소비자에게 적용되는 준수 요구 사항이 있습니다. 이들은 무엇을 요구하는지에 따라 구별할 수 있습니다: 생산자에 대한 요구 사항은 허용되는 것을 명시하고, 소비자에 대한 요구 사항은 소프트웨어가 어떻게 작동해야 하는지를 명시합니다.

예를 들어, "the foo 속성의 값은 유효한 정수여야 한다"는 생산자에 대한 요구 사항입니다. 이는 허용된 값을 명시하기 때문입니다. 반면, "the foo 속성의 값은 정수를 파싱하는 규칙을 사용하여 파싱되어야 한다"는 소비자에 대한 요구 사항입니다. 이는 콘텐츠를 처리하는 방법을 설명합니다.

생산자에 대한 요구 사항은 소비자에게 전혀 영향을 미치지 않습니다.

위의 예를 계속해서, 특정 속성의 값이 유효한 정수로 제한된다는 요구 사항은 소비자에 대한 요구 사항과 전혀 관련이 없습니다. 실제로 소비자는 값이 요구 사항을 준수하는지 여부에 전혀 영향을 받지 않는 불투명한 문자열로 해당 속성을 처리해야 할 수도 있습니다. 또는 (이전 예와 같이) 소비자가 유효하지 않은(이 경우 비숫자) 값을 처리하는 방법을 정의하는 특정 규칙을 사용하여 값을 파싱해야 할 수도 있습니다.

1.9.2 타이포그래픽 규칙

이것은 정의, 요구 사항 또는 설명입니다.

이것은 주석입니다.

이것은 예제입니다.

이것은 열려 있는 이슈입니다.

이것은 경고입니다.

[Exposed=Window]
interface Example {
  // this is an IDL definition
};
variable = object.method([optionalArgument])

이것은 인터페이스의 사용법을 설명하는 작성자에게 주는 참고 사항입니다.

/* this is a CSS fragment */

용어의 정의 인스턴스는 이와 같이 표시됩니다. 해당 용어의 사용은 이와 같이 또는 이와 같이 표시됩니다.

요소, 속성 또는 API의 정의 인스턴스는 이와 같이 표시됩니다. 해당 요소, 속성 또는 API에 대한 참조는 이와 같이 표시됩니다.

다른 코드 조각은 이와 같이 표시됩니다.

변수는 이와 같이 표시됩니다.

알고리즘에서 동기화 섹션의 단계는 ⌛로 표시됩니다.

일부 경우에는 조건과 해당 조건에 적용되는 요구 사항을 포함한 목록의 형태로 요구 사항이 제공됩니다. 이러한 경우 조건에 적용되는 요구 사항은 항상 조건 다음에 나오는 첫 번째 요구 사항 집합이며, 해당 요구 사항에 대해 여러 조건 집합이 있는 경우에도 마찬가지입니다. 이러한 경우는 다음과 같이 표시됩니다:

이것은 조건입니다.
이것은 또 다른 조건입니다.
위 조건에 적용되는 요구 사항입니다.
이것은 세 번째 조건입니다.
세 번째 조건에 적용되는 요구 사항입니다.

1.10 HTML 간단 소개

이 섹션은 비규범적입니다.

기본적인 HTML 문서는 다음과 같습니다:

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Sample page</title>
 </head>
 <body>
  <h1>Sample page</h1>
  <p>This is a <a href="demo.html">simple</a> sample.</p>
  <!-- this is a comment -->
 </body>
</html>

HTML 문서는 요소와 텍스트로 구성된 트리로 이루어져 있습니다. 각 요소는 "<body>"와 같은 시작 태그와 "</body>"와 같은 종료 태그로 소스에서 표시됩니다. (특정 상황에서는 일부 시작 태그와 종료 태그를 생략할 수 있으며, 다른 태그에 의해 암시될 수 있습니다.)

태그는 요소가 서로 겹치지 않고 완전히 다른 요소 안에 포함되도록 중첩되어야 합니다:

<p>This is <em>very <strong>wrong</em>!</strong></p>
<p>This <em>is <strong>correct</strong>.</em></p>

이 명세서는 HTML에서 사용할 수 있는 요소 집합과 요소를 중첩할 수 있는 방법에 대한 규칙을 정의합니다.

요소는 작동 방식을 제어하는 속성을 가질 수 있습니다. 아래 예에서는 하이퍼링크a 요소와 해당 href 속성을 사용하여 생성되었습니다:

<a href="demo.html">simple</a>

속성은 시작 태그 안에 배치되며, 이름으로 구성되며, "=" 문자로 구분됩니다. 속성 값에 ASCII 공백 문자", ', `, =, <, >가 포함되지 않은 경우에는 따옴표를 사용하지 않아도 됩니다. 그렇지 않은 경우, 단일 또는 이중 따옴표를 사용하여 값을 따옴표로 묶어야 합니다. 값이 빈 문자열인 경우 "=" 문자와 함께 값을 생략할 수 있습니다.

<!-- 빈 속성 -->
<input name=address disabled>
<input name=address disabled="">

<!-- 값이 있는 속성 -->
<input name=address maxlength=200>
<input name=address maxlength='200'>
<input name=address maxlength="200">

HTML 사용자 에이전트(예: 웹 브라우저)는 이 마크업을 파싱하여 이를 DOM(문서 객체 모델) 트리로 변환합니다. DOM 트리는 문서의 메모리 내 표현입니다.

DOM 트리는 여러 종류의 노드를 포함하며, 특히 DocumentType 노드, Element 노드, Text 노드, Comment 노드 및 경우에 따라 ProcessingInstruction 노드를 포함합니다.

이 섹션의 위쪽에 있는 마크업 스니펫은 다음과 같은 DOM 트리로 변환됩니다:

이 트리의 문서 요소html 요소이며, HTML 문서에서 항상 이 위치에 나타납니다. 이 요소는 head 요소와 body 요소, 그리고 그 사이의 텍스트 노드를 포함합니다.

DOM 트리에는 예상보다 많은 텍스트 노드가 포함되어 있으며, 소스에는 여러 개의 공백 문자(여기서는 "␣"로 표시)와 줄 바꿈("⏎")이 포함되어 있으며, 이들은 모두 DOM에서 텍스트 노드로 나타납니다. 그러나 역사적 이유로 인해 원본 마크업의 모든 공백 문자와 줄 바꿈이 DOM에 나타나지는 않습니다. 특히 head 시작 태그 이전의 모든 공백 문자는 조용히 삭제되고, body 종료 태그 이후의 모든 공백 문자는 body의 끝에 배치됩니다.

head 요소에는 title 요소가 포함되어 있으며, 이 요소에는 "Sample page"라는 텍스트가 있는 텍스트 노드가 포함되어 있습니다. 유사하게, body 요소에는 h1 요소, p 요소 및 주석이 포함되어 있습니다.


이 DOM 트리는 페이지의 스크립트에서 조작할 수 있습니다. 스크립트(일반적으로 JavaScript로 작성됨)는 script 요소를 사용하거나 이벤트 핸들러 콘텐츠 속성을 사용하여 포함할 수 있는 작은 프로그램입니다. 예를 들어, 여기에서 폼의 output 요소의 값을 "Hello World"로 설정하는 스크립트가 포함된 폼이 있습니다:

<form name="main">
 Result: <output name="result"></output>
 <script>
  document.forms.main.elements.result.value = 'Hello World';
 </script>
</form>

DOM 트리의 각 요소는 객체로 표현되며, 이러한 객체에는 조작할 수 있는 API가 있습니다. 예를 들어, 링크(예: 위 트리의 a 요소)는 "href" 속성을 여러 가지 방법으로 변경할 수 있습니다:

var a = document.links[0]; // 문서에서 첫 번째 링크를 얻습니다
a.href = 'sample.html'; // 링크의 대상 URL을 변경합니다
a.protocol = 'https'; // URL의 스킴 부분만 변경합니다
a.setAttribute('href', 'https://example.com/'); // 콘텐츠 속성을 직접 변경합니다

DOM 트리는 구현이 처리하고 표시할 때(특히 웹 브라우저와 같은 상호작용형 구현에서) HTML 문서를 표현하는 방식으로 사용되기 때문에, 이 명세서는 주로 위에서 설명한 마크업 대신 DOM 트리를 기준으로 작성되었습니다.


HTML 문서는 상호작용 콘텐츠의 매체 독립적인 설명을 나타냅니다. HTML 문서는 화면에 렌더링되거나, 음성 합성기를 통해 읽히거나, 점자 디스플레이에 표시될 수 있습니다. 이러한 렌더링이 정확히 어떻게 이루어지는지에 영향을 미치기 위해, 작성자는 CSS와 같은 스타일링 언어를 사용할 수 있습니다.

다음 예에서는 CSS를 사용하여 페이지가 노란색 배경에 파란색 텍스트로 설정되었습니다.

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Sample styled page</title>
  <style>
   body { background: navy; color: yellow; }
  </style>
 </head>
 <body>
  <h1>Sample styled page</h1>
  <p>This page is just a demo.</p>
 </body>
</html>

HTML을 사용하는 방법에 대한 자세한 내용은 작성자가 튜토리얼과 가이드를 참조할 것을 권장합니다. 이 명세서에 포함된 일부 예제도 유용할 수 있지만, 초보 작성자는 이 명세서가 필요에 따라 정의된 언어를 처음에는 이해하기 어려울 수 있는 수준의 세부 사항으로 정의하고 있다는 점을 유의해야 합니다.

1.10.1 HTML로 보안 애플리케이션 작성하기

이 섹션은 비규범적입니다.

HTML을 사용하여 상호작용 사이트를 만들 때, 공격자가 사이트 자체 또는 사이트 사용자의 무결성을 손상시킬 수 있는 취약점을 도입하지 않도록 주의해야 합니다.

이 문제에 대한 포괄적인 연구는 이 문서의 범위를 벗어나며, 작성자는 이 문제를 더 자세히 연구할 것을 강력히 권장합니다. 그러나 이 섹션에서는 HTML 애플리케이션 개발에서 흔히 발생하는 몇 가지 함정을 간단히 소개하려고 합니다.

웹의 보안 모델은 "출처" 개념을 기반으로 하며, 따라서 웹에서 발생할 수 있는 많은 공격은 교차 출처 작업과 관련이 있습니다. [ORIGIN]

사용자 입력 검증 안 함
크로스 사이트 스크립팅(XSS)
SQL 인젝션

신뢰할 수 없는 입력(예: 텍스트 댓글, URL 매개변수의 값, 타사 사이트의 메시지 등과 같은 사용자 생성 콘텐츠)을 수락할 때는 사용하기 전에 데이터를 검증하고 표시할 때 적절히 이스케이프해야 합니다. 이를 수행하지 않으면 악의적인 사용자가 거짓 사용자 정보 제공(예: 음수 나이와 같은 사소한 것에서부터)부터 정보를 포함하는 페이지를 볼 때마다 스크립트를 실행하여 공격을 전파하는 등의 심각한 공격, 서버의 모든 데이터를 삭제하는 등의 치명적인 공격에 이르기까지 다양한 공격을 수행할 수 있습니다.

사용자 입력을 검증하는 필터를 작성할 때는 항상 허용 목록 기반 필터를 사용하여 알려진 안전한 구문만 허용하고 모든 다른 입력을 허용하지 않도록 해야 합니다. 블랙리스트 기반 필터는 알려진 나쁜 입력을 차단하고 나머지는 모두 허용하는 방식으로는 보안이 보장되지 않습니다. 나쁜 입력 중 일부는 아직 알려지지 않았을 수 있기 때문입니다(예: 미래에 새로운 공격 방식이 발명될 수 있습니다).

예를 들어, URL의 쿼리 문자열을 확인하여 표시할 내용을 결정한 다음, 사이트가 해당 페이지로 사용자를 리디렉션하여 메시지를 표시한다고 가정해 보겠습니다:

<ul>
 <li><a href="message.cgi?say=Hello">Say Hello</a>
 </ul>

메시지가 이스케이프 처리 없이 사용자에게 표시되면, 공격자가 스크립트 요소를 포함하는 URL을 생성할 수 있습니다:

https://example.com/message.cgi?say=%3Cscript%3Ealert%28%27Oh%20no%21%27%29%3C/script%3E

공격자가 피해자인 사용자가 이 페이지를 방문하도록 설득하면, 공격자가 선택한 스크립트가 페이지에서 실행됩니다. 이러한 스크립트는 사이트가 제공하는 것에 따라 무수히 많은 악의적인 작업을 수행할 수 있습니다. 예를 들어, 사이트가 전자 상거래 사이트인 경우, 이러한 스크립트는 사용자가 인지하지 못한 상태에서 임의의 원치 않는 구매를 하도록 만들 수 있습니다.

이것을 크로스 사이트 스크립팅 공격이라고 합니다.

사이트에 코드를 실행하도록 속이기 위해 사용할 수 있는 여러 구문이 있습니다. 작성자는 허용 목록 필터를 작성할 때 다음과 같은 항목을 고려할 것을 권장합니다:

크로스 사이트 요청 위조(CSRF)

사용자가 사용자별 부작용이 있는 폼 제출을 할 수 있는 사이트, 예를 들어 사용자의 이름으로 포럼에 메시지를 게시하거나, 구매를 하거나, 여권을 신청하는 등의 사이트에서는 요청이 사용자가 의도적으로 한 것인지, 아니면 다른 사이트가 사용자를 속여 알지 못하게 요청을 수행하게 한 것인지를 확인하는 것이 중요합니다.

이 문제는 HTML 폼이 다른 출처로 제출될 수 있기 때문에 발생합니다.

사이트는 사용자별 숨겨진 토큰으로 폼을 채우거나 모든 요청에 대해 `Origin` 헤더를 확인하여 이러한 공격을 방지할 수 있습니다.

클릭재킹

사용자가 원하지 않는 작업을 수행하는 인터페이스를 제공하는 페이지는 사용자가 인터페이스를 활성화하도록 속일 수 있는 가능성을 방지하도록 설계해야 합니다.

사용자가 이러한 속임수에 넘어갈 수 있는 한 가지 방법은 악성 사이트가 피해자 사이트를 작은 iframe에 배치한 다음, 사용자가 반응 게임을 하도록 설득하는 것입니다. 사용자가 게임을 하고 있으면 악성 사이트는 사용자가 클릭하려는 순간 iframe을 마우스 커서 아래에 빠르게 위치시켜 사용자가 피해자 사이트의 인터페이스를 클릭하도록 속일 수 있습니다.

이를 방지하기 위해 프레임에서 사용될 것으로 예상하지 않는 사이트는 프레임에 있지 않음을 감지한 경우에만 인터페이스를 활성화하는 것이 좋습니다(예: window 객체를 top 속성의 값과 비교하여 확인).

1.10.2 스크립팅 API를 사용할 때 피해야 할 일반적인 함정

이 섹션은 비규범적입니다.

HTML에서 스크립트는 "완료될 때까지 실행"되는 의미를 가지며, 이는 브라우저가 다른 작업(예: 추가 이벤트 발생 또는 문서 파싱 지속)을 수행하기 전에 일반적으로 스크립트를 중단 없이 실행한다는 것을 의미합니다.

반면에 HTML 파일의 파싱은 점진적으로 발생하므로, 파서가 언제든지 중단되어 스크립트를 실행할 수 있습니다. 이는 일반적으로 좋은 일이지만, 작성자는 이벤트 핸들러를 이벤트가 발생할 수 있는 시점 이후에 연결하지 않도록 주의해야 합니다.

이를 안정적으로 수행하는 두 가지 방법은 이벤트 핸들러 콘텐츠 속성을 사용하거나, 동일한 스크립트에서 요소를 생성하고 이벤트 핸들러를 추가하는 것입니다. 후자의 방법은 앞서 언급한 것처럼, 스크립트가 추가 이벤트가 발생하기 전에 완료될 때까지 실행되므로 안전합니다.

이것이 발생할 수 있는 한 가지 방법은 img 요소와 load 이벤트와 관련된 것입니다. 특히 이미지가 이미 캐시된 경우(이는 흔한 일입니다) 요소가 파싱되자마자 이벤트가 발생할 수 있습니다.

여기에서 작성자는 onload 핸들러를 img 요소에 사용하여 load 이벤트를 포착합니다:

<img src="games.png" alt="Games" onload="gamesLogoHasLoaded(event)">

스크립트로 요소를 추가하는 경우, 이벤트 핸들러가 동일한 스크립트에서 추가되기만 하면 이벤트가 여전히 누락되지 않습니다:

<script>
 var img = new Image();
 img.src = 'games.png';
 img.alt = 'Games'; 
 img.onload = gamesLogoHasLoaded; 
 // img.addEventListener('load', gamesLogoHasLoaded, false); // 이 방법도 작동합니다
</script>

그러나 작성자가 먼저 img 요소를 생성하고, 별도의 스크립트에서 이벤트 리스너를 추가하면 load 이벤트가 그 사이에 발생하여 이벤트를 놓칠 수 있습니다:

<!-- 이 스타일을 사용하지 마십시오, 경합 상태가 발생할 수 있습니다! -->
 <img id="games" src="games.png" alt="Games">
 <!-- 파서가 잠시 멈추는 동안 'load' 이벤트가 여기서 발생할 수 있으며,
      이 경우 이벤트를 볼 수 없게 됩니다! -->
 <script>
  var img = document.getElementById('games'); 
  img.onload = gamesLogoHasLoaded; // 이벤트가 절대 발생하지 않을 수 있습니다!
 </script>

1.10.3 HTML 작성 시 실수를 잡는 방법: 검증기 및 적합성 검사기

이 섹션은 비규범적입니다.

작성자는 일반적인 실수를 잡기 위해 적합성 검사기(검증기라고도 함)를 사용하는 것이 좋습니다. WHATWG에서는 이러한 도구의 목록을 유지 관리하고 있습니다: https://whatwg.org/validator/

1.11 작성자를 위한 적합성 요구사항

이 섹션은 비규범적입니다.

이전 버전의 HTML 명세서와 달리, 이 명세서는 유효한 문서뿐만 아니라 유효하지 않은 문서의 처리에 대한 요구사항도 일부 자세히 정의하고 있습니다.

그러나 유효하지 않은 콘텐츠의 처리가 대부분의 경우 잘 정의되어 있지만, 문서 적합성 요구사항은 여전히 중요합니다. 실제로, 상호 운용성(특정 콘텐츠를 신뢰할 수 있고 동일하거나 동등한 방식으로 모든 구현이 처리하는 상황)은 문서 적합성 요구사항의 유일한 목표가 아닙니다. 이 섹션에서는 여전히 적합한 문서와 오류가 있는 문서를 구별해야 하는 일반적인 이유를 설명합니다.

1.11.1 표현 마크업

이 섹션은 비규범적입니다.

이전 버전의 HTML에서 대부분의 표현적 기능은 더 이상 허용되지 않습니다. 일반적으로 표현 마크업은 여러 가지 문제가 있는 것으로 나타났습니다:

표현 요소의 사용은 접근성을 저하시킵니다

표현 마크업을 사용하여 보조 기술(AT) 사용자에게 수용 가능한 경험을 제공하는 것은 가능하지만(예: ARIA 사용), 이는 의미적으로 적절한 마크업을 사용할 때보다 훨씬 더 어렵습니다. 게다가, 이러한 기술을 사용하더라도 텍스트 모드 브라우저 사용자와 같은 비-AT 비-그래픽 사용자에게 페이지를 접근 가능하게 만드는 데 도움이 되지 않습니다.

반면, 미디어 독립적인 마크업을 사용하면 텍스트 브라우저 사용자 등 더 많은 사용자에게 작동하는 방식으로 문서를 작성할 수 있는 쉬운 방법을 제공합니다.

유지 보수 비용이 높아짐

스타일에 독립적인 방식으로 작성된 사이트를 유지 보수하는 것이 훨씬 더 쉽습니다. 예를 들어, <font color="">를 사용하는 사이트의 색상을 변경하는 경우, 사이트 전체에 걸쳐 변경해야 하지만, CSS를 기반으로 한 사이트의 유사한 변경은 단일 파일을 변경하여 수행할 수 있습니다.

문서 크기 증가

표현 마크업은 일반적으로 훨씬 더 중복되므로 문서 크기가 커집니다.

이러한 이유로 이 버전의 HTML에서 표현 마크업이 제거되었습니다. 이 변경은 놀라운 일이 아닙니다. HTML4는 많은 해 전에 표현 마크업을 더 이상 사용하지 않도록 하고, 작성자가 표현 마크업에서 벗어나도록 돕기 위해 모드(HTML4 Transitional)를 제공했습니다. 나중에 XHTML 1.1은 이러한 기능을 완전히 폐기했습니다.

HTML에 남아 있는 유일한 표현 마크업 기능은 style 속성과 style 요소입니다. style 속성의 사용은 프로덕션 환경에서 다소 권장되지 않지만, 나중에 별도의 스타일 시트로 직접 이동할 수 있는 규칙을 신속하게 프로토타입화하는 데 유용할 수 있으며, 별도의 스타일 시트가 불편한 경우 특정 스타일을 제공하는 데 유용할 수 있습니다. 유사하게, style 요소는 배포 또는 페이지별 스타일에 유용할 수 있지만, 스타일이 여러 페이지에 적용되는 경우 일반적으로 외부 스타일 시트가 더 편리합니다.

또한 이전에 표현적이었던 일부 요소가 이 명세서에서 미디어 독립적으로 재정의되었다는 점도 주목할 가치가 있습니다: b, i, hr, s, small, u.

1.11.2 문법 오류

이 섹션은 비규범적입니다.

HTML의 문법은 다양한 문제를 피하기 위해 제한됩니다.

직관적이지 않은 오류 처리 동작

특정 잘못된 문법 구조는 파싱될 때 매우 직관적이지 않은 DOM 트리를 생성할 수 있습니다.

예를 들어, 다음 마크업 조각은 hr 요소가 해당 table 요소보다 이전에 형제로 나타나는 DOM을 생성합니다:

<table><hr>...
옵션 오류 복구가 있는 오류

사용자 에이전트를 제어된 환경에서 사용할 수 있도록, 더 기괴하고 복잡한 오류 처리 규칙을 구현하지 않고도 사용자 에이전트가 파싱 오류를 만날 때마다 실패할 수 있습니다.

스트리밍 사용자 에이전트와 호환되지 않는 오류 처리 동작

위에서 언급한 <table><hr>... 예와 같은 일부 오류 처리 동작은 상태를 저장하지 않고 한 번의 통과로 HTML 파일을 처리하는 스트리밍 사용자 에이전트와 호환되지 않습니다. 이러한 사용자 에이전트와의 상호 운용성 문제를 피하기 위해, 이러한 동작을 초래하는 모든 문법은 유효하지 않은 것으로 간주됩니다.

정보 집합 강제를 초래할 수 있는 오류

XML을 기반으로 하는 사용자 에이전트가 HTML 파서에 연결될 때, 요소 또는 속성 이름에 여러 개의 콜론이 포함되지 않는 것과 같은 XML이 강제하는 특정 불변성이 HTML 파일에 의해 위반될 수 있습니다. 이를 처리하려면 파서가 HTML DOM을 XML 호환 정보 집합으로 강제해야 할 수 있습니다. 이러한 처리가 필요한 대부분의 문법 구조는 유효하지 않은 것으로 간주됩니다. (연속된 두 개의 하이픈을 포함하거나 하이픈으로 끝나는 주석은 HTML 문법에서 허용되는 예외입니다.)

불균형적으로 성능이 저하될 수 있는 오류

특정 문법 구조는 불균형적으로 성능이 저하될 수 있습니다. 이러한 구조의 사용을 방지하기 위해, 이들은 일반적으로 적합하지 않은 것으로 만들어집니다.

예를 들어, 다음 마크업은 성능이 저하됩니다. 모든 닫히지 않은 i 요소가 각 문단에서 다시 구성되어 점차적으로 각 문단에 더 많은 요소가 생성됩니다:

<p><i>그녀는 꿈을 꾸었다.
<p><i>그녀는 아침을 먹었다는 꿈을 꾸었다.
<p><i>그 후 점심.
<p><i>그리고 마침내 저녁.

이 조각의 결과로 생성된 DOM은 다음과 같습니다:

  • p
    • i
      • #text: 그녀는 꿈을 꾸었다.
  • p
    • i
      • i
        • #text: 그녀는 아침을 먹었다는 꿈을 꾸었다.
  • p
  • p
취약한 문법 구조와 관련된 오류

역사적 이유로 상대적으로 취약한 문법 구조가 있습니다. 이러한 문제에 우연히 부딪히는 사용자의 수를 줄이기 위해, 이러한 구조는 비적합한 것으로 만들어집니다.

예를 들어, 속성에서 특정 명명된 문자 참조의 파싱은 종결 세미콜론이 생략되더라도 발생합니다. 따옴표로 닫히지 않은 속성에서 따옴표 없이 앰퍼샌드(&)와 글자를 포함하는 경우, 그 글자가 명명된 문자 참조가 아닌 경우에는 안전하지만, 명명된 문자 참조로 해석되는 경우 그 문자로 해석됩니다.

이 조각에서, 속성 값은 "?bill&ted"입니다:

<a href="?bill&ted">Bill and Ted</a>

그러나 다음 조각에서, 속성 값은 실제로 "?art©"입니다. 의도된 "?art&copy"가 아닌 "©"로 해석됩니다.

<a href="?art&copy">Art and Copy</a>

이 문제를 피하기 위해, 모든 명명된 문자 참조는 세미콜론으로 끝나야 하며, 세미콜론 없이 명명된 문자 참조를 사용하는 경우 오류로 표시됩니다.

따라서 위의 경우를 올바르게 표현하는 방법은 다음과 같습니다:

<a href="?bill&ted">Bill and Ted</a> <!-- &ted는 명명된 문자 참조가 아니므로 괜찮습니다. -->
<a href="?art&amp;copy">Art and Copy</a> <!-- &copy는 명명된 문자 참조이므로 &가 이스케이프되어야 합니다. -->
레거시 사용자 에이전트에서의 상호 운용성 문제를 일으키는 오류

특정 문법 구조는 레거시 사용자 에이전트에서 특히 미묘하거나 심각한 문제를 일으키는 것으로 알려져 있으며, 작성자가 이러한 문제를 피할 수 있도록 비적합한 것으로 표시됩니다.

예를 들어, U+0060 그레이브 악센트(`) 문자가 따옴표로 닫히지 않은 속성에서 허용되지 않는 이유는 특정 레거시 사용자 에이전트에서 때때로 따옴표 문자로 처리되기 때문입니다.

또 다른 예로, DOCTYPE은 퀴르크 모드를 방지하기 위해 필수적으로 비 퀴르크 모드로 트리거됩니다. 레거시 사용자 에이전트의 퀴르크 모드에서의 동작은 대부분 문서화되지 않았기 때문입니다.

보안 공격에 노출될 위험이 있는 오류

특정 제한은 알려진 보안 문제를 피하기 위해 존재합니다.

예를 들어, UTF-7의 사용 제한은 UTF-7을 사용한 알려진 크로스 사이트 스크립팅 공격으로 인해 작성자가 피해를 입지 않도록 순전히 존재합니다. [UTF7]

작성자의 의도가 불분명한 경우

작성자의 의도가 매우 불분명한 마크업은 종종 비적합한 것으로 간주됩니다. 이러한 오류를 조기에 수정하면 나중에 유지보수가 더 쉬워집니다.

예를 들어, 작성자가 다음을 h1 제목으로 의도했는지 또는 h2 제목으로 의도했는지는 불분명합니다:

<h1>연락처</h2>
오타일 가능성이 높은 경우

사용자가 간단한 오타를 범했을 때, 이 오류를 조기에 잡아내면 작성자가 많은 디버깅 시간을 절약할 수 있습니다. 따라서 이 명세서는 일반적으로 이 명세서에 정의된 이름과 일치하지 않는 요소 이름, 속성 이름 등을 사용하는 것을 오류로 간주합니다.

예를 들어, 작성자가 <capton> 대신 <caption>을 입력한 경우, 이는 오류로 표시되어 작성자가 즉시 오타를 수정할 수 있습니다.

미래의 새로운 문법과 충돌할 가능성이 있는 오류

미래에 언어 문법을 확장할 수 있도록 하기 위해, 그렇지 않으면 무해한 기능들이 허용되지 않습니다.

예를 들어, 현재는 "속성"이 종료 태그에서 무시되지만, 이들은 무효이며, 미래에 해당 문법 기능을 사용하여 배포된(및 유효한!) 콘텐츠와 충돌하지 않도록 하기 위해 비적합합니다.

일부 작성자는 모든 속성을 항상 따옴표로 묶고 모든 선택적 태그를 항상 포함하는 관행을 따르는 것이 유용하다고 생각하며, HTML 문법의 유연성을 활용하여 제공되는 간결성의 사소한 이점보다 이러한 관습에서 얻는 일관성을 선호합니다. 이러한 작성자를 돕기 위해, 적합성 검사기는 그러한 관습이 강제되는 운영 모드를 제공할 수 있습니다.

1.11.3 콘텐츠 모델 및 속성 값에 대한 제한사항

이 섹션은 비규범적입니다.

언어의 문법을 넘어서, 이 명세서는 요소와 속성을 지정하는 방법에 대한 제한도 둡니다. 이러한 제한은 비슷한 이유로 존재합니다:

의심스러운 의미론을 가진 콘텐츠와 관련된 오류

정의된 의미를 가진 요소의 오용을 피하기 위해, 이러한 중첩이 의심스러운 가치가 있을 경우 요소를 중첩하는 방법을 제한하는 콘텐츠 모델이 정의됩니다.

예를 들어, 이 명세서는 section 요소를 kbd 요소 내부에 중첩하는 것을 허용하지 않는데, 이는 저자가 전체 섹션을 입력해야 한다고 표시할 가능성이 매우 낮기 때문입니다.

표현된 의미의 충돌과 관련된 오류

마찬가지로, 요소 사용의 실수를 저자의 주목을 끌기 위해, 표현된 의미에서의 명백한 모순은 적합성 오류로 간주됩니다.

예를 들어, 아래의 조각에서는 의미가 말이 되지 않습니다: 구분자는 동시에 셀일 수 없으며, 라디오 버튼은 진행 표시줄이 될 수 없습니다.

<hr role="cell">
<input type=radio role=progressbar>

또 다른 예는 ul 요소의 콘텐츠 모델에 대한 제한입니다. 이 요소는 li 요소 자식만을 허용합니다. 리스트는 정의상 0개 이상의 리스트 항목으로만 구성되므로, ul 요소에 li 요소 이외의 것이 포함된 경우, 무엇을 의미하는지 명확하지 않습니다.

기본 스타일이 혼란을 초래할 가능성이 있는 경우

일부 요소는 기본 스타일이나 동작으로 인해 특정 조합이 혼란을 초래할 가능성이 있습니다. 이 문제를 피할 수 있는 동등한 대체 요소가 있는 경우, 혼란스러운 조합은 허용되지 않습니다.

예를 들어, div 요소는 블록 박스로 렌더링되며, span 요소는 인라인 박스로 렌더링됩니다. 블록 박스인라인 박스에 넣는 것은 불필요하게 혼란스럽습니다. div 요소를 중첩하거나, span 요소를 중첩하거나, span 요소를 div 요소 안에 중첩하는 것은 모두 div 요소를 span 요소 안에 중첩하는 것과 동일한 목적을 수행하지만, 후자는 블록 박스인라인 박스에 넣는 것을 포함하기 때문에 후자 조합은 허용되지 않습니다.

또 다른 예는 인터랙티브 콘텐츠가 중첩될 수 없는 방식입니다. 예를 들어, button 요소는 textarea 요소를 포함할 수 없습니다. 이는 이러한 중첩된 인터랙티브 요소의 기본 동작이 사용자에게 매우 혼란스러울 수 있기 때문입니다. 이러한 요소를 중첩하는 대신 나란히 배치할 수 있습니다.

명세서를 오해한 것 같다고 나타나는 오류

때때로, 무언가가 허용되지 않는 이유는 이를 허용하는 것이 저자의 혼란을 야기할 가능성이 높기 때문입니다.

예를 들어, disabled 속성을 "false" 값으로 설정하는 것은 허용되지 않으며, 이는 요소가 활성화된다는 의미로 보일 수 있지만 실제로는 요소가 비활성화됨을 의미하기 때문입니다. (구현에서 중요한 것은 속성의 값이 아니라 속성의 존재입니다).

단순히 언어를 단순화하기 위해 부과된 제한과 관련된 오류

일부 적합성 오류는 저자가 배워야 할 언어를 단순화합니다.

예를 들어, area 요소의 shape 속성은 실습에서 동의어로 circcircle 값을 허용하지만, circ 값을 허용하지 않으므로 자습서 및 기타 학습 도구를 단순화할 수 있습니다. 둘 다 허용하는 데는 이점이 없지만 언어를 가르치는 데 혼란을 초래할 수 있습니다.

구문 분석기의 특이성과 관련된 오류

일부 요소는 다소 독특한 방식으로 구문 분석되며(주로 역사적 이유로), 이러한 콘텐츠 모델 제한은 저자가 이러한 문제에 노출되는 것을 방지하기 위한 것입니다.

예를 들어, form 요소는 구문 콘텐츠 내에서 허용되지 않으며, HTML로 구문 분석할 때, form 요소의 시작 태그는 p 요소의 종료 태그를 암시합니다. 따라서 다음 마크업은 하나가 아닌 두 개의 문단을 생성합니다:

<p>Welcome. <form><label>Name:</label> <input></form>

이는 정확히 다음과 같이 구문 분석됩니다:

<p>Welcome. </p><form><label>Name:</label> <input></form>
스크립트가 디버깅하기 어려운 방식으로 실패할 가능성이 있는 오류

일부 오류는 디버깅하기 어려운 스크립트 문제를 방지하기 위해 의도되었습니다.

예를 들어, 동일한 값을 가진 두 개의 id 속성을 갖는 것이 비적합한 이유는 중복된 ID가 잘못된 요소가 선택되도록 하여, 때로는 원인을 파악하기 어려운 재앙적인 영향을 미칠 수 있기 때문입니다.

저작 시간 낭비와 관련된 오류

일부 구조는 역사적으로 많은 저작 시간 낭비의 원인이 되었기 때문에 금지되었으며, 이를 피함으로써 저자는 미래의 작업에서 시간을 절약할 수 있습니다.

예를 들어, script 요소의 src 속성은 요소의 내용을 무시하게 합니다. 그러나 이는 명확하지 않으며, 특히 요소의 내용이 실행 가능한 스크립트처럼 보이는 경우 저자는 실행되지 않는 인라인 스크립트를 디버깅하려고 시간을 낭비할 수 있습니다. 이러한 문제를 줄이기 위해, 이 명세서는 script 요소의 src 속성이 존재할 때 실행 가능한 스크립트를 포함하는 것을 비적합하게 만듭니다. 이를 통해 문서를 검증하는 작성자는 이러한 실수로 시간을 낭비할 가능성이 줄어듭니다.

HTML 및 XML 문법 간의 전환을 시도하는 작성자에게 영향을 미치는 오류

일부 저자는 XML 및 HTML로 유사한 결과를 해석할 수 있는 파일을 작성하는 것을 좋아합니다. 이 실습은 일반적으로 스크립팅, 스타일링 또는 자동화된 직렬화와 관련된 미묘한 복잡성으로 인해 권장되지 않지만, 이 명세서는 이러한 어려움을 어느 정도 완화하기 위한 몇 가지 제한을 두고 있습니다. 이는 작성자가 HTML 및 XML 문법 간의 전환 시 이를 임시 단계로 사용할 수 있도록 합니다.

예를 들어, langxml:lang 속성을 동기화 상태로 유지하기 위한 다소 복잡한 규칙이 존재합니다.

또 다른 예는 HTML 직렬화에서 xmlns 속성 값에 대한 제한입니다. 이러한 제한은 문서를 HTML 또는 XML로 처리할 때 요소가 동일한 네임스페이스에 속하도록 보장하기 위해 마련되었습니다.

미래 확장을 위해 예약된 영역과 관련된 오류

언어의 미래 수정에서 새로운 구문을 허용하기 위한 구문 제한과 마찬가지로, 요소의 콘텐츠 모델 및 속성 값에 대한 일부 제한은 HTML 어휘의 미래 확장을 허용하기 위한 것입니다.

예를 들어, U+005F LOW LINE 문자(_)로 시작하는 target 속성 값이 특정 미리 정의된 값만 허용되도록 제한함으로써, 작성자가 정의한 값과 충돌하지 않고 나중에 새로운 미리 정의된 값을 도입할 수 있습니다.

다른 명세서를 잘못 사용한 것과 관련된 오류

일부 제한은 다른 명세서에 의해 설정된 제한을 지원하기 위한 것입니다.

예를 들어, 미디어 쿼리 목록을 사용하는 속성은 유효한 미디어 쿼리 목록만을 사용하도록 요구함으로써 해당 명세서의 적합성 규칙을 따르는 것의 중요성을 강조합니다.

1.12 추천 읽을거리

이 섹션은 비규범적입니다.

다음 문서는 이 사양의 독자에게 흥미로울 수 있습니다.

월드 와이드 웹을 위한 문자 모델 1.0: 기본 사항 [CHARMOD]

이 아키텍처 사양은 사양 작성자, 소프트웨어 개발자 및 콘텐츠 개발자에게 유니코드 표준과 ISO/IEC 10646에 의해 공동으로 정의된 유니버설 문자 세트를 기반으로 웹에서 상호 운용 가능한 텍스트 처리를 위한 공통 참조를 제공합니다. 다루는 주제는 '문자', '인코딩' 및 '문자열' 용어의 사용, 참조 처리 모델, 문자 인코딩의 선택 및 식별, 문자 이스케이프 및 문자열 인덱싱을 포함합니다.

유니코드 보안 고려 사항 [UTR36]

유니코드는 매우 많은 수의 문자를 포함하고 있으며 세계의 다양한 문자 체계를 통합하고 있기 때문에 잘못된 사용은 프로그램이나 시스템을 보안 공격에 노출시킬 수 있습니다. 특히 더 많은 제품이 국제화됨에 따라 이것은 매우 중요합니다. 이 문서는 프로그래머, 시스템 분석가, 표준 개발자 및 사용자가 고려해야 할 보안 고려 사항 중 일부를 설명하고, 문제의 위험을 줄이기 위한 구체적인 권장 사항을 제공합니다.

웹 콘텐츠 접근성 지침 (WCAG) [WCAG]

웹 콘텐츠 접근성 지침 (WCAG)은 웹 콘텐츠를 더 접근 가능하게 만드는 방법에 대한 다양한 권장 사항을 다룹니다. 이 지침을 따르면 시각 장애, 청각 장애, 학습 장애, 인지적 제한, 운동 제한, 언어 장애, 광 과민성 및 이들의 조합을 포함한 다양한 장애를 가진 사람들에게 콘텐츠를 접근 가능하게 할 수 있습니다. 이 지침을 따르면 일반 사용자를 포함하여 더 많은 사용자가 웹 콘텐츠를 더 쉽게 이용할 수 있게 됩니다.

저작 도구 접근성 지침 (ATAG) 2.0 [ATAG]

이 사양은 장애인을 위한 더 접근 가능한 웹 콘텐츠 저작 도구를 설계하기 위한 지침을 제공합니다. 이 지침을 준수하는 저작 도구는 장애인을 위한 접근 가능한 사용자 인터페이스를 제공할 뿐만 아니라 모든 저자가 접근 가능한 웹 콘텐츠를 제작할 수 있도록 지원하고 촉진할 것입니다.

사용자 에이전트 접근성 지침 (UAAG) 2.0 [UAAG]

이 문서는 장애인을 위한 웹 접근성을 향상시키기 위한 사용자 에이전트를 설계하는 지침을 제공합니다. 사용자 에이전트에는 웹 콘텐츠를 검색하고 렌더링하는 브라우저 및 기타 유형의 소프트웨어가 포함됩니다. 이 지침을 준수하는 사용자 에이전트는 자체 사용자 인터페이스와 기타 내부 기능을 통해 접근성을 촉진할 것이며, 특히 보조 기술과의 통신 능력을 포함합니다. 또한 장애인뿐만 아니라 모든 사용자가 준수하는 사용자 에이전트를 더 사용하기 쉽게 느낄 것입니다.

2 공통 인프라

이 사양은 Infra에 의존합니다. [INFRA]

2.1 용어

이 사양은 HTML 및 XML 속성과 IDL 속성을 모두 참조하며, 종종 동일한 맥락에서 사용됩니다. 어떤 것을 참조하는지 명확하지 않을 때는 HTML 및 XML 속성을 콘텐츠 속성이라고 하고, IDL 인터페이스에 정의된 속성은 IDL 속성이라고 합니다. 유사하게, "속성"이라는 용어는 자바스크립트 객체 속성과 CSS 속성 모두에 사용됩니다. 이러한 경우 모호함을 피하기 위해 객체 속성CSS 속성으로 명확히 구분합니다.

일반적으로, 사양에서 특정 기능이 HTML 구문 또는 XML 구문에 적용된다고 명시할 때, 다른 하나에도 적용됩니다. 특정 기능이 두 언어 중 하나에만 적용될 경우, "HTML의 경우, ... (이는 XML에는 적용되지 않음)"과 같이 명확하게 언급하여 다른 형식에는 적용되지 않음을 명시합니다.

이 사양은 문서라는 용어를 HTML의 모든 사용 사례를 참조하는 데 사용합니다. 이에는 짧은 정적 문서부터 멀티미디어가 풍부한 긴 에세이 또는 보고서, 완전한 인터랙티브 애플리케이션까지 포함됩니다. 이 용어는 Document 객체 및 그 하위 DOM 트리와, HTML 구문 또는 XML 구문을 사용하여 직렬화된 바이트 스트림을 참조하는 데 사용됩니다. 어떤 맥락에서 사용되는지에 따라 다릅니다.

DOM 구조의 맥락에서 HTML 문서XML 문서라는 용어는 DOM에서 정의된 대로 사용되며, Document 객체가 처할 수 있는 두 가지 다른 모드를 구체적으로 나타냅니다. [DOM] (이러한 용어 사용 시 항상 정의로 하이퍼링크됩니다.)

바이트 스트림의 맥락에서, HTML 문서는 text/html로 라벨이 지정된 리소스를, XML 문서는 XML MIME 타입으로 라벨이 지정된 리소스를 의미합니다.


간단히 하기 위해, 문서가 사용자에게 렌더링되는 방식과 관련하여 표시됨, 디스플레이됨, 보임과 같은 용어를 사용할 수 있습니다. 이러한 용어는 시각적 매체를 암시하는 것이 아니며, 다른 매체에도 동등하게 적용되어야 합니다.

2.1.1 병렬 처리

단계를 병렬로 실행한다는 것은 해당 단계들이 표준의 다른 로직(예: 이벤트 루프)과 동시에 실행되어야 함을 의미합니다. 이 표준은 이를 달성하는 정확한 메커니즘, 예를 들어 타임셰어링 협동 멀티태스킹, 파이버, 스레드, 프로세스, 다른 하이퍼스레드, 코어, CPU, 머신 등을 정의하지 않습니다. 반면, 즉시 실행되어야 하는 작업은 현재 실행 중인 작업을 중단하고, 자신을 실행한 후 이전에 실행 중이던 작업을 다시 시작해야 합니다.

병렬 처리를 활용하는 사양을 작성하는 방법에 대한 지침은 다른 사양에서 이벤트 루프 처리를 참조하십시오.

동일한 데이터에서 작동하는 여러 병렬 알고리즘 간의 경쟁 조건을 피하기 위해 병렬 큐를 사용할 수 있습니다.

병렬 큐는 일련의 알고리즘 단계를 순차적으로 실행해야 하는 큐를 나타냅니다.

병렬 큐알고리즘 큐()를 가지며, 초기에는 비어 있습니다.

병렬 큐에 단계를 큐에 추가하려면, 알고리즘 단계를 병렬 큐알고리즘 큐추가합니다.

새로운 병렬 큐를 시작하려면 다음 단계를 실행합니다:

  1. parallelQueue를 새로운 병렬 큐로 설정합니다.

  2. 다음 단계를 병렬로 실행합니다:

    1. 항상:

      1. stepsparallelQueue알고리즘 큐에서 큐에서 제거한 결과로 설정합니다.

      2. steps가 아무것도 아닌 경우, steps를 실행합니다.

      3. Assert: 병렬로 실행되는 단계는 예외를 발생시킬 수 없으므로 steps를 실행한 결과 예외가 발생하지 않았음을 확인합니다.

      구현에서는 이를 지속적으로 실행되는 루프로 구현할 필요는 없습니다. 표준의 알고리즘은 이해하기 쉬워야 하며 배터리 수명이나 성능을 반드시 고려하지는 않습니다.

  3. parallelQueue를 반환합니다.

병렬로 실행되는 단계들은 자체적으로 다른 단계를 병렬로 실행할 수 있습니다. 예를 들어, 병렬 큐 내에서 일련의 단계를 큐와 병렬로 실행하는 것이 유용할 수 있습니다.

어떤 표준이 nameList(리스트)를 정의하고, nameListname을 추가하는 메서드를 정의하는데, nameList에 이미 name이 포함되어 있는 경우 거부하는 것으로 가정합니다.

아래 솔루션은 경쟁 조건이 발생할 수 있습니다:

  1. p관련 영역에서 생성된 새 프라미스로 설정합니다.

  2. 다음 단계를 병렬로 실행합니다:

    1. nameList포함name이라면, 글로벌 작업을 큐에 추가하고 관련 글로벌 객체TypeErrorp를 거부하도록 하고, 이 단계를 중단합니다.

    2. 잠재적으로 긴 작업을 수행합니다.

    3. 이름nameList에 추가합니다.

    4. 글로벌 작업을 큐에 추가하고 관련 글로벌 객체p를 undefined로 해결하도록 합니다.

  3. p를 반환합니다.

위의 두 가지 호출은 동시에 실행될 수 있으며, name이 2.1 단계 동안 nameList에 없지만, 2.3 단계를 실행하기 전에 추가될 수 있으므로 namenameList에 두 번 추가됩니다.

병렬 큐는 이 문제를 해결합니다. 표준은 nameListQueue새로운 병렬 큐를 시작한 결과로 정의하고, 다음 과 같이 합니다:

  1. p관련 영역에서 생성된 새 프라미스로 설정합니다.

  2. 다음 단계를 큐에 추가하여 nameListQueue에 추가합니다:

    1. nameList포함name이라면, 글로벌 작업을 큐에 추가하고 관련 글로벌 객체TypeErrorp를 거부하도록 하고, 이 단계를 중단합니다.

    2. 잠재적으로 긴 작업을 수행합니다.

    3. 이름nameList에 추가합니다.

    4. 글로벌 작업을 큐에 추가하고 관련 글로벌 객체p를 undefined로 해결하도록 합니다.

  3. p를 반환합니다.

이제 단계들이 큐에 추가되고 경쟁 상태가 발생하지 않습니다.

2.1.2 리소스

본 명세서에서는 외부 리소스의 의미를 해석할 수 있는 구현이 있는지 여부를 나타낼 때 지원됨이라는 용어를 사용합니다. 특정 형식 또는 유형의 외부 리소스를 처리할 수 있고 해당 리소스의 중요한 측면이 무시되지 않으면 해당 형식 또는 유형이 지원됨으로 간주됩니다. 특정 리소스가 지원됨인지 여부는 리소스 형식의 기능이 어떻게 사용되는지에 따라 달라질 수 있습니다.

예를 들어, PNG 이미지는 해당 픽셀 데이터를 해독하고 렌더링할 수 있다면, 구현이 알지 못하더라도 이미지에 애니메이션 데이터가 포함되어 있어도 지원되는 형식으로 간주됩니다.

MPEG-4 비디오 파일은 압축 형식이 지원되지 않는다면 해당 구현이 파일의 메타데이터에서 영화의 크기를 결정할 수 있더라도 지원되는 형식으로 간주되지 않습니다.

일부 명세서, 특히 HTTP 명세서에서 표현이라고 하는 것을 이 명세서에서는 리소스라고 합니다. [HTTP]

리소스의 중요 하위 리소스는 리소스를 올바르게 처리하기 위해 필요한 리소스입니다. 어떤 리소스가 중요한지 아닌지는 리소스 형식을 정의하는 명세서에서 정의됩니다.

예를 들어, CSS 스타일 시트의 경우, 여기에서는 임시로 이들의 중요한 하위 리소스를 @import 규칙을 통해 가져온 다른 스타일 시트들로 정의합니다. 다른 가져온 스타일 시트들에 의해 간접적으로 가져온 스타일 시트들도 포함됩니다.

이 정의는 완전히 상호 운용 가능한 것은 아닙니다. 또한 일부 사용자 에이전트는 배경 이미지나 웹 폰트와 같은 리소스를 중요한 하위 리소스로 간주하는 것 같습니다. 이상적으로는 CSS 워킹 그룹이 이것을 정의해야 합니다. 이 문제에 대한 진행 상황을 추적하려면 w3c/csswg-drafts issue #1088를 참조하십시오.

2.1.3 XML 호환성

HTML에서 XML로의 마이그레이션을 용이하게 하기 위해, 이 명세서를 준수하는 사용자 에이전트는 HTML의 요소를 http://www.w3.org/1999/xhtml 네임스페이스에 배치합니다. 적어도 DOM과 CSS의 목적을 위해서라도 그렇습니다. "HTML 요소"라는 용어는 XML 문서에서도 해당 네임스페이스에 있는 모든 요소를 지칭합니다.

달리 명시되지 않는 한, 이 명세서에서 정의되거나 언급된 모든 요소는 HTML 네임스페이스 ("http://www.w3.org/1999/xhtml")에 있으며, 이 명세서에서 정의되거나 언급된 모든 속성은 네임스페이스가 없습니다.

요소 타입이라는 용어는 특정 로컬 이름과 네임스페이스를 가진 요소의 집합을 지칭하는 데 사용됩니다. 예를 들어, button 요소는 button 요소 타입의 요소로, 로컬 이름이 "button"이며 (위에서 정의한 대로 암묵적으로) HTML 네임스페이스에 속합니다.

속성 이름은 XML에서 정의된 Name 생성 규칙을 준수하고 U+003A 콜론 문자 (:)를 포함하지 않는 경우 XML 호환이라고 합니다. [XML]

2.1.4 DOM 트리

어떤 요소나 속성이 무시됨, 또는 다른 값으로 처리됨, 또는 다른 것으로 취급됨이라고 명시된 경우, 이는 해당 노드가 DOM에 삽입된 후 처리에만 해당됩니다. 이러한 상황에서 사용자 에이전트는 DOM을 변경해서는 안 됩니다.

콘텐츠 속성의 값이 이전 값과 다를 때만 값이 변경됨이라고 합니다. 이미 가진 값으로 속성을 설정하는 것은 변경으로 간주되지 않습니다.

비어 있음이라는 용어는 속성 값, 텍스트 노드 또는 문자열에 사용될 때, 텍스트의 길이가 0임을 의미합니다 (즉, 제어 문자 또는 U+0020 SPACE를 포함하지 않음).

HTML 요소는 요소의 로컬 이름에 대해 특정한 HTML 요소 삽입 단계를 가질 수 있습니다. 유사하게, HTML 요소는 요소의 로컬 이름에 대해 특정한 HTML 요소 제거 단계를 가질 수 있습니다.

HTML 표준의 삽입 단계insertedNode가 주어졌을 때 다음과 같이 정의됩니다:

  1. 만약 insertedNode네임스페이스HTML 네임스페이스인 요소이고, 이 표준에서 insertedNode로컬 이름에 대해 HTML 요소 삽입 단계를 정의하고 있는 경우, insertedNode에 대해 해당 HTML 요소 삽입 단계를 실행합니다.

  2. 만약 insertedNode양식 관련 요소이거나 양식 관련 요소의 상위 요소인 경우:

    1. 만약 양식 관련 요소파서 삽입 플래그가 설정된 경우, 반환합니다.

    2. 양식 소유자 재설정양식 관련 요소에 대해 실행합니다.

  3. 만약 insertedNode요소로서 열린 요소 스택에 없는 경우, 내부 리소스 링크 처리insertedNode노드 문서에 대해 실행합니다.

HTML 표준의 제거 단계removedNodeoldParent가 주어졌을 때 다음과 같이 정의됩니다:

  1. removedNode노드 문서document로 설정합니다.

  2. 만약 document포커스된 영역removedNode라면, document뷰포트로 설정하고, document관련 글로벌 객체내비게이션 API진행 중인 내비게이션 동안 포커스 변경을 false로 설정합니다.

    이 작업은 포커스 해제 단계, 포커스 설정 단계 또는 포커스 업데이트 단계를 수행하지 않으며, 따라서 blur 또는 change 이벤트가 발생하지 않습니다.

  3. 만약 removedNode네임스페이스HTML 네임스페이스인 요소이고, 이 표준에서 removedNode로컬 이름에 대해 HTML 요소 제거 단계를 정의하고 있는 경우, removedNodeoldParent에 대해 해당 HTML 요소 제거 단계를 실행합니다.

  4. 만약 removedNode팝오버 속성이 팝오버 없음 상태에 있지 않다면, removedNode, false, false 및 false를 사용하여 팝오버 숨기기 알고리즘을 실행합니다.

노드가 문서에 삽입됨삽입 단계가 해당 노드를 인수로 호출하고 이제 문서 트리에 포함되었을 때를 의미합니다. 마찬가지로, 노드가 문서에서 제거됨제거 단계가 해당 노드를 인수로 호출하고 이제 더 이상 문서 트리에 포함되지 않았을 때를 의미합니다.

노드가 연결됨삽입 단계가 해당 노드를 인수로 호출하고 이제 연결됨을 의미합니다. 마찬가지로, 노드가 연결 해제됨제거 단계가 해당 노드를 인수로 호출하고 이제 더 이상 연결됨이 아닌 경우를 의미합니다.

노드가 탐색 문맥에 연결됨은 해당 노드가 연결됨이고, 해당 노드의 섀도우 포함 루트탐색 문맥이 null이 아닐 때를 의미합니다. 노드가 탐색 문맥에 연결됨삽입 단계가 해당 노드를 인수로 호출하고 이제 탐색 문맥에 연결됨을 의미합니다. 노드가 탐색 문맥에서 연결 해제됨제거 단계가 해당 노드를 인수로 호출하고 이제 더 이상 탐색 문맥에 연결됨이 아니거나, 해당 노드의 섀도우 포함 루트탐색 문맥이 null이 된 경우를 의미합니다.

2.1.5 스크립팅

Foo가 실제로는 인터페이스인 경우에도 "a Foo object"라는 표현이 사용되며, 이는 더 정확한 "인터페이스 Foo를 구현하는 객체" 대신 사용되기도 합니다.

IDL 속성이 얻어짐이라고 할 때는 해당 속성의 값이 조회되고 있을 때(예: 저자 스크립트에 의해), 설정됨이라고 할 때는 새 값이 할당될 때를 의미합니다.

DOM 객체가 라이브라고 할 때, 해당 객체의 속성과 메서드는 스냅샷이 아닌 실제 기본 데이터에 대해 작동해야 합니다.

2.1.6 플러그인

플러그인이라는 용어는 사용자 에이전트가 사용하는 구현 정의된 콘텐츠 핸들러 집합을 의미하며, 이는 document 객체의 렌더링에 참여할 수 있지만, document하위 탐색 가능 요소로 작동하지 않으며, 노드 객체를 document의 DOM에 추가하지 않습니다.

일반적으로 이러한 콘텐츠 핸들러는 서드파티에 의해 제공되지만, 사용자 에이전트가 내장된 콘텐츠 핸들러를 플러그인으로 지정할 수도 있습니다.

사용자 에이전트는 text/plainapplication/octet-stream 유형을 등록된 플러그인으로 간주해서는 안 됩니다.

플러그인의 한 예로, 사용자가 PDF 파일로 이동할 때 탐색 가능 요소에서 인스턴스화되는 PDF 뷰어를 들 수 있습니다. 이는 PDF 뷰어 구성 요소를 구현한 당사자가 사용자 에이전트를 구현한 당사자와 동일한지 여부와 관계없이 플러그인으로 간주됩니다. 그러나 사용자 에이전트와 별도로 실행되는 PDF 뷰어 애플리케이션(동일한 인터페이스를 사용하지 않는 경우)은 이 정의에 따른 플러그인이 아닙니다.

이 명세서는 플러그인과 상호 작용하는 메커니즘을 정의하지 않습니다. 이는 사용자 에이전트 및 플랫폼에 따라 다를 것으로 예상되기 때문입니다. 일부 사용자 에이전트는 Netscape 플러그인 API와 같은 플러그인 메커니즘을 지원할 수 있으며, 다른 사용자 에이전트는 원격 콘텐츠 변환기를 사용하거나 특정 유형에 대한 내장 지원을 가질 수 있습니다. 실제로 이 명세서는 사용자 에이전트가 플러그인을 지원해야 한다고 요구하지 않습니다. [NPAPI]

브라우저는 플러그인을 위해 의도된 외부 콘텐츠와 상호 작용할 때 극도로 주의해야 합니다. 서드파티 소프트웨어가 사용자 에이전트 자체와 동일한 권한으로 실행될 때, 서드파티 소프트웨어의 취약점은 사용자 에이전트의 취약점만큼 위험해질 수 있습니다.

(이것은 추적 벡터입니다.) 서로 다른 사용자가 서로 다른 플러그인 집합을 가지는 것이 사용자가 고유하게 식별될 가능성을 높이는 추적 벡터를 제공하기 때문에, 사용자 에이전트는 각 사용자에 대해 동일한 플러그인 집합을 지원하도록 권장됩니다.

2.1.7 문자 인코딩

문자 인코딩은, 또는 모호하지 않은 경우 인코딩인코딩에서 정의된 바와 같이 바이트 스트림과 유니코드 문자열 간의 변환을 정의하는 방법입니다. 인코딩인코딩 이름과 하나 이상의 인코딩 레이블을 가지며, 인코딩 표준에서는 이를 인코딩의 이름레이블이라고 합니다. [ENCODING]

2.1.8 준수 클래스

이 명세서는 사용자 에이전트(구현자에게 관련)와 문서(저자 및 저작 도구 구현자에게 관련)에 대한 준수 기준을 설명합니다.

준수 문서는 문서에 대한 모든 준수 기준을 준수하는 문서입니다. 가독성을 위해 이러한 준수 요구 사항 중 일부는 저자에 대한 준수 요구 사항으로 표현됩니다. 이러한 요구 사항은 암묵적으로 문서에 대한 요구 사항입니다. 정의상, 모든 문서는 저자가 있는 것으로 가정됩니다. (일부 경우에는 그 저자가 사용자 에이전트일 수도 있으며, 이러한 사용자 에이전트는 아래에서 설명하는 추가 규칙의 적용을 받습니다.)

예를 들어, "저자는 foobar 요소를 사용해서는 안 됩니다."라는 요구 사항이 있으면 문서에 foobar라는 이름의 요소가 포함될 수 없음을 의미합니다.

문서 준수 요구 사항과 구현 준수 요구 사항 간에는 암묵적인 관계가 없습니다. 사용자 에이전트는 비준수 문서를 자유롭게 처리할 수 없습니다. 이 명세서에서 설명하는 처리 모델은 입력 문서의 준수 여부와 관계없이 구현에 적용됩니다.

사용자 에이전트는 여러 (중첩된) 범주로 나뉘며, 각각 다른 준수 요구 사항이 있습니다.

웹 브라우저 및 기타 상호작용 사용자 에이전트

XML 구문을 지원하는 웹 브라우저는 XML 문서에서 발견된 HTML 네임스페이스의 요소와 속성을 이 명세서에서 설명한 대로 처리하여 사용자가 상호작용할 수 있도록 해야 합니다. 단, 이러한 요소의 의미가 다른 명세서에 의해 재정의된 경우는 제외합니다.

준수 웹 브라우저는 XML 문서에서 스크립트 요소를 발견하면 해당 요소에 포함된 스크립트를 실행해야 합니다. 그러나, XSLT로 표현된 변환 내에서 이 요소가 발견되면 (사용자 에이전트가 XSLT도 지원한다고 가정할 때) 프로세서는 대신 스크립트 요소를 변환의 일부를 형성하는 불투명한 요소로 취급해야 합니다.

HTML 구문을 지원하는 웹 브라우저는 이 명세서에서 설명한 대로 HTML MIME 유형으로 레이블된 문서를 처리하여 사용자가 상호작용할 수 있도록 해야 합니다.

스크립팅을 지원하는 사용자 에이전트는 또한 이 명세서의 IDL 조각의 준수 구현이어야 합니다. Web IDL에서 설명한 대로. [WEBIDL]

명시적으로 명시되지 않는 한, HTML 요소의 의미를 재정의하는 명세서는 해당 요소를 나타내는 DOM 객체에 대한 요구 사항을 재정의하지 않습니다. 예를 들어, 위 예에서 스크립트 요소는 여전히 HTMLScriptElement 인터페이스를 구현해야 합니다.

비상호작용 프레젠테이션 사용자 에이전트

HTML 및 XML 문서를 처리하여 비상호작용 버전으로 렌더링하는 사용자 에이전트는 사용자 상호작용에 대한 요구 사항을 제외하고 웹 브라우저와 동일한 준수 기준을 준수해야 합니다.

비상호작용 프레젠테이션 사용자 에이전트의 전형적인 예로는 프린터(정적 UA) 및 오버헤드 디스플레이(동적 UA)가 있습니다. 대부분의 정적 비상호작용 프레젠테이션 사용자 에이전트는 스크립팅 지원이 없도록 선택할 것으로 예상됩니다.

비상호작용이지만 동적인 프레젠테이션 UA는 여전히 스크립트를 실행하여 양식을 동적으로 제출할 수 있도록 해야 합니다. 그러나 사용자가 문서와 상호작용할 수 없는 경우 "포커스"라는 개념은 관련이 없으므로 UA는 포커스 관련 DOM API를 지원할 필요가 없습니다.

권장 기본 렌더링을 지원하는 시각적 사용자 에이전트

사용자 에이전트는 상호작용 여부와 관계없이 이 명세서에서 정의된 권장 기본 렌더링을 지원하는 것으로 지정될 수 있습니다(사용자 옵션으로 지정될 수 있음).

이는 필수 사항은 아닙니다. 특히, 권장 기본 렌더링을 구현하는 사용자 에이전트라도 기본 설정을 덮어써서 사용자 경험을 개선할 수 있는 설정을 제공하는 것이 좋습니다. 예를 들어 색상 대비를 변경하거나, 다른 포커스 스타일을 사용하거나, 사용자가 더 접근 가능하고 사용하기 쉽도록 하는 등의 방법이 있습니다.

권장 기본 렌더링을 지원하도록 지정된 사용자 에이전트는 그러한 상태에서 렌더링 섹션에서 정의된 대로 사용자 에이전트가 구현할 것으로 기대되는 동작 규칙을 구현해야 합니다.

스크립팅 지원이 없는 사용자 에이전트

스크립팅을 지원하지 않거나 스크립팅 기능이 완전히 비활성화된 구현은 이 명세서에서 언급된 이벤트 및 DOM 인터페이스를 지원할 필요가 없습니다. 이벤트 모델이나 DOM 측면에서 정의된 명세서의 부분에 대해서는 그러한 사용자 에이전트가 이벤트와 DOM이 지원되는 것처럼 행동해야 합니다.

스크립팅은 애플리케이션의 필수적인 부분을 형성할 수 있습니다. 스크립팅을 지원하지 않거나 스크립팅이 비활성화된 웹 브라우저는 저자의 의도를 완전히 전달하지 못할 수 있습니다.

준수 검사기

준수 검사기는 문서가 이 명세서에서 설명하는 해당 준수 기준을 준수하는지 확인해야 합니다. 자동화된 준수 검사기는 저자의 의도를 해석해야 하는 오류(예: 인용 블록 요소의 내용이 인용이 아닌 경우 문서는 비준수이지만, 인간의 판단 입력 없이 실행되는 준수 검사기는 인용 블록 요소에 인용된 자료만 포함되어 있는지 확인할 필요는 없습니다.)를 감지하는 것을 면제받습니다.

준수 검사기는 입력 문서가 탐색 문맥 없이 파싱될 때(스크립트가 실행되지 않으며 파서의 스크립팅 플래그가 비활성화됨) 문서가 준수하는지 확인해야 하며, 입력 문서가 스크립트가 실행되는 탐색 문맥에서 파싱될 때도 준수하는지 확인해야 합니다. 스크립트가 실행 중에만 발생하는 일시적인 상태를 제외하고는 스크립트가 비준수 상태를 일으키지 않아야 합니다. (이는 불가능한 것으로 입증되었기 때문에 "해야 한다"가 아닌 "권장 사항"입니다. [COMPUTABLE])

"HTML 유효성 검사기"라는 용어는 이 명세서의 해당 요구 사항을 준수하는 준수 검사기를 나타내는 데 사용할 수 있습니다.

XML DTD는 이 명세서의 모든 준수 요구 사항을 표현할 수 없습니다. 따라서 유효성 검사 XML 프로세서와 DTD는 준수 검사기를 구성할 수 없습니다. 또한, 이 명세서에서 정의한 두 가지 저작 형식 중 어느 것도 SGML의 응용 프로그램이 아니기 때문에 유효성 검사 SGML 시스템도 준수 검사기를 구성할 수 없습니다.

달리 표현하자면, 세 가지 유형의 준수 기준이 있습니다:

  1. DTD로 표현할 수 있는 기준.
  2. DTD로 표현할 수 없지만 여전히 기계로 검사할 수 있는 기준.
  3. 인간만이 검사할 수 있는 기준.

준수 검사기는 첫 번째와 두 번째를 검사해야 합니다. 단순 DTD 기반 유효성 검사기는 오류의 첫 번째 클래스를 검사할 뿐이므로 이 명세서에 따라 준수 검사기로 간주되지 않습니다.

데이터 마이닝 도구

문서를 렌더링하거나 준수 여부를 검사하기 위해서가 아닌 다른 이유로 HTML 및 XML 문서를 처리하는 애플리케이션 및 도구는 처리하는 문서의 의미에 따라 행동해야 합니다.

단락마다 중첩 수준을 증가시키고 헤딩에 대해서는 중첩 수준을 증가시키지 않는 문서 개요를 생성하는 도구는 준수하지 않는 것입니다.

저작 도구 및 마크업 생성기

저작 도구 및 마크업 생성기는 준수 문서를 생성해야 합니다. 저자에게 적용되는 준수 기준은 적절한 경우 저작 도구에도 적용됩니다.

저작 도구는 요소를 지정된 용도로만 사용하는 것에 대한 엄격한 요구 사항에서 제외되지만, 저작 도구가 아직 저자의 의도를 결정할 수 없는 범위 내에서만 해당됩니다. 그러나 저작 도구는 요소를 자동으로 오용하거나 사용자가 그렇게 하도록 유도해서는 안 됩니다.

예를 들어, 주소 요소를 임의의 연락처 정보에 사용하는 것은 준수하지 않는 것입니다. 해당 요소는 가장 가까운 아티클 또는 본문 요소 상위 요소에 대한 연락처 정보를 표시하는 데만 사용할 수 있습니다. 그러나 저작 도구는 차이를 결정할 수 없을 가능성이 높기 때문에 저작 도구는 해당 요구 사항에서 제외됩니다. 그러나 이것이 저작 도구가 주소 요소를 임의의 이탤릭체 텍스트 블록에 사용할 수 있음을 의미하는 것은 아닙니다. 이것은 단지 사용자가 아티클 요소에 대한 연락처 정보를 삽입하기 위한 도구를 사용할 때, 사용자가 실제로 그렇게 하고 다른 것을 삽입하지 않는다는 것을 확인할 필요가 없다는 것을 의미합니다.

준수 검사와 관련하여, 편집기는 준수 검사기가 확인할 것과 동일한 정도로 문서를 출력해야 합니다.

비준수 문서를 편집하기 위해 저작 도구를 사용하는 경우, 편집 세션 중에 편집되지 않은 문서의 섹션에서 준수 오류를 유지할 수 있습니다(즉, 편집 도구는 잘못된 콘텐츠를 라운드트립하는 것이 허용됩니다). 그러나 오류가 그렇게 유지된 경우 저작 도구는 출력이 준수한다고 주장해서는 안 됩니다.

저작 도구는 구조 또는 의미 데이터에서 작동하는 도구와 미디어별 편집 기반(WYSIWYG)에서 작동하는 도구의 두 가지 광범위한 종류로 나뉠 것으로 예상됩니다.

전자는 HTML을 작성하는 도구에 권장되는 메커니즘입니다. 소스 정보의 구조를 사용하여 어느 HTML 요소와 속성이 가장 적합한지에 대해 정보에 입각한 선택을 할 수 있기 때문입니다.

그러나 WYSIWYG 도구도 정당합니다. WYSIWYG 도구는 적절하다고 판단되는 요소를 사용해야 하며, 적절하지 않은 요소는 사용하지 않아야 합니다. 이는 극단적인 경우에 div, b, i, span과 같은 몇 가지 요소로 흐름 요소의 사용을 제한하고 스타일 속성을 자유롭게 사용하는 것을 의미할 수 있습니다.

WYSIWYG 여부와 관계없이 모든 저작 도구는 사용자가 구조가 잘 갖춰져 있고, 의미가 풍부하며, 미디어에 독립적인 콘텐츠를 만들 수 있도록 최선을 다해야 합니다.

기존 콘텐츠 및 이전 명세서와의 호환성을 위해 이 명세서는 두 가지 저작 형식을 설명합니다: 하나는 XML을 기반으로 하며, 하나는 SGML에서 영감을 받은 사용자 정의 형식을 사용합니다(HTML 구문이라고 함). 구현은 이 두 형식 중 하나 이상을 지원해야 하지만, 둘 다 지원하는 것이 좋습니다.

일부 준수 요구 사항은 요소, 속성, 메서드 또는 객체에 대한 요구 사항으로 표현됩니다. 이러한 요구 사항은 콘텐츠 모델 제한을 설명하는 것과 구현 동작을 설명하는 두 가지 범주로 나뉩니다. 전자는 문서 및 저작 도구에 대한 요구 사항이고, 후자는 사용자 에이전트에 대한 요구 사항입니다. 마찬가지로 일부 준수 요구 사항은 저자에 대한 요구 사항으로 표현됩니다. 이러한 요구 사항은 저자가 작성한 문서에 대한 준수 요구 사항으로 해석되어야 합니다. (즉, 이 명세서는 저자에 대한 준수 기준과 문서에 대한 준수 기준을 구분하지 않습니다.)

2.1.9 의존성

이 명세서는 여러 다른 기본 명세서에 의존합니다.

Infra

다음 용어는 Infra에서 정의됩니다: [INFRA]

유니코드 및 인코딩

유니코드 문자 집합은 텍스트 데이터를 나타내는 데 사용되며, 인코딩문자 인코딩과 관련된 요구 사항을 정의합니다. [UNICODE]

이 명세서는 용어를 이러한 명세서에서 정의된 용어를 기반으로 도입합니다.

다음 용어는 인코딩에서 정의된 대로 사용됩니다: [ENCODING]

  • 인코딩 얻기
  • 출력 인코딩 얻기
  • 바이트 스트림과 인코딩을 받아 문자 스트림을 반환하는 일반 디코딩 알고리즘
  • 바이트 스트림을 받아 문자 스트림을 반환하며, 가능하다면 하나의 UTF-8 바이트 순서 표시(BOM)를 제거하는 UTF-8 디코딩 알고리즘
  • 하나의 UTF-8 바이트 순서 표시(BOM)를 제거하지 않는다는 점을 제외하면 UTF-8 디코딩과 동일한 BOM 없는 UTF-8 디코딩 알고리즘
  • 문자 스트림과 인코딩을 받아 바이트 스트림을 반환하는 인코딩 알고리즘
  • 문자 스트림을 받아 바이트 스트림을 반환하는 UTF-8 인코딩 알고리즘
  • 바이트 스트림을 받아 인코딩 또는 null을 반환하는 BOM 감지 알고리즘
XML 및 관련 명세서

HTML에 대해 XML 구문을 지원하는 구현은 XML의 일부 버전과 해당 네임스페이스 명세서를 지원해야 합니다. 왜냐하면 해당 구문은 네임스페이스가 있는 XML 직렬화를 사용하기 때문입니다. [XML] [XMLNS]

스크립트를 실행하지 않고 CSS나 XPath 표현식을 평가하지 않으며, 또는 결과 DOM을 임의의 콘텐츠에 노출하지 않고 콘텐츠에 대해 작업을 수행하는 데이터 마이닝 도구 및 기타 사용자 에이전트는 DOM 노드 유사체가 특정 네임스페이스에 있음을 주장하는 것으로 "네임스페이스 지원"을 할 수 있으며, 실제로 네임스페이스 문자열을 노출하지 않아도 됩니다.

HTML 구문에서는 네임스페이스 접두사 및 네임스페이스 선언이 XML에서와 동일한 효과를 가지지 않습니다. 예를 들어, 콜론은 HTML 요소 이름에서 특별한 의미를 가지지 않습니다.


XML 네임스페이스space 이름을 가진 속성은 확장 가능 마크업 언어 (XML)에서 정의됩니다. [XML]

Name 프로덕션은 XML에서 정의됩니다. [XML]

이 명세서는 또한 XML 문서와 스타일 시트를 연결하는 명세서에서 정의된 <?xml-stylesheet?> 처리 지침을 참조합니다. [XMLSSPI]

이 명세서는 또한 XSLTProcessor 인터페이스와 transformToFragment(), transformToDocument() 메서드를 비규범적으로 언급합니다. [XSLTP]

URL

다음 용어는 URL에서 정의됩니다: [URL]

이 명세서는 또한 다음과 같은 스키마 및 프로토콜을 참조합니다:

미디어 프래그먼트 구문미디어 프래그먼트 URI에서 정의됩니다. [MEDIAFRAG]

HTTP 및 관련 명세서

다음 용어는 HTTP 명세서에서 정의됩니다: [HTTP]

다음 용어는 HTTP 상태 관리 메커니즘에서 정의됩니다: [COOKIES]

다음 용어는 웹 링크에서 정의됩니다: [WEBLINK]

다음 용어는 HTTP를 위한 구조화된 필드 값에서 정의됩니다: [STRUCTURED-FIELDS]

다음 용어는 MIME 스니핑에서 정의됩니다: [MIMESNIFF]

Fetch

다음 용어는 Fetch에서 정의됩니다: [FETCH]

Paint Timing

Paint Timing에서 다음 용어가 정의되었습니다: [PAINTTIMING]

Navigation Timing

Navigation Timing에서 다음 용어가 정의되었습니다: [NAVIGATIONTIMING]

Resource Timing

Resource Timing에서 다음 용어가 정의되었습니다: [RESOURCETIMING]

Performance Timeline

Performance Timeline에서 다음 용어가 정의되었습니다: [PERFORMANCETIMELINE]

Long Animation Frames

Long Animation Frames에서 다음 용어가 정의되었습니다: [LONGANIMATIONFRAMES]

Long Tasks

Long Tasks에서 다음 용어가 정의되었습니다: [LONGTASKS]

Web IDL

이 명세서의 IDL 조각은 Web IDL에 설명된 대로 IDL 조각을 준수하기 위해 해석되어야 합니다. [WEBIDL]

Web IDL에서 다음 용어가 정의되었습니다:

Web IDL 또한 이 명세서의 Web IDL 조각에서 사용되는 다음 타입을 정의합니다:

이 명세서에서 throw라는 용어는 Web IDL에 정의된 대로 사용됩니다. DOMException 타입 및 다음 예외 이름은 Web IDL에 의해 정의되고 이 명세서에서 사용됩니다:

이 명세서가 특정 시간을 나타내는 Date 객체를 생성해야 하는 경우(특별 값 Not-a-Number 포함), 해당 시간이 있다면 그 밀리초 구성요소는 정수로 잘려야 하며, 새로 생성된 Date 객체의 시간 값은 잘린 결과를 나타내야 합니다.

예를 들어, 2000년 1월 1일 01:00 UTC 이후 23045만분의 1초인 2000-01-01T00:00:00.023045Z의 경우, 해당 시간을 나타내는 객체는 45만분의 1초 이전의 2000-01-01T00:00:00.023Z 시간을 나타내는 객체와 동일한 시간을 나타냅니다. 주어진 시간이 NaN인 경우, 결과는 특정 시간을 나타내지 않는 시간을 나타내는 Date 객체가 됩니다.

JavaScript

이 명세서에서 설명하는 언어의 일부는 JavaScript를 기본 스크립팅 언어로만 지원합니다. [JAVASCRIPT]

"JavaScript"라는 용어는 ECMAScript라는 공식 용어 대신 ECMA-262를 지칭하는 데 사용되며, 이는 JavaScript가 더 널리 알려져 있기 때문입니다.

다음 용어는 JavaScript 명세서에 정의되어 있으며, 이 명세서에서 사용됩니다:

JavaScript를 지원하는 사용자 에이전트는 동적 코드 브랜드 체크 제안을 구현해야 합니다. 이 명세서에서 사용하는 다음 용어가 해당 제안에 정의되어 있습니다: [JSDYNAMICCODEBRANDCHECKS]

JavaScript를 지원하는 사용자 에이전트는 또한 ECMAScript 국제화 API를 구현해야 합니다. [JSINTL]

JavaScript를 지원하는 사용자 에이전트는 또한 Import Attributes 제안을 구현해야 합니다. 이 명세서에서 사용하는 다음 용어가 해당 제안에 정의되어 있습니다: [JSIMPORTATTRIBUTES]

JavaScript를 지원하는 사용자 에이전트는 또한 JSON 모듈 제안을 구현해야 합니다. 이 명세서에서 사용하는 다음 용어가 해당 제안에 정의되어 있습니다: [JSJSONMODULES]

JavaScript를 지원하는 사용자 에이전트는 또한 크기 조정 가능한 ArrayBuffer 및 확장 가능한 SharedArrayBuffer 제안을 구현해야 합니다. 이 명세서에서 사용하는 다음 용어가 해당 제안에 정의되어 있습니다: [JSRESIZABLEBUFFERS]

JavaScript를 지원하는 사용자 에이전트는 또한 Temporal 제안을 구현해야 합니다. 이 명세서에서 사용하는 다음 용어가 해당 제안에 정의되어 있습니다: [JSTEMPORAL]

WebAssembly

WebAssembly JavaScript Interface에서 정의된 용어는 다음과 같습니다: [WASMJS]

DOM

문서 객체 모델(DOM)은 문서와 그 내용의 표현입니다. DOM은 단순한 API가 아니라, HTML 구현의 적합성 기준이 이 명세서에서 DOM 작업의 관점에서 정의됩니다. [DOM]

이 명세서는 DOM을 통해 정의되며, 일부 기능은 DOM 인터페이스의 확장으로 정의되므로 구현체는 DOM과 UI 이벤트에서 정의된 이벤트를 지원해야 합니다. [DOM] [UIEVENTS]

특히, DOM에서 정의된 기능은 다음과 같습니다: [DOM]

다음 기능은 UI Events에 정의되어 있습니다: [UIEVENTS]

다음 기능은 Touch Events에 정의되어 있습니다: [TOUCH]

다음 기능은 Pointer Events에 정의되어 있습니다: [POINTEREVENTS]

다음 이벤트는 Clipboard API and events에 정의되어 있습니다: [CLIPBOARD-APIS]

이 사양에서는 때때로 이벤트의 타입을 참조하여 이름이라는 용어를 사용합니다. 예를 들어 "이름이 click인 이벤트" 또는 "이벤트 이름이 keypress인 경우"와 같이 사용됩니다. 이벤트의 "이름"과 "타입"은 동의어입니다.

다음 기능은 DOM Parsing and Serialization에 정의되어 있습니다: [DOMPARSING]

다음 기능은 Selection API에 정의되어 있습니다: [SELECTION]

사용자 에이전트는 execCommand에서 설명한 기능을 구현하는 것이 권장됩니다. [EXECCOMMAND]

다음 기능은 Fullscreen API에 정의되어 있습니다: [FULLSCREEN]

High Resolution Time는 다음 기능을 제공합니다: [HRT]

파일 API

이 명세서는 파일 API에 정의된 다음 기능들을 사용합니다: [FILEAPI]

인덱스된 데이터베이스 API

이 명세서는 인덱스된 데이터베이스 API에 정의된 인덱스된 데이터베이스 트랜잭션 정리 을 사용합니다. [INDEXEDDB]

미디어 소스 확장

다음 용어들은 미디어 소스 확장에 정의되어 있습니다: [MEDIASOURCE]

미디어 캡처 및 스트림

다음 용어들은 미디어 캡처 및 스트림에 정의되어 있습니다: [MEDIASTREAM]

리포팅

다음 용어들은 리포팅에 정의되어 있습니다: [REPORTING]

XMLHttpRequest

다음 기능들과 용어들은 XMLHttpRequest에 정의되어 있습니다: [XHR]

배터리 상태

다음 기능들은 배터리 상태 API에 정의되어 있습니다: [BATTERY]

미디어 쿼리

구현체는 미디어 쿼리를 지원해야 합니다. <media-condition> 기능이 그곳에 정의되어 있습니다. [MQ]

CSS 모듈

이 명세서의 구현에 CSS 전체에 대한 지원이 필수는 아니지만(특히 웹 브라우저의 경우 지원을 권장함), 일부 기능은 특정 CSS 요구 사항에 따라 정의됩니다.

이 명세서에서 무언가를 특정 CSS 문법에 따라 구문 분석해야 한다고 요구할 때, CSS 구문의 관련 알고리즘을 따라야 하며, 오류 처리 규칙도 포함됩니다. [CSSSYNTAX]

예를 들어, 사용자 에이전트는 스타일 시트의 끝을 예상치 못하게 발견할 때 모든 열린 구문을 닫아야 합니다. 따라서 색상 값으로 문자열 "rgb(0,0,0"(닫는 괄호가 누락된 경우)을 구문 분석할 때 이 오류 처리 규칙에 따라 닫는 괄호가 암시되어 검은색이 얻어집니다. 그러나 "rgb(0,0,"(괄호와 "blue" 값이 모두 누락된 경우)와 같은 유사한 구문은 열린 구문을 닫아도 적절한 값을 얻을 수 없으므로 구문 분석할 수 없습니다.

다음 용어와 기능은 CSS에서 정의됩니다: [CSS]

'display' 속성의 기본 버전은 CSS에 정의되어 있으며, 이 속성은 다른 CSS 모듈에 의해 확장됩니다. [CSS] [CSSRUBY] [CSSTABLE]

다음 용어와 기능은 CSS 박스 모델에 정의되어 있습니다: [CSSBOX]

다음 기능들은 CSS 논리적 속성에 정의되어 있습니다: [CSSLOGICAL]

다음 용어와 기능들은 CSS 색상에 정의되어 있습니다: [CSSCOLOR]

다음 용어는 CSS 이미지에 정의되어 있습니다: [CSSIMAGES]

페인트 소스 용어는 CSS 이미지 레벨 4에서 정의되었으며, CSS 'element()' 함수와 특정 HTML 요소 간의 상호작용을 정의하는 데 사용됩니다. [CSSIMAGES4]

다음 기능들은 CSS 배경 및 테두리에 정의되어 있습니다: [CSSBG]

CSS 배경 및 테두리는 다음과 같은 테두리 속성도 정의합니다: [CSSBG]

테두리 속성
상단 하단 왼쪽 오른쪽
너비 'border-top-width' 'border-bottom-width' 'border-left-width' 'border-right-width'
스타일 'border-top-style' 'border-bottom-style' 'border-left-style' 'border-right-style'
색상 'border-top-color' 'border-bottom-color' 'border-left-color' 'border-right-color'

다음 기능들은 CSS 박스 정렬에 정의되어 있습니다: [CSSALIGN]

다음 용어와 기능들은 CSS 디스플레이에 정의되어 있습니다: [CSSDISPLAY]

다음 기능들은 CSS 플렉서블 박스 레이아웃에 정의되어 있습니다: [CSSFLEXBOX]

다음 용어와 기능들은 CSS 폰트에 정의되어 있습니다: [CSSFONTS]

다음 기능들은 CSS 그리드 레이아웃에 정의되어 있습니다: [CSSGRID]

다음 용어는 CSS 인라인 레이아웃에 정의되어 있습니다: [CSSINLINE]

다음 용어와 기능들은 CSS 박스 사이징에 정의되어 있습니다: [CSSSIZING]

다음 기능들은 CSS 목록 및 카운터에 정의되어 있습니다. [CSSLISTS]

다음 기능들은 CSS 오버플로우에 정의되어 있습니다. [CSSOVERFLOW]

다음 용어와 기능들은 CSS 위치 지정 레이아웃에 정의되어 있습니다: [CSSPOSITION]

다음 기능들은 CSS 멀티컬럼 레이아웃에 정의되어 있습니다. [CSSMULTICOL]

'ruby-base' 값은 'display' 속성의 값으로 CSS 루비 레이아웃에 정의되어 있습니다. [CSSRUBY]

다음 기능들은 CSS 테이블에 정의되어 있습니다: [CSSTABLE]

다음 기능들은 CSS 텍스트에 정의되어 있습니다: [CSSTEXT]

다음 기능들은 CSS 쓰기 모드에 정의되어 있습니다: [CSSWM]

다음 기능들은 CSS 기본 사용자 인터페이스에 정의되어 있습니다: [CSSUI]

애니메이션을 업데이트하고 이벤트를 전송하는 알고리즘은 웹 애니메이션에 정의되어 있습니다. [WEBANIMATIONS]

스크립팅을 지원하는 구현은 CSS 객체 모델을 지원해야 합니다. 다음 기능과 용어는 CSSOM 명세에서 정의되어 있습니다: [CSSOM] [CSSOMVIEW]

다음 기능들과 용어들은 CSS Syntax에 정의되어 있습니다: [CSSSYNTAX]

다음 용어들은 Selectors에 정의되어 있습니다: [SELECTORS]

다음 기능들은 CSS Values and Units에 정의되어 있습니다: [CSSVALUES]

다음 기능들은 CSS View Transitions에 정의되어 있습니다: [CSSVIEWTRANSITIONS]

스타일 속성 용어는 CSS Style Attributes에 정의되어 있습니다. [CSSATTR]

다음 용어들은 CSS Cascading and Inheritance에 정의되어 있습니다: [CSSCASCADE]

CanvasRenderingContext2D 객체의 글꼴 사용은 CSS FontsFont Loading 명세에서 설명된 기능들에 따라 달라집니다. 특히 FontFace 객체와 글꼴 소스 개념에 의존합니다. [CSSFONTS] [CSSFONTLOAD]

다음 인터페이스들과 용어들은 Geometry Interfaces에 정의되어 있습니다: [GEOMETRY]

다음 용어들은 CSS Scoping에 정의되어 있습니다: [CSSSCOPING]

다음 용어들과 기능들은 CSS Color Adjustment에 정의되어 있습니다: [CSSCOLORADJUST]

다음 용어들은 CSS Pseudo-Elements에 정의되어 있습니다: [CSSPSEUDO]

다음 용어들은 CSS Containment에 정의되어 있습니다: [CSSCONTAIN]

Intersection Observer

다음 용어는 Intersection Observer에 정의되어 있습니다: [INTERSECTIONOBSERVER]

Resize Observer

다음 용어들은 Resize Observer에 정의되어 있습니다: [RESIZEOBSERVER]

WebGL

다음 인터페이스들은 WebGL 명세서에 정의되어 있습니다: [WEBGL]

WebGPU

다음 인터페이스들은 WebGPU에 정의되어 있습니다: [WEBGPU]

WebVTT

구현체들은 WebVTT를 자막, 캡션, 메타데이터 등의 텍스트 트랙 형식으로 지원할 수 있습니다. [WEBVTT]

이 명세서에서 사용된 다음 용어들은 WebVTT에 정의되어 있습니다:

ARIA

role 속성은 Accessible Rich Internet Applications (ARIA)에 정의되어 있으며, 다음 역할들도 포함됩니다: [ARIA]

또한, 다음 aria-* 콘텐츠 속성들도 ARIA에 정의되어 있습니다: [ARIA]

마지막으로, 다음 용어들은 ARIA에 정의되어 있습니다: [ARIA]

콘텐츠 보안 정책

다음 용어들은 콘텐츠 보안 정책에 정의되어 있습니다: [CSP]

Service Workers

다음 용어들은 Service Workers에 정의되어 있습니다: [SW]

보안 컨텍스트

다음 알고리즘들은 보안 컨텍스트에 정의되어 있습니다: [SECURE-CONTEXTS]

권한 정책

다음 용어들은 권한 정책에 정의되어 있습니다: [PERMISSIONSPOLICY]

결제 요청 API

다음 기능은 결제 요청 API에서 정의되었습니다: [PAYMENTREQUEST]

MathML

이 규격에서는 MathML 전체를 지원할 필요는 없지만 (웹 브라우저에서는 권장됨), 특정 기능은 MathML의 일부 요소 구현에 의존합니다. [MATHML]

다음 기능은 수학적 마크업 언어 (MathML)에서 정의됩니다:

SVG

이 규격에서는 SVG 전체를 지원할 필요는 없지만 (웹 브라우저에서는 권장됨), 특정 기능은 SVG의 일부 요소 구현에 의존합니다.

SVG를 구현하는 사용자 에이전트는 SVG 2 사양을 구현해야 하며, 이전 버전은 지원하지 않습니다.

다음 기능은 SVG 2 사양에서 정의됩니다: [SVG]

필터 효과

다음 기능은 필터 효과에서 정의됩니다: [FILTERS]

합성 및 혼합

다음 기능은 합성 및 혼합에서 정의됩니다: [COMPOSITE]

백그라운드 작업의 협력적 스케줄링

다음 기능은 백그라운드 작업의 협력적 스케줄링에서 정의됩니다: [REQUESTIDLECALLBACK]

화면 방향

다음 용어는 화면 방향에서 정의됩니다: [SCREENORIENTATION]

저장소

다음 용어는 저장소에서 정의됩니다: [STORAGE]

웹 앱 매니페스트

다음 기능은 웹 앱 매니페스트에서 정의됩니다: [MANIFEST]

WebCodecs

다음 기능은 WebCodecs에서 정의됩니다: [WEBCODECS]

WebDriver

다음 용어는 WebDriver에서 정의됩니다: [WEBDRIVER]

WebDriver BiDi

다음 용어는 WebDriver BiDi에서 정의됩니다: [WEBDRIVERBIDI]

웹 암호화 API

다음 용어는 웹 암호화 API에서 정의됩니다: [WEBCRYPTO]

웹소켓

다음 용어는 웹소켓에서 정의됩니다: [WEBSOCKETS]

웹 전송

다음 용어는 웹 전송에서 정의됩니다: [WEBTRANSPORT]

웹 인증: 공개 키 자격 증명에 액세스하기 위한 API

다음 용어는 웹 인증: 공개 키 자격 증명에 액세스하기 위한 API에서 정의됩니다: [WEBAUTHN]

자격 증명 관리

다음 용어는 자격 증명 관리에서 정의됩니다: [CREDMAN]

콘솔

다음 용어는 콘솔에서 정의됩니다: [CONSOLE]

웹 잠금 API

다음 용어는 웹 잠금 API에서 정의됩니다: [WEBLOCKS]

신뢰된 유형

이 사양은 신뢰된 유형에서 정의된 다음 기능을 사용합니다: [TRUSTED-TYPES]


이 명세는 특정 네트워크 프로토콜, 스타일 시트 언어, 스크립팅 언어, 또는 위에 나열된 것들 외의 DOM 명세를 필수적으로 지원해야 하는 것은 아닙니다. 그러나 이 명세에서 설명하는 언어는 CSS를 스타일링 언어로, JavaScript를 스크립팅 언어로, HTTP를 네트워크 프로토콜로 편향되어 있으며, 여러 기능이 이러한 언어와 프로토콜이 사용되고 있음을 전제로 합니다.

HTTP 프로토콜을 구현하는 사용자 에이전트는 HTTP 상태 관리 메커니즘 (쿠키)도 구현해야 합니다. [HTTP] [COOKIES]

이 명세는 각 섹션에서 문자 인코딩, 이미지 형식, 오디오 형식 및 비디오 형식에 대한 추가적인 요구 사항이 있을 수 있습니다.

2.1.10 확장성

이 사양에 대한 공급업체별 독점 사용자 에이전트 확장은 강력히 권장되지 않습니다. 문서에서 이러한 확장을 사용해서는 안 되며, 그렇게 하면 상호 운용성이 감소하고 사용자 기반이 분열되어 특정 사용자 에이전트만 콘텐츠에 접근할 수 있게 됩니다.

모든 확장은 이 사양에서 정의된 기능을 모순되거나 비준수로 만들지 않도록 정의되어야 합니다.

예를 들어, 권장되지 않지만, 구현에서 사용자에게 현재 제어값을 선택하는 데 걸린 시간을 반환하는 "typeTime"이라는 새로운 IDL 속성을 컨트롤에 추가할 수 있습니다. 반면, 양식의 elements 배열에 나타나는 새로운 컨트롤을 정의하는 것은 위의 요구 사항을 위반하는 것으로, 이 사양에서 제공된 elements의 정의를 위반하는 것입니다.


이 사양에 대한 공급업체 중립적인 확장이 필요할 때, 이 사양을 적절히 업데이트하거나 이 사양의 요구 사항을 무효화하는 확장 사양을 작성할 수 있습니다. 이 사양을 적용하는 사람이 해당 확장 사양의 요구 사항을 인정하기로 결정하면, 해당 확장 사양은 이 사양의 준수 요구 사항의 목적에 대해 적용 가능한 사양이 됩니다.

누군가는 임의의 바이트 스트림을 준수하는 것으로 정의하는 사양을 작성한 후, 자신이 만든 무작위 데이터가 준수한다고 주장할 수 있습니다. 그러나 이것이 모든 목적에서 실제로 준수된다는 의미는 아닙니다. 다른 사람이 해당 사양이 자신의 작업에 적용되지 않는다고 결정하면, 해당 무작위 데이터가 단지 쓰레기일 뿐이며 전혀 준수되지 않는다고 정당하게 말할 수 있습니다. 준수에 관한 한, 특정 커뮤니티에서 중요한 것은 그 커뮤니티가 적용 가능한 것으로 동의하는 것입니다.


사용자 에이전트는 이해하지 못하는 요소와 속성을 의미적으로 중립적으로 취급해야 하며, 이를 DOM에 남겨두고(CSS 프로세서의 경우 CSS에 따라 스타일을 지정) 의미를 유추해서는 안 됩니다.

기능에 대한 지원이 비활성화된 경우(예: 보안 문제를 완화하기 위한 긴급 조치, 개발 지원, 성능 문제 등), 사용자 에이전트는 해당 기능에 대한 지원이 전혀 없었던 것처럼 행동해야 하며, 해당 기능이 이 사양에서 언급되지 않은 것처럼 행동해야 합니다. 예를 들어, 특정 기능이 Web IDL 인터페이스의 속성을 통해 접근되는 경우, 해당 속성 자체는 해당 인터페이스를 구현하는 객체에서 생략되어야 하며, 속성을 객체에 남겨두고 null을 반환하거나 예외를 발생시키는 것은 충분하지 않습니다.

2.1.11 XPath 및 XSLT와의 상호작용

이 사양에 설명된 방식으로 파싱되거나 생성된 HTML 문서에서 작동하는 XPath 1.0의 구현은 다음 편집이 XPath 1.0 사양에 적용된 것처럼 작동해야 합니다.

먼저, 다음 단락을 제거합니다:

노드 테스트의 QName은 표현 컨텍스트에서 네임스페이스 선언을 사용하여 확장된 이름으로 확장됩니다. 이는 시작 및 종료 태그의 요소 유형 이름에 대해 확장이 수행되는 방식과 동일하지만, xmlns로 선언된 기본 네임스페이스는 사용되지 않습니다: QName에 접두사가 없으면 네임스페이스 URI는 null입니다 (속성 이름이 확장되는 방식과 동일합니다). QName에 표현 컨텍스트에서 네임스페이스 선언이 없는 접두사가 있는 경우 오류가 발생합니다.

그런 다음, 다음 내용으로 대체합니다:

노드 테스트의 QName은 표현 컨텍스트에서 네임스페이스 선언을 사용하여 확장된 이름으로 확장됩니다. QName에 접두사가 있는 경우, 이 접두사에 대한 네임스페이스 선언이 표현 컨텍스트에 있어야 하며, 해당 네임스페이스 URI는 이 접두사와 연결된 URI입니다. QName에 표현 컨텍스트에서 네임스페이스 선언이 없는 접두사가 있는 경우 오류가 발생합니다.

QName에 접두사가 없고 축의 주요 노드 유형이 요소인 경우 기본 요소 네임스페이스가 사용됩니다. 그렇지 않고 QName에 접두사가 없는 경우 네임스페이스 URI는 null입니다. 기본 요소 네임스페이스는 XPath 표현식의 컨텍스트 구성원입니다. DOM3 XPath API를 통해 XPath 표현식을 실행할 때 기본 요소 네임스페이스의 값은 다음과 같이 결정됩니다:

  1. 컨텍스트 노드가 HTML DOM에서 온 경우 기본 요소 네임스페이스는 "http://www.w3.org/1999/xhtml"입니다.
  2. 그 외의 경우 기본 요소 네임스페이스 URI는 null입니다.

이는 XPath 2.0의 기본 요소 네임스페이스 기능을 XPath 1.0에 추가하고, HTML 문서에 대해 HTML 네임스페이스를 기본 요소 네임스페이스로 사용하는 것과 동일합니다. 이는 이 사양이 HTML 요소에 사용되는 네임스페이스에 도입하는 변경 사항을 지원하면서도 기존 HTML 콘텐츠와 호환되도록 구현하려는 욕구에서 비롯되었으며, XPath 2.0보다는 XPath 1.0을 사용하려는 욕구에서 비롯되었습니다.

이 변경 사항은 HTML 요소에 사용되는 네임스페이스와 관련하여 이 사양이 도입하는 변경 사항을 지원하면서도 기존 콘텐츠와 호환되도록 구현하려는 욕구에서 비롯된 XPath 1.0 사양의 의도적인 위반입니다. [XPATH10]


XSLT 1.0 프로세서가 출력 메서드가 "html"인 경우(DOM으로 출력하는 경우 XSLT 1.0에서의 기본 규칙을 통해 명시적으로 또는 기본 규칙을 통해) 다음과 같이 영향을 받습니다:

변환 프로그램이 네임스페이스가 없는 요소를 출력하는 경우, 프로세서는 해당 DOM 요소 노드를 구성하기 전에 요소의 네임스페이스를 HTML 네임스페이스로 변경하고, 요소의 로컬 이름을 ASCII 소문자로 변환하며, 요소의 비네임스페이스 속성의 이름도 ASCII 소문자로 변환해야 합니다.

이 요구 사항은 DOM 기반 XSLT 변환과 호환되지 않을 수 있는 방식으로 HTML의 네임스페이스 및 대소문자 구분 규칙을 변경하기 때문에 필요합니다. (출력을 직렬화하는 프로세서는 영향을 받지 않습니다.) [XSLT10]


이 사양은 XSLT 처리와 HTML 파서 인프라가 상호작용하는 방식을 정확히 명시하지 않습니다 (예: XSLT 프로세서가 모든 요소를 열린 요소의 스택에 넣는 것처럼 작동하는지 여부). 그러나 XSLT 프로세서는 성공적으로 완료된 경우 파싱을 중지해야 하며, 중단된 경우 먼저 "interactive"로, 그 다음 "complete"로 현재 문서 준비 상태를 업데이트해야 합니다.


이 사양은 XSLT가 탐색 알고리즘과 상호작용하는 방식, 이벤트 루프와의 연관성, 또는 오류 페이지가 처리되는 방식(XSLT 오류가 증분 XSLT 출력을 대체하는지, 인라인으로 렌더링되는지 등)을 명시하지 않습니다.

XSLT와 HTML 간의 상호작용에 관한 추가적인 비규범적 설명이 script 요소 섹션에 있으며, XSLT, XPath, HTML 간의 상호작용에 관한 설명이 template 요소 섹션에 있습니다.

2.2 정책으로 제어되는 기능

Headers/Permissions-Policy/document-domain

하나의 엔진에서만 지원됩니다.

Firefox🔰 74+Safari지원 안 함Chrome🔰 88+
Opera?Edge🔰 88+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android지원 안 함WebView Android?Samsung Internet?Opera Android?

이 문서는 다음과 같은 정책으로 제어되는 기능을 정의합니다:

Headers/Feature-Policy/autoplay

Firefox🔰 74+Safari지원 안 함Chrome64+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Headers/Permissions-Policy/autoplay

하나의 엔진에서만 지원됩니다.

Firefox🔰 74+Safari지원 안 함Chrome88+
Opera?Edge88+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

2.3 공통 마이크로 구문

HTML에서는 날짜나 숫자와 같은 특정 데이터 유형을 허용하는 다양한 위치가 있습니다. 이 섹션에서는 해당 형식의 콘텐츠에 대한 적합성 기준과 이를 파싱하는 방법을 설명합니다.

구현자들은 아래 설명된 구문을 파싱하기 위해 사용할 수 있는 서드파티 라이브러리를 신중하게 검토할 것을 강력히 권장합니다. 예를 들어, 날짜 라이브러리는 이 사양에서 요구하는 것과 다른 오류 처리 동작을 구현할 가능성이 큽니다. 이는 유사한 날짜 구문을 설명하는 사양에서는 오류 처리 동작이 자주 정의되지 않기 때문에, 구현에 따라 오류를 처리하는 방식이 크게 다를 수 있기 때문입니다.

2.3.1 공통 파서 관용구

아래에 설명된 일부 마이크로 파서는 파싱할 문자열을 저장하는 input 변수와 input에서 다음에 파싱할 문자를 가리키는 position 변수를 가지는 패턴을 따릅니다.

2.3.2 불리언 속성

많은 속성이 불리언 속성입니다. 요소에 불리언 속성이 존재하면 true 값을 나타내고, 속성이 없으면 false 값을 나타냅니다.

속성이 존재하는 경우, 그 값은 빈 문자열이거나 속성의 표준 이름과 ASCII 대소문자 구분 없이 일치하는 값이어야 하며, 앞뒤에 공백이 없어야 합니다.

불리언 속성에는 "true"와 "false" 값을 사용할 수 없습니다. false 값을 나타내려면 속성을 완전히 생략해야 합니다.

다음은 체크되어 있고 비활성화된 체크박스의 예입니다. checkeddisabled 속성이 불리언 속성입니다.

<label><input type=checkbox checked name=cheese disabled> Cheese</label>

이 코드는 다음과 같이 동일하게 작성할 수 있습니다:

<label><input type=checkbox checked=checked name=cheese disabled=disabled> Cheese</label>

스타일을 혼합해서 사용하는 것도 가능하며, 다음과 같이 작성해도 여전히 동일한 의미를 갖습니다:

<label><input type='checkbox' checked name=cheese disabled=""> Cheese</label>

2.3.3 키워드와 열거형 속성

일부 속성은 열거형 속성이라 하며, 유한한 상태 집합을 가집니다. 이러한 속성의 상태는 속성의 값, 각 속성의 사양에 명시된 키워드/상태 매핑 세트, 그리고 속성의 사양에 명시될 수 있는 두 가지 특수 상태를 조합하여 도출됩니다. 이 특수 상태는 유효하지 않은 값의 기본값누락된 값의 기본값입니다.

여러 키워드가 동일한 상태에 매핑될 수 있습니다.

빈 문자열도 유효한 키워드일 수 있습니다. 누락된 값의 기본값은 속성이 존재하지 않을 때만 적용되며, 빈 문자열 값이 있는 경우에는 적용되지 않음을 유의하십시오.

속성의 상태를 결정하려면 다음 단계를 따르십시오:

  1. 속성이 지정되지 않은 경우:

    1. 속성에 누락된 값의 기본값 상태가 정의되어 있으면, 해당 누락된 값의 기본값 상태를 반환합니다.

    2. 그렇지 않으면 상태를 반환하지 않습니다.

  2. 속성의 값이 속성에 대해 정의된 키워드 중 하나와 ASCII 대소문자 구분 없이 일치하는 경우, 해당 키워드가 나타내는 상태를 반환합니다.

  3. 속성에 유효하지 않은 값의 기본값 상태가 정의되어 있으면, 해당 유효하지 않은 값의 기본값 상태를 반환합니다.

  4. 상태를 반환하지 않습니다.

작성 적합성 기준을 위해, 열거형 속성이 지정된 경우 해당 속성의 값은 해당 속성의 적합한 키워드 중 하나와 ASCII 대소문자 구분 없이 일치해야 하며, 앞뒤에 공백이 없어야 합니다.

반영 목적으로, 키워드가 매핑되는 상태는 표준 키워드를 가진다고 합니다. 이는 다음과 같이 결정됩니다:

2.3.4 숫자

2.3.4.1 부호 있는 정수

문자열이 하나 이상의 ASCII 숫자로 구성되고, 선택적으로 U+002D 하이픈-마이너스 문자(-)로 시작하는 경우, 그 문자열은 유효한 정수입니다.

U+002D 하이픈-마이너스(-) 접두사가 없는 유효한 정수는 해당 숫자 문자열로 나타낸 10진수 숫자를 나타냅니다. U+002D 하이픈-마이너스(-) 접두사가 있는 유효한 정수는 하이픈-마이너스 뒤에 나오는 숫자 문자열로 나타낸 10진수 숫자에서 0을 뺀 값을 나타냅니다.

정수 파싱 규칙은 다음 알고리즘에 제시된 대로입니다. 호출될 때, 주어진 순서대로 단계를 따라야 하며, 값을 반환하는 첫 번째 단계에서 중단합니다. 이 알고리즘은 정수 또는 오류를 반환합니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

  3. sign을(를) "positive"로 설정합니다.

  4. ASCII 공백을 건너뜁니다 position이 가리키는 input 내에서.

  5. positioninput의 끝을 지난 경우, 오류를 반환합니다.

  6. position이 가리키는 문자(첫 번째 문자)가 U+002D 하이픈-마이너스 문자(-)인 경우:

    1. sign을(를) "negative"로 설정합니다.
    2. position을(를) 다음 문자로 이동시킵니다.
    3. positioninput의 끝을 지난 경우, 오류를 반환합니다.

    그렇지 않고 position이 가리키는 문자(첫 번째 문자)가 U+002B 플러스 기호(+)인 경우:

    1. position을(를) 다음 문자로 이동시킵니다. ("+"는 무시되지만, 이는 적합하지 않습니다.)
    2. positioninput의 끝을 지난 경우, 오류를 반환합니다.
  7. position이 가리키는 문자가 ASCII 숫자가 아니면, 오류를 반환합니다.

  8. 코드 포인트 시퀀스를 수집합니다 position이 가리키는 input에서 ASCII 숫자로 구성된 시퀀스를 수집하고, 결과 시퀀스를 10진수 정수로 해석합니다. value을(를) 그 정수로 설정합니다.

  9. sign이 "positive"이면 value를 반환하고, 그렇지 않으면 value에서 0을 뺀 결과를 반환합니다.

2.3.4.2 음이 아닌 정수

문자열이 하나 이상의 ASCII 숫자로 구성된 경우, 그 문자열은 유효한 음이 아닌 정수입니다.

유효한 음이 아닌 정수는 해당 숫자 문자열로 나타낸 10진수 숫자를 나타냅니다.

음이 아닌 정수를 파싱하는 규칙은 다음 알고리즘에 제시된 대로입니다. 호출될 때, 주어진 순서대로 단계를 따라야 하며, 값을 반환하는 첫 번째 단계에서 중단합니다. 이 알고리즘은 0, 양의 정수 또는 오류를 반환합니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. value을(를) 정수 파싱 규칙을 사용하여 input을 파싱한 결과로 설정합니다.

  3. value가 오류이면, 오류를 반환합니다.

  4. value가 0보다 작으면, 오류를 반환합니다.

  5. value을(를) 반환합니다.

2.3.4.3 부동 소수점 숫자

문자열이 다음으로 구성된 경우, 그 문자열은 유효한 부동 소수점 숫자입니다:

  1. 선택적으로, U+002D 하이픈-마이너스 문자(-).

  2. 다음 중 하나 또는 둘 다, 주어진 순서대로:

    1. 하나 이상의 ASCII 숫자.

    2. 다음 두 가지, 주어진 순서대로:

      1. 하나의 U+002E 풀 스톱 문자(.).

      2. 하나 이상의 ASCII 숫자.

  3. 선택적으로:

    1. U+0065 라틴 소문자 e (e) 또는 U+0045 라틴 대문자 E (E).

    2. 선택적으로, U+002D 하이픈-마이너스 문자(-) 또는 U+002B 플러스 기호(+).

    3. 하나 이상의 ASCII 숫자.

유효한 부동 소수점 숫자는 유효숫자(significand)를 10의 지수승(exponent)으로 곱한 값으로 나타낸 숫자입니다. 여기서 유효숫자는 첫 번째 숫자로, 10진수로 해석됩니다(소수점 및 소수점 이후 숫자가 있을 경우 포함하며, 문자열 전체가 U+002D 하이픈-마이너스 문자(-)로 시작하고 숫자가 0이 아닌 경우 유효숫자를 음수로 해석). 지수는 E 뒤에 나오는 숫자입니다(숫자가 0이 아닌 경우, E와 숫자 사이에 U+002D 하이픈-마이너스 문자(-)가 있으면 지수를 음수로 해석하며, 그렇지 않으면 E와 숫자 사이에 U+002B 플러스 기호(+)가 있을 경우 이를 무시합니다). E가 없으면 지수는 0으로 처리됩니다.

Infinity 및 NaN(숫자가 아님) 값은 유효한 부동 소수점 숫자가 아닙니다.

유효한 부동 소수점 숫자 개념은 일반적으로 저자가 사용할 수 있는 것을 제한하는 데만 사용되며, 사용자 에이전트 요구사항은 아래의 부동 소수점 숫자 값을 파싱하는 규칙을 사용합니다(예: max 속성이 progress 요소에 있는 경우). 그러나 일부 경우에는 사용자 에이전트 요구사항에 문자열이 유효한 부동 소수점 숫자인지 확인하는 것이 포함됩니다(예: 값 정화 알고리즘에서 Number 상태가 input 요소에 있는 경우, 또는 srcset 속성 파싱 알고리즘에서).

부동 소수점 숫자로서 숫자 n의 최적 표현ToString(n)을 실행하여 얻은 문자열입니다. ToString 추상 연산은 고유하게 결정되지 않습니다. 특정 값에 대해 ToString에서 얻을 수 있는 여러 문자열이 있을 때, 사용자 에이전트는 항상 해당 값에 대해 동일한 문자열을 반환해야 합니다(다른 사용자 에이전트에서 사용된 값과 다를 수 있음에도 불구하고).

부동 소수점 숫자 값을 파싱하는 규칙은 다음 알고리즘에 제시된 대로입니다. 이 알고리즘은 반환하는 단계에서 즉시 중단해야 합니다. 이 알고리즘은 숫자 또는 오류를 반환합니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

  3. value를 1로 설정합니다.

  4. divisor를 1로 설정합니다.

  5. exponent를 1로 설정합니다.

  6. ASCII 공백을 건너뜁니다 position이 가리키는 input 내에서.

  7. positioninput의 끝을 지난 경우, 오류를 반환합니다.

  8. position이 가리키는 문자가 U+002D 하이픈-마이너스 문자(-)인 경우:

    1. valuedivisor를 −1로 변경합니다.
    2. position을(를) 다음 문자로 이동시킵니다.
    3. positioninput의 끝을 지난 경우, 오류를 반환합니다.

    그렇지 않고 position이 가리키는 문자(첫 번째 문자)가 U+002B 플러스 기호(+)인 경우:

    1. position을(를) 다음 문자로 이동시킵니다. ("+"는 무시되지만, 이는 적합하지 않습니다.)
    2. positioninput의 끝을 지난 경우, 오류를 반환합니다.
  9. position이 가리키는 문자가 U+002E 풀 스톱 문자(.)이고, 그 다음 문자가 ASCII 숫자인 경우, value를 0으로 설정하고 fraction 단계로 이동합니다.

  10. position이 가리키는 문자가 ASCII 숫자가 아니면, 오류를 반환합니다.

  11. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집하고, 이를 10진수 정수로 해석하여 value에 곱합니다.

  12. positioninput의 끝을 지난 경우, conversion 단계로 이동합니다.
  13. Fraction: position이 가리키는 문자가 U+002E 풀 스톱(.)인 경우, 다음 단계를 실행합니다:

    1. position을(를) 다음 문자로 이동시킵니다.
    2. positioninput의 끝을 지나거나, position이 가리키는 문자가 ASCII 숫자, U+0065 라틴 소문자 e (e), 또는 U+0045 라틴 대문자 E (E)가 아닌 경우, conversion 단계로 이동합니다.

    3. position이 가리키는 문자가 U+0065 라틴 소문자 e 또는 U+0045 라틴 대문자 E이면, 이 단계의 나머지를 건너뜁니다.

    4. Fraction loop: divisor에 10을 곱합니다.

    5. position이 가리키는 문자를 10진수 숫자(0..9)로 해석하고 divisor로 나눈 값을 value에 더합니다.
    6. position을(를) 다음 문자로 이동시킵니다.
    7. positioninput의 끝을 지난 경우, conversion 단계로 이동합니다.

    8. position이 가리키는 문자가 ASCII 숫자인 경우, 이 단계의 fraction loop로 돌아갑니다.

  14. position이 가리키는 문자가 U+0065 (e) 또는 U+0045 (E)인 경우, 다음을 실행합니다:

    1. position을(를) 다음 문자로 이동시킵니다.
    2. positioninput의 끝을 지난 경우, conversion 단계로 이동합니다.

    3. position이 가리키는 문자가 U+002D 하이픈-마이너스 문자(-)인 경우:

      1. exponent를 −1로 변경합니다.
      2. position을(를) 다음 문자로 이동시킵니다.
      3. positioninput의 끝을 지난 경우, conversion 단계로 이동합니다.

      그렇지 않고 position이 가리키는 문자가 U+002B 플러스 기호(+)인 경우:

      1. position을(를) 다음 문자로 이동시킵니다.
      2. positioninput의 끝을 지난 경우, conversion 단계로 이동합니다.
    4. position이 가리키는 문자가 ASCII 숫자가 아니면, conversion 단계로 이동합니다.
    5. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집하고, 이를 10진수 정수로 해석하여 exponent에 곱합니다.

    6. value에 10의 exponent 제곱 값을 곱합니다.
  15. Conversion: S를 유한한 IEEE 754 배정밀도 부동 소수점 값 집합(−0 제외)으로 설정하되, 21024 및 −21024를 추가합니다.

  16. rounded-valuevalue에 가장 가까운 S의 숫자로 설정하되, 두 개의 값이 동일하게 가까운 경우 유효숫자가 짝수인 숫자를 선택합니다(이 목적을 위해 21024 및 −21024는 유효숫자가 짝수로 간주됨).

  17. rounded-value가 21024 또는 −21024인 경우, 오류를 반환합니다.

  18. rounded-value을(를) 반환합니다.

2.3.4.4 백분율과 길이

차원 값을 파싱하는 규칙은 다음 알고리즘에 제시된 대로입니다. 호출될 때, 주어진 순서대로 단계를 따라야 하며, 값을 반환하는 첫 번째 단계에서 중단합니다. 이 알고리즘은 0.0 이상인 숫자 또는 실패를 반환합니다. 숫자가 반환된 경우, 이는 백분율 또는 길이로 추가로 분류됩니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) 위치 변수로 설정하며, 초기값은 input의 시작 위치입니다.

  3. ASCII 공백을 건너뜁니다 position이 가리키는 input 내에서.

  4. positioninput의 끝을 지나거나 input 내에서 position이 가리키는 코드 포인트가 ASCII 숫자가 아닌 경우, 실패를 반환합니다.

  5. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집하고, 이를 10진수 정수로 해석하여 value에 설정합니다.

  6. positioninput의 끝을 지난 경우, value을(를) 길이로 반환합니다.

  7. position이 가리키는 코드 포인트가 U+002E (.)인 경우, 다음을 실행합니다:

    1. position을(를) 1만큼 이동시킵니다.
    2. positioninput의 끝을 지나거나 position이 가리키는 코드 포인트가 ASCII 숫자가 아닌 경우, 현재 차원 값value, input, position과 함께 반환합니다.
    3. divisor에 1을 설정합니다.
    4. 다음 반복문을 실행합니다:

      1. divisor에 10을 곱합니다.
      2. position이 가리키는 코드 포인트를 10진수 숫자(0..9)로 해석하여 divisor로 나눈 값을 value에 더합니다.
      3. position을(를) 1만큼 이동시킵니다.
      4. positioninput의 끝을 지나면 value을(를) 길이로 반환합니다.
      5. position이 가리키는 코드 포인트가 ASCII 숫자가 아니면, 반복을 중단합니다.
  8. 현재 차원 값value, input, position과 함께 반환합니다.

현재 차원 값value, input, position이 주어진 경우, 다음과 같이 결정됩니다:

  1. positioninput의 끝을 지난 경우, value를 길이로 반환합니다.

  2. position이 가리키는 코드 포인트가 U+0025 (%)인 경우, value를 백분율로 반환합니다.

  3. value를 길이로 반환합니다.

2.3.4.5 0이 아닌 백분율과 길이

0이 아닌 차원 값을 파싱하는 규칙은 다음 알고리즘에 제시된 대로입니다. 호출될 때, 주어진 순서대로 단계를 따라야 하며, 값을 반환하는 첫 번째 단계에서 중단합니다. 이 알고리즘은 0.0보다 큰 숫자 또는 오류를 반환합니다. 숫자가 반환된 경우, 이는 백분율 또는 길이로 추가로 분류됩니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. value차원 값을 파싱하는 규칙을 사용하여 input을 파싱한 결과로 설정합니다.

  3. value가 오류이면, 오류를 반환합니다.

  4. value가 0이면, 오류를 반환합니다.

  5. value가 백분율인 경우, value를 백분율로 반환합니다.

  6. value를 길이로 반환합니다.

2.3.4.6 부동 소수점 숫자 목록

유효한 부동 소수점 숫자 목록유효한 부동 소수점 숫자가 U+002C 콤마 문자로 구분된 것입니다. 다른 문자가 없어야 합니다(예: ASCII 공백이 없어야 함). 또한, 부동 소수점 숫자의 개수나 허용되는 값의 범위에 제한이 있을 수 있습니다.

부동 소수점 숫자 목록을 파싱하는 규칙은 다음과 같습니다:

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

  3. numbers를 초기에는 비어 있는 부동 소수점 숫자 목록으로 설정합니다. 이 목록이 이 알고리즘의 결과가 됩니다.

  4. 코드 포인트 시퀀스를 수집합니다 position이 가리키는 input 내에서 ASCII 공백, U+002C 콤마, U+003B 세미콜론 문자를 수집합니다. 이는 앞부분의 구분 문자를 건너뜁니다.

  5. positioninput의 끝을 지나지 않았을 때:

    1. 코드 포인트 시퀀스를 수집합니다 position이 가리키는 input 내에서 ASCII 공백, U+002C 콤마, U+003B 세미콜론, ASCII 숫자, U+002E 풀 스톱, U+002D 하이픈-마이너스 문자가 아닌 코드 포인트를 수집합니다. 이는 앞부분의 쓰레기를 건너뜁니다.

    2. 코드 포인트 시퀀스를 수집합니다 position이 가리키는 input 내에서 ASCII 공백, U+002C 콤마, U+003B 세미콜론이 아닌 코드 포인트를 수집하고, 이를 unparsed number로 설정합니다.

    3. number부동 소수점 숫자 값을 파싱하는 규칙을 사용하여 unparsed number를 파싱한 결과로 설정합니다.

    4. number가 오류이면, number를 0으로 설정합니다.

    5. numbernumbers에 추가합니다.

    6. 코드 포인트 시퀀스를 수집합니다 position이 가리키는 input 내에서 ASCII 공백, U+002C 콤마, U+003B 세미콜론 문자를 수집합니다. 이는 구분 문자를 건너뜁니다.

  6. numbers을(를) 반환합니다.

2.3.4.7 차원 목록

차원 목록을 파싱하는 규칙은 다음과 같습니다. 이 규칙은 0개 이상의 숫자와 단위로 구성된 쌍의 목록을 반환합니다. 단위는 백분율, 상대적인, 절대적인 중 하나입니다.

  1. raw input을(를) 파싱 중인 문자열로 설정합니다.

  2. 만약 raw input의 마지막 문자가 U+002C 콤마 문자(,)인 경우, 해당 문자를 raw input에서 제거합니다.

  3. 문자열 raw input을 콤마로 나눕니다. raw tokens을(를) 생성된 토큰 목록으로 설정합니다.

  4. result을(를) 비어 있는 숫자/단위 쌍 목록으로 설정합니다.

  5. raw tokens의 각 토큰에 대해 다음 하위 단계를 실행합니다:

    1. input을(를) 해당 토큰으로 설정합니다.

    2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

    3. value를 0으로 설정합니다.

    4. unit을(를) 절대적인으로 설정합니다.

    5. positioninput의 끝을 지난 경우, unit을(를) 상대적인으로 설정하고 마지막 하위 단계로 이동합니다.

    6. position이 가리키는 문자가 ASCII 숫자인 경우, 코드 포인트 시퀀스를 수집합니다 input에서, 결과 시퀀스를 10진수 정수로 해석하여 value에 추가합니다.

    7. position이 가리키는 문자가 U+002E (.)인 경우:

      1. 코드 포인트 시퀀스를 수집합니다 ASCII 공백ASCII 숫자로 구성된 시퀀스를 input에서 수집합니다. s을(를) 생성된 시퀀스로 설정합니다.

      2. s에서 모든 ASCII 공백을 제거합니다.

      3. s이(가) 빈 문자열이 아닌 경우:

        1. lengths의 문자 수로 설정합니다.

        2. fraction을(를) s을(를) 10진수 정수로 해석한 결과로 설정하고, 그 숫자를 10length로 나눕니다.

        3. valuefraction을(를) 추가합니다.

    8. ASCII 공백을 건너뜁니다 input 내에서 position이 가리키는 위치에 따라.

    9. position이 가리키는 문자가 U+0025 퍼센트 기호(%)인 경우, unit을(를) 백분율로 설정합니다.

      그렇지 않고, position이 가리키는 문자가 U+002A 별표 문자(*)인 경우, unit을(를) 상대적인으로 설정합니다.

    10. resultvalueunit으로 구성된 항목을 추가합니다.

  6. result 목록을 반환합니다.

2.3.5 날짜와 시간

다음 알고리즘에서는, 해당 연도에 있는 일수는 다음과 같습니다: 이 1, 3, 5, 7, 8, 10, 또는 12이면 31일, 이 4, 6, 9, 또는 11이면 30일, 연도가 400으로 나누어 떨어지거나, 4로 나누어 떨어지지만 100으로 나누어 떨어지지 않는 경우 이 2이면 29일, 그렇지 않으면 28일. 이는 그레고리력의 윤년을 고려한 것입니다. [GREGORIAN]

이 섹션에서 정의된 날짜와 시간 구문에서 ASCII 숫자가 사용되는 경우, 이들은 10진수로 숫자를 나타냅니다.

여기서 설명하는 형식은 해당 ISO8601 형식의 하위 집합을 의도하고 있지만, 이 명세서는 ISO8601보다 훨씬 자세하게 파싱 규칙을 정의합니다. 따라서 구현자는 아래에 설명된 파싱 규칙을 구현하기 위해 날짜 파싱 라이브러리를 사용하기 전에 주의 깊게 검토해야 합니다. ISO8601 라이브러리가 날짜와 시간을 정확히 동일한 방식으로 파싱하지 않을 수 있습니다. [ISO8601]

이 명세서가 프롤렙틱 그레고리력을 참조하는 경우, 이는 현대 그레고리력을 의미하며, 연도 1로 소급하여 적용한 것입니다. 프롤렙틱 그레고리력에 있는 날짜는 이 명세서가 언급한 대로 해당 달력으로 설명된 것입니다. 그 당시(또는 장소)에 그 달력이 사용되지 않았더라도 마찬가지입니다. [GREGORIAN]

이 명세서에서 그레고리력을 와이어 형식으로 사용하는 것은 의사 결정에 참여한 사람들의 문화적 편향에서 비롯된 임의의 선택입니다. 저자를 위한 양식에서 날짜, 시간, 숫자 형식에 대해 논의하는 섹션과 양식 컨트롤의 지역화와 관련된 구현 참고 사항을 참고하십시오. time 요소도 참조하십시오.

2.3.5.1

은 특정 프롤렙틱 그레고리력 날짜로 구성되며, 시간대 정보가 없고 연도와 월 이상의 날짜 정보가 없는 것입니다. [GREGORIAN]

문자열이 연도을 나타내는 유효한 월 문자열인 경우, 이는 주어진 순서로 다음 구성 요소로 구성됩니다:

  1. 연도을(를) 나타내는 네 개 이상의 ASCII 숫자, 연도 > 0
  2. U+002D 하이픈-마이너스 문자(-)
  3. 을(를) 나타내는 두 개의 ASCII 숫자, 1 ≤ ≤ 12 범위 내

월 문자열을 파싱하는 규칙은 다음과 같습니다. 이는 연도와 월을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

  3. 월 구성 요소를 파싱하여 연도을 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  4. positioninput의 끝을 넘지 않는 경우, 실패합니다.

  5. 연도을 반환합니다.

월 구성 요소를 파싱하는 규칙은 주어진 input 문자열과 position을 사용합니다. 이는 연도와 월을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 최소한 네 글자가 되지 않으면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 연도로 설정합니다.

  2. 연도가 0보다 큰 숫자가 아니면, 알고리즘이 실패합니다.

  3. positioninput의 끝을 넘거나, position이 가리키는 문자가 U+002D 하이픈-마이너스 문자가 아닌 경우, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.

  4. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 로 설정합니다.

  5. 이 1 ≤ ≤ 12 범위 내 숫자가 아니면, 알고리즘이 실패합니다.

  6. 연도을 반환합니다.

2.3.5.2 날짜

날짜는 특정 프롤렙틱 그레고리력 날짜로 구성되며, 시간대 정보가 없고 연도, 월, 일로 구성됩니다. [GREGORIAN]

문자열이 연도, , 을 나타내는 유효한 날짜 문자열인 경우, 이는 주어진 순서로 다음 구성 요소로 구성됩니다:

  1. 유효한 월 문자열, 연도을 나타냅니다.
  2. U+002D 하이픈-마이너스 문자(-)
  3. 두 개의 ASCII 숫자, 을 나타내며, 1 ≤ maxday 범위 내. 여기서 maxday해당 월과 연도에 있는 일수입니다.

날짜 문자열을 파싱하는 규칙은 다음과 같습니다. 이는 날짜를 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

  3. 날짜 구성 요소를 파싱하여 연도, , 을 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  4. positioninput의 끝을 넘지 않는 경우, 실패합니다.

  5. date을(를) 연도, , 을 가진 날짜로 설정합니다.

  6. date를 반환합니다.

날짜 구성 요소를 파싱하는 규칙은 주어진 input 문자열과 position을 사용합니다. 이는 연도, 월, 일 또는 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. 월 구성 요소를 파싱하여 연도을 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  2. maxday을(를) 해당 월과 연도에 있는 일수로 설정합니다.

  3. positioninput의 끝을 넘거나, position이 가리키는 문자가 U+002D 하이픈-마이너스 문자가 아닌 경우, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.

  4. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 로 설정합니다.

  5. 이 1 ≤ maxday 범위 내 숫자가 아니면, 알고리즘이 실패합니다.

  6. 연도, , 을 반환합니다.

2.3.5.3 연도 없는 날짜

연도 없는 날짜는 그레고리력의 특정 월과 해당 월 내의 특정 일로 구성되며, 연도는 포함되지 않습니다. [GREGORIAN]

문자열이 을 나타내는 유효한 연도 없는 날짜 문자열인 경우, 이는 주어진 순서로 다음 구성 요소로 구성됩니다:

  1. 선택적으로, 두 개의 U+002D 하이픈-마이너스 문자(-)
  2. 두 개의 ASCII 숫자, 을 나타내며, 1 ≤ ≤ 12 범위 내
  3. U+002D 하이픈-마이너스 문자(-)
  4. 두 개의 ASCII 숫자, 을 나타내며, 1 ≤ maxday 범위 내. 여기서 maxday해당 월에 있는 일수이며, 임의의 윤년(예: 4 또는 2000년)의 기준을 따릅니다.

다시 말해, 이 "02"(2월)인 경우, 윤년으로 가정하여 은 29일이 될 수 있습니다.

연도 없는 날짜 문자열을 파싱하는 규칙은 다음과 같습니다. 이는 월과 일을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.

  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.

  3. 연도 없는 날짜 구성 요소를 파싱하여 을 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  4. positioninput의 끝을 넘지 않는 경우, 실패합니다.

  5. 을 반환합니다.

연도 없는 날짜 구성 요소를 파싱하는 규칙은 주어진 input 문자열과 position을 사용합니다. 이는 월과 일을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. 코드 포인트 시퀀스를 수집합니다 input에서 U+002D 하이픈-마이너스 문자(-)로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 0 또는 2 글자가 되지 않으면, 알고리즘이 실패합니다.

  2. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 로 설정합니다.

  3. 이 1 ≤ ≤ 12 범위 내 숫자가 아니면, 알고리즘이 실패합니다.

  4. maxday을(를) 해당 월의 임의의 윤년(예: 4 또는 2000년) 기준 일수로 설정합니다.

  5. positioninput의 끝을 넘거나, position이 가리키는 문자가 U+002D 하이픈-마이너스 문자가 아닌 경우, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.

  6. 코드 포인트 시퀀스를 수집합니다 input에서 ASCII 숫자로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 로 설정합니다.

  7. 이 1 ≤ maxday 범위 내 숫자가 아니면, 알고리즘이 실패합니다.

  8. 을 반환합니다.

2.3.5.4 시간

시간은 시간대 정보가 없는 특정 시간으로, 시간, 분, 초, 초의 일부로 구성됩니다.

문자열이 hour(시간), minute(분), second(초)을 나타내는 유효한 시간 문자열인 경우, 이는 주어진 순서로 다음 구성 요소로 구성됩니다:

  1. 두 개의 ASCII 숫자, hour을 나타내며, 0 ≤ hour ≤ 23 범위 내
  2. U+003A 콜론 문자 (:)
  3. 두 개의 ASCII 숫자, minute을 나타내며, 0 ≤ minute ≤ 59 범위 내
  4. 만약 second가 0이 아닌 경우, 또는 선택적으로 second가 0인 경우:
    1. U+003A 콜론 문자 (:)
    2. 두 개의 ASCII 숫자, second의 정수 부분을 나타내며, 0 ≤ second ≤ 59 범위 내
    3. 만약 second가 정수가 아닌 경우, 또는 선택적으로 second가 정수인 경우:
      1. U+002E 마침표 문자 (.)
      2. 하나, 두 개 또는 세 개의 ASCII 숫자, second의 소수 부분을 나타냄

second 구성 요소는 60 또는 61이 될 수 없습니다. 윤초는 표현할 수 없습니다.

시간 문자열을 파싱하는 규칙은 다음과 같습니다. 이는 시간 또는 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.
  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.
  3. 시간 구성 요소를 파싱하여 hour, minute, second을(를) 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.
  4. positioninput의 끝을 넘지 않는 경우, 실패합니다.
  5. hour, minute, second로 구성된 time을 반환합니다.

시간 구성 요소를 파싱하는 규칙은 주어진 input 문자열과 position을 사용합니다. 이는 시간, 분, 초를 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. 코드 포인트 시퀀스를 수집하여 input에서 ASCII 숫자 두 개로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 hour로 설정합니다.
  2. hour이 0 ≤ hour ≤ 23 범위 내 숫자가 아니면, 알고리즘이 실패합니다.
  3. positioninput의 끝을 넘거나 position이 가리키는 문자가 U+003A 콜론 문자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.
  4. 코드 포인트 시퀀스를 수집하여 input에서 ASCII 숫자 두 개로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 정확히 두 글자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 정수로 해석하여 해당 숫자를 minute으로 설정합니다.
  5. minute이 0 ≤ minute ≤ 59 범위 내 숫자가 아니면, 알고리즘이 실패합니다.
  6. second을 0으로 설정합니다.
  7. positioninput의 끝을 넘지 않고 position이 가리키는 문자가 U+003A (:)인 경우:
    1. positioninput에서 다음 문자로 이동시킵니다.
    2. positioninput의 끝을 넘거나 마지막 문자에 도달했거나, position부터 시작하는 input의 다음 두 문자가 모두 ASCII 숫자가 아닌 경우, 알고리즘이 실패합니다.
    3. 코드 포인트 시퀀스를 수집하여 input에서 ASCII 숫자 또는 U+002E 마침표 문자로 구성된 시퀀스를 수집합니다. 수집된 시퀀스가 세 글자 길이이거나, 세 글자보다 길면서 세 번째 문자가 U+002E 마침표 문자가 아닌 경우, 또는 U+002E 마침표 문자가 두 개 이상 포함된 경우, 알고리즘이 실패합니다. 그렇지 않으면, 생성된 시퀀스를 10진수 숫자(소수 부분 포함 가능)로 해석합니다. second를 해당 숫자로 설정합니다.
    4. second이 0 ≤ second  < 60 범위 내 숫자가 아니면, 알고리즘이 실패합니다.
  8. hour, minute, second을 반환합니다.
2.3.5.5 로컬 날짜와 시간

로컬 날짜와 시간은 특정 프로렙틱 그레고리력 날짜로, 연도, 월, 일로 구성되며, 시간은 시, 분, 초 및 초의 일부로 구성되지만, 시간대 정보는 포함되지 않습니다. [GREGORIAN]

문자열이 날짜와 시간을 나타내는 유효한 로컬 날짜 및 시간 문자열인 경우, 이는 주어진 순서로 다음 구성 요소로 구성됩니다:

  1. 유효한 날짜 문자열, 날짜를 나타냄
  2. U+0054 라틴 대문자 T 문자(T) 또는 U+0020 공백 문자
  3. 유효한 시간 문자열, 시간을 나타냄

문자열이 날짜와 시간을 나타내는 유효한 정규화된 로컬 날짜 및 시간 문자열인 경우, 이는 주어진 순서로 다음 구성 요소로 구성됩니다:

  1. 유효한 날짜 문자열, 날짜를 나타냄
  2. U+0054 라틴 대문자 T 문자(T)
  3. 유효한 시간 문자열, 시간을 나타내며, 주어진 시간에 대해 가능한 한 짧은 문자열로 표현됨(예: 주어진 시간이 0초인 경우 초 구성 요소를 완전히 생략)

로컬 날짜 및 시간 문자열을 파싱하는 규칙은 다음과 같습니다. 이 규칙은 날짜와 시간을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.
  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.
  3. 날짜 구성 요소를 파싱하여 year, month, day를 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  4. positioninput의 끝을 넘었거나, position이 가리키는 문자가 U+0054 라틴 대문자 T 문자(T) 또는 U+0020 공백 문자가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.
  5. 시간 구성 요소를 파싱하여 hour, minute, second을(를) 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  6. positioninput의 끝을 넘지 않으면, 알고리즘이 실패합니다.
  7. year, month, day로 구성된 date을(를) 설정합니다.
  8. hour, minute, second로 구성된 time을(를) 설정합니다.
  9. datetime을 반환합니다.
2.3.5.6 시간대

시간대 오프셋은 시간과 분으로 이루어진 부호 있는 숫자를 의미합니다.

문자열이 시간대 오프셋을 나타내는 유효한 시간대 오프셋 문자열인 경우, 이는 다음 중 하나로 구성됩니다:

이 형식은 -23:59에서 +23:59까지의 시간대 오프셋을 허용합니다. 현재 실제 시간대의 오프셋 범위는 -12:00에서 +14:00까지이며, 실제 시간대의 오프셋의 분 구성 요소는 항상 00, 30 또는 45입니다. 그러나 시간대는 정치적 이유로 변동될 수 있기 때문에, 이 범위가 영원히 유지될 것이라는 보장은 없습니다.

역사적인 시간과 관련된 시간대 오프셋 사용에 대한 자세한 내용은 아래 전역 날짜 및 시간 섹션의 사용 설명 및 예제를 참조하십시오.

시간대 오프셋 문자열을 파싱하는 규칙은 다음과 같습니다. 이 규칙은 시간대 오프셋을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.
  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.
  3. 시간대 오프셋 구성 요소를 파싱하여 timezonehourstimezoneminutes를 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  4. positioninput의 끝을 넘지 않으면, 알고리즘이 실패합니다.
  5. timezonehourstimezoneminutes로 구성된 시간대 오프셋을 반환합니다.

시간대 오프셋 구성 요소를 파싱하는 규칙은 다음과 같습니다. 이 규칙은 시간대 오프셋의 시간과 분을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. position이 가리키는 문자가 U+005A 라틴 대문자 Z 문자(Z)인 경우:

    1. timezonehours를 0으로 설정합니다.
    2. timezoneminutes를 0으로 설정합니다.
    3. positioninput 내의 다음 문자로 이동시킵니다.
  2. position이 가리키는 문자가 U+002B 플러스 문자(+) 또는 U+002D 하이픈-마이너스 문자(-)인 경우:

    1. position이 가리키는 문자가 U+002B 플러스 문자(+)인 경우, sign을 "positive"로 설정합니다. 그렇지 않은 경우, 즉 U+002D 하이픈-마이너스 문자(-)인 경우, sign을 "negative"로 설정합니다.
    2. positioninput 내의 다음 문자로 이동시킵니다.
    3. 코드 포인트 시퀀스를 수집합니다 input에서 position이 가리키는 위치로부터 ASCII 숫자를 포함하는 시퀀스를 수집하고, 그 결과를 s로 설정합니다.
    4. s이 정확히 두 문자 길이인 경우:

      1. s을 10진수 정수로 해석합니다. 그 숫자를 timezonehours로 설정합니다.
      2. positioninput의 끝을 넘었거나 position이 가리키는 문자가 U+003A 콜론 문자가 아닌 경우, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.
      3. 코드 포인트 시퀀스를 수집합니다 input에서 position이 가리키는 위치로부터 ASCII 숫자를 포함하는 시퀀스를 수집합니다. 이 시퀀스가 정확히 두 문자 길이가 아니면, 알고리즘이 실패합니다. 그렇지 않으면, 그 결과 시퀀스를 10진수 정수로 해석합니다. 그 숫자를 timezoneminutes로 설정합니다.
    5. s이 정확히 네 문자 길이인 경우:

      1. s의 첫 두 문자를 10진수 정수로 해석합니다. 그 숫자를 timezonehours로 설정합니다.
      2. s의 마지막 두 문자를 10진수 정수로 해석합니다. 그 숫자를 timezoneminutes로 설정합니다.
    6. 그 외의 경우, 알고리즘이 실패합니다.
    7. timezonehours이(가) 0 ≤ timezonehours ≤ 23 범위 내에 있지 않으면, 알고리즘이 실패합니다.
    8. sign이 "negative"인 경우, timezonehours을 음수로 설정합니다.
    9. timezoneminutes이(가) 0 ≤ timezoneminutes ≤ 59 범위 내에 있지 않으면, 알고리즘이 실패합니다.
    10. sign이 "negative"인 경우, timezoneminutes을 음수로 설정합니다.
  3. 그 외의 경우, 알고리즘이 실패합니다.
  4. timezonehourstimezoneminutes을 반환합니다.
2.3.5.7 전역 날짜 및 시간

전역 날짜 및 시간은 특정한 프롤렙틱 그레고리력 날짜로 구성되며, 연도, 월, 일, 시간(시간, 분, 초, 소수 초) 및 시간대 오프셋(부호 있는 시간 및 분 수)을 포함합니다. [GREGORIAN]

문자열이 날짜, 시간, 그리고 시간대 오프셋을 나타내는 유효한 전역 날짜 및 시간 문자열인 경우, 이는 다음 구성 요소들로 주어진 순서대로 구성됩니다:

  1. 유효한 날짜 문자열로 날짜를 나타냄
  2. U+0054 라틴 대문자 T 문자(T) 또는 U+0020 공백 문자
  3. 유효한 시간 문자열로 시간을 나타냄
  4. 유효한 시간대 오프셋 문자열로 시간대 오프셋을 나타냄

UTC가 형성되기 전의 날짜의 시간은 UTC가 아닌 UT1(0° 경도의 현대 지구 태양 시간) 기준으로 표현하고 해석해야 하며, 시간대가 형성되기 전의 시간은 그리니치 런던에서 관측된 시간과 적절한 현지 시간 간의 차이를 대략적으로 나타내는 명시적인 시간대 오프셋과 함께 UT1 시간으로 표현하고 해석해야 합니다.

다음은 유효한 전역 날짜 및 시간 문자열로 작성된 날짜의 몇 가지 예입니다.

"0037-12-13 00:00Z"
네로 황제의 생일에 런던 시간으로 자정을 나타냅니다. 이 날짜가 실제로 어떤 날짜인지에 대한 논의는 아래를 참조하세요.
"1979-10-14T12:00:00.001-04:00"
1979년 10월 14일, 미국 동부 해안의 일광 절약 시간제 사용 시간으로 정오 직후 1밀리초를 나타냅니다.
"8592-01-01T02:09+02:09"
UTC 기준으로 8592년 1월 1일 자정을 나타냅니다. 해당 시간대는 UTC보다 2시간 9분 앞서며, 이는 현재 실제 시간대는 아니지만 허용됩니다.

이 날짜들에서 주목할 점은 다음과 같습니다:

전역 날짜 및 시간 문자열을 파싱하는 규칙은 다음과 같습니다. 이 규칙은 UTC 시간과 표시 또는 라운드 트립을 위한 관련 시간대 오프셋 정보를 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.
  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.
  3. 날짜 구성 요소를 파싱하여 year, month, day를 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  4. positioninput의 끝을 넘었거나 position이 가리키는 문자가 U+0054 라틴 대문자 T 문자(T) 또는 U+0020 공백 문자가 아닌 경우, 알고리즘이 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.
  5. 시간 구성 요소를 파싱하여 hour, minute, second를 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  6. positioninput의 끝을 넘었다면, 알고리즘이 실패합니다.
  7. 시간대 오프셋 구성 요소를 파싱하여 timezonehourstimezoneminutes를 얻습니다. 이 과정에서 실패하면, 알고리즘이 실패합니다.

  8. positioninput의 끝을 넘지 않았다면, 알고리즘이 실패합니다.
  9. timeyear, month, day, hour, minute, second으로 구성된 시간으로 설정하고, timezonehours 시간과 timezoneminutes 분을 뺀 시간을 구합니다. 이 시간은 UTC 시간대의 순간입니다.
  10. timezonetimezonehourstimezoneminutes로 설정합니다.
  11. timetimezone을 반환합니다.
2.3.5.8

는 주-연도 번호와 월요일부터 시작하는 7일 기간을 나타내는 주 번호로 구성됩니다. 이 달력 시스템에서 각 주-연도는 아래 정의된 대로 52주 또는 53주의 7일 기간을 포함합니다. 1969년 12월 29일 월요일(1969-12-29)에 시작하는 7일 기간은 1970년 주-연도에서 주 번호 1로 정의됩니다. 연속적인 주는 순차적으로 번호가 매겨집니다. 주-연도에서 번호 1 이전의 주는 이전 주-연도의 마지막 주이며, 그 반대의 경우도 마찬가지입니다. [GREGORIAN]

숫자 year로 된 주-연도는 프롤렙틱 그레고리력의 첫 번째 날(1월 1일)이 목요일인 경우, 또는 year가 400으로 나누어 떨어지거나 100으로 나누어 떨어지지 않는 4로 나누어 떨어지는 숫자이며, 첫 번째 날(1월 1일)이 수요일인 경우 53주를 포함합니다. 다른 모든 주-연도는 52주를 갖습니다.

마지막 날의 주 번호는 53주를 가진 주-연도의 경우 53이며, 52주를 가진 주-연도의 마지막 날의 주 번호는 52입니다.

특정 날의 주-연도 번호는 프롤렙틱 그레고리력에서 그 날을 포함하는 연도의 번호와 다를 수 있습니다. 주-연도 y의 첫 번째 주는 y년의 그레고리력의 첫 번째 목요일을 포함하는 주입니다.

현대적 목적에서는, 여기서 정의된 는 ISO 8601에서 정의된 ISO 주와 동일합니다. [ISO8601]

문자열이 주-연도 year와 주 week를 나타내는 유효한 주 문자열인 경우, 이는 다음 구성 요소들로 주어진 순서대로 구성됩니다:

  1. 네 자리 이상의 ASCII 숫자, year를 나타내며, year > 0
  2. U+002D 하이픈-마이너스 문자 (-)
  3. U+0057 라틴 대문자 W 문자 (W)
  4. 두 자리 ASCII 숫자, 주 week를 나타내며, 범위는 1 ≤ weekmaxweek이며, 여기서 maxweek는 주-연도 year마지막 날의 주 번호입니다.

주 문자열을 파싱하는 규칙은 다음과 같습니다. 이 규칙은 주-연도 번호와 주 번호를 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 지점에서는 알고리즘이 중단되고 아무것도 반환되지 않습니다.

  1. input을(를) 파싱 중인 문자열로 설정합니다.
  2. position을(를) input의 시작을 가리키는 포인터로 설정합니다.
  3. 코드 포인트 시퀀스를 수집합니다, input에서 position이 가리키는 ASCII 숫자로 이루어진 시퀀스를 수집하고, 수집된 시퀀스가 네 자리 이상이 아니면 실패합니다. 그렇지 않으면, 해당 시퀀스를 10진수로 해석하여 그 숫자를 year로 설정합니다.
  4. year이(가) 0보다 큰 숫자가 아니면 실패합니다.
  5. positioninput의 끝을 넘었거나, position이 가리키는 문자가 U+002D 하이픈-마이너스 문자가 아니면 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.
  6. positioninput의 끝을 넘었거나, position이 가리키는 문자가 U+0057 라틴 대문자 W 문자가 아니면 실패합니다. 그렇지 않으면, position을 한 문자 앞으로 이동시킵니다.
  7. 코드 포인트 시퀀스를 수집합니다, input에서 position이 가리키는 ASCII 숫자로 이루어진 시퀀스를 수집하고, 수집된 시퀀스가 정확히 두 자리가 아니면 실패합니다. 그렇지 않으면, 해당 시퀀스를 10진수로 해석하여 그 숫자를 week로 설정합니다.
  8. maxweek을(를) 주-연도 year의 마지막 날의 주 번호로 설정합니다.
  9. week이(가) 1 ≤ weekmaxweek 범위 내의 숫자가 아니면 실패합니다.
  10. positioninput의 끝을 넘지 않았으면 실패합니다.
  11. 주-연도 번호 year와 주 번호 week를 반환합니다.
2.3.5.9 지속 시간

지속 시간은 초 단위로 구성됩니다.

달과 초는 비교할 수 없습니다(달은 정확한 초의 수가 아니라 측정되는 특정 날짜에 따라 길이가 달라지는 기간이기 때문에). 따라서 이 사양에서 정의된 지속 시간에는 달(또는 12개월에 해당하는 연도)을 포함할 수 없습니다. 오직 특정 초의 수를 나타내는 지속 시간만 설명할 수 있습니다.

문자열이 지속 시간 t을 나타내는 유효한 지속 시간 문자열이라면, 다음 중 하나로 구성됩니다:

지속 시간 문자열을 구문 분석하는 규칙은 다음과 같습니다. 이 규칙은 지속 시간을 반환하거나 아무것도 반환하지 않습니다. 알고리즘이 "실패"했다고 말하면, 이는 그 시점에서 중단되고 아무것도 반환되지 않음을 의미합니다.

  1. input이 구문 분석 중인 문자열이라고 가정합니다.

  2. positioninput의 시작 부분을 가리키는 포인터로 가정합니다.

  3. months, seconds, component count를 모두 0으로 설정합니다.

  4. M-disambiguatorminutes로 설정합니다.

    이 플래그의 다른 값은 months입니다. 이 플래그는 ISO8601 지속 시간에서 "M" 단위를 분과 월을 구분하기 위해 사용됩니다. 월은 허용되지 않지만, 미래의 호환성을 위해 그리고 다른 컨텍스트에서 유효할 수 있는 ISO8601 지속 시간을 오해하지 않기 위해 구문 분석됩니다.

  5. ASCII 공백 문자를 건너뛰십시오 input 내에서 position을 기준으로.

  6. 만약 positioninput의 끝을 넘어섰다면, 실패합니다.

  7. 만약 input 내의 position이 가리키는 문자가 U+0050 라틴 대문자 P 문자라면, position을 다음 문자로 이동시키고, M-disambiguatormonths로 설정하고 ASCII 공백 문자를 건너뛰십시오 input 내에서 position을 기준으로.

  8. 다음의 과정을 반복합니다:

    1. units을 정의되지 않은 상태로 둡니다. 이것은 다음 값 중 하나로 설정됩니다: years, months, weeks, days, hours, minutes, seconds.

    2. next character를 정의되지 않은 상태로 둡니다. 이것은 input에서 문자를 처리하는 데 사용됩니다.

    3. 만약 positioninput의 끝을 넘어섰다면, 중단합니다.

    4. 만약 position이 가리키는 문자가 U+0054 라틴 대문자 T 문자라면, position을 다음 문자로 이동시키고, M-disambiguatorminutes로 설정하고, ASCII 공백 문자를 건너뛰십시오 input 내에서 position을 기준으로, 그리고 계속합니다.

    5. next characterinput 내의 position이 가리키는 문자로 설정합니다.

    6. 만약 next character가 U+002E 온점 문자(.)라면, N을 0으로 설정합니다. (position을 이동시키지 마십시오. 이것은 아래에서 처리됩니다.)

      그렇지 않다면, 만약 next characterASCII 숫자라면, 코드 포인트 시퀀스를 수집합니다 position을 기준으로 input에서. 이 시퀀스를 10진수로 해석하고, 그 숫자를 N으로 설정합니다.

      그렇지 않다면, next character는 숫자가 아니므로 실패합니다.

    7. 만약 positioninput의 끝을 넘어섰다면, 실패합니다.

    8. next characterinput 내의 position이 가리키는 문자로 설정하고, 이번에는 position을 다음 문자로 이동시킵니다. (만약 next character가 이전에 U+002E 온점 문자(.)였다면, 이번에도 동일한 문자일 것입니다.)

    9. 만약 next character가 U+002E(.)이라면:

      1. 코드 포인트 시퀀스를 수집합니다 position을 기준으로 input에서 ASCII 숫자. s를 결과 시퀀스로 설정합니다.

      2. 만약 s가 빈 문자열이라면, 실패합니다.

      3. lengths의 문자 수로 설정합니다.

      4. fraction을 10length으로 나눈 후 s를 10진수로 해석한 결과로 설정합니다.

      5. Nfraction만큼 증가시킵니다.

      6. ASCII 공백 문자를 건너뛰십시오 input 내에서 position을 기준으로.

      7. 만약 positioninput의 끝을 넘어섰다면, 실패합니다.

      8. next characterinput 내의 position이 가리키는 문자로 설정하고, position을 다음 문자로 이동시킵니다.

      9. 만약 next character가 U+0053 라틴 대문자 S 문자나 U+0073 라틴 소문자 S 문자가 아니라면, 실패합니다.

      10. unitsseconds로 설정합니다.

      그렇지 않다면:

      1. 만약 next characterASCII 공백 문자라면, ASCII 공백 문자를 건너뛰십시오 input 내에서 position을 기준으로, next characterposition이 가리키는 문자로 설정하고, position을 다음 문자로 이동시킵니다.

      2. 만약 next character가 U+0059 라틴 대문자 Y 문자이거나 U+0079 라틴 소문자 Y 문자라면, unitsyears로 설정하고 M-disambiguatormonths로 설정합니다.

        만약 next character가 U+004D 라틴 대문자 M 문자이거나 U+006D 라틴 소문자 M 문자이고, M-disambiguatormonths라면, unitsmonths로 설정합니다.

        만약 next character가 U+0057 라틴 대문자 W 문자이거나 U+0077 라틴 소문자 W 문자라면, unitsweeks로 설정하고 M-disambiguatorminutes로 설정합니다.

        만약 next character가 U+0044 라틴 대문자 D 문자이거나 U+0064 라틴 소문자 D 문자라면, unitsdays로 설정하고 M-disambiguatorminutes로 설정합니다.

        만약 next character가 U+0048 라틴 대문자 H 문자이거나 U+0068 라틴 소문자 H 문자라면, unitshours로 설정하고 M-disambiguatorminutes로 설정합니다.

        만약 next character가 U+004D 라틴 대문자 M 문자이거나 U+006D 라틴 소문자 M 문자이고, M-disambiguatorminutes라면, unitsminutes로 설정합니다.

        만약 next character가 U+0053 라틴 대문자 S 문자이거나 U+0073 라틴 소문자 S 문자라면, unitsseconds로 설정하고 M-disambiguatorminutes로 설정합니다.

        그렇지 않다면, 만약 next character가 위의 문자들 중 어느 것도 아니라면, 실패합니다.

    10. component count를 증가시킵니다.

    11. multiplier를 1로 설정합니다.

    12. 만약 unitsyears라면, multiplier를 12로 곱하고 unitsmonths로 설정합니다.

    13. 만약 unitsmonths라면, monthsNmultiplier의 곱을 더합니다.

      그렇지 않다면:

      1. 만약 unitsweeks라면, multiplier를 7로 곱하고 unitsdays로 설정합니다.

      2. 만약 unitsdays라면, multiplier를 24로 곱하고 unitshours로 설정합니다.

      3. 만약 unitshours라면, multiplier를 60으로 곱하고 unitsminutes로 설정합니다.

      4. 만약 unitsminutes라면, multiplier를 60으로 곱하고 unitsseconds로 설정합니다.

      5. 강제로, units는 이제 seconds입니다. Nmultiplier의 곱을 seconds에 더합니다.

    14. ASCII 공백 문자를 건너뛰십시오 input 내에서 position을 기준으로.

  9. 만약 component count가 0이라면, 실패합니다.

  10. 만약 months가 0이 아니라면, 실패합니다.

  11. seconds 초로 구성된 지속 시간을 반환합니다.

2.3.5.10 불분명한 시간들

문자열이 다음 중 하나일 경우 유효한 선택적 시간 포함 날짜 문자열입니다:


날짜 또는 시간 문자열을 구문 분석하는 규칙은 다음과 같습니다. 이 알고리즘은 날짜, 시간, 전역 날짜 및 시간 또는 아무것도 반환하지 않습니다. 알고리즘이 "실패"한다고 말하는 경우, 이 시점에서 중단되고 아무것도 반환하지 않습니다.

  1. input을 구문 분석 중인 문자열로 설정합니다.

  2. positioninput의 시작을 가리키는 포인터로 설정합니다.

  3. start positionposition과 동일한 위치로 설정합니다.

  4. date presenttime present 플래그를 true로 설정합니다.

  5. 날짜 구성 요소를 구문 분석하여 year, month, 및 day를 얻습니다. 실패할 경우, date present 플래그를 false로 설정합니다.

  6. date present가 true이고 positioninput의 끝을 넘지 않았으며 position의 문자가 U+0054 라틴 대문자 T 문자(T) 또는 U+0020 공백 문자인 경우 positioninput에서 다음 문자로 이동시킵니다.

    그렇지 않다면, date present가 true이고 positioninput의 끝을 넘었거나 position의 문자가 U+0054 라틴 대문자 T 문자(T)도 U+0020 공백 문자도 아닌 경우 time present를 false로 설정합니다.

    그렇지 않다면, date present가 false일 경우 positionstart position과 동일한 위치로 되돌립니다.

  7. 만약 time present 플래그가 true라면 시간 구성 요소를 구문 분석하여 hour, minute, 및 second를 얻습니다. 만약 실패하면, 중단합니다.

  8. date presenttime present 플래그가 모두 true이고 positioninput의 끝을 넘은 경우, 실패합니다.

  9. date presenttime present 플래그가 모두 true일 경우 시간대 오프셋 구성 요소를 구문 분석하여 timezonehourstimezoneminutes를 얻습니다. 실패할 경우, 중단합니다.

  10. positioninput의 끝을 넘지 않았다면, 실패합니다.

  11. date present 플래그가 true이고 time present 플래그가 false인 경우 year, month, day로 구성된 date를 설정하고 date를 반환합니다.

    그렇지 않다면 time present 플래그가 true이고 date present 플래그가 false인 경우 hour, minute, second로 구성된 time을 설정하고 time을 반환합니다.

    그렇지 않다면, year, month, day, hour, minute, second로 구성된 시간을 설정하고 timezonehourstimezoneminutes를 빼서 UTC 시간대에서 해당 시간을 계산합니다. timezonetimezonehourstimezoneminutes로 설정하고 timetimezone을 반환합니다.

2.3.6 색상

단순 색상'srgb' 색상 공간에서 각각 색상의 빨강, 녹색 및 파랑 구성 요소를 나타내는 0부터 255까지의 범위에 있는 세 개의 8비트 숫자로 구성됩니다.

문자열이 정확히 7자 길이이며 첫 번째 문자가 U+0023 번호 기호 문자(#)이고 나머지 6문자가 모두 ASCII 16진수 숫자라면, 유효한 단순 색상 문자열(valid simple color)입니다. 첫 두 자리 숫자는 빨간색 구성 요소를, 중간 두 자리 숫자는 녹색 구성 요소를, 마지막 두 자리 숫자는 파란색 구성 요소를 나타내며, 이 값들은 16진수로 나타냅니다.

문자열이 유효한 단순 색상이며 U+0041부터 U+0046 사이의 문자(A에서 F까지의 라틴 대문자)를 사용하지 않는다면, 이는 유효한 소문자 단순 색상(valid lowercase simple color)입니다.

단순 색상 값을 구문 분석하는 규칙은 다음 알고리즘에서 주어진 순서대로 따라야 합니다. 이 알고리즘은 단순 색상 또는 오류를 반환합니다.

  1. input을 구문 분석 중인 문자열로 설정합니다.

  2. input이 정확히 7자 길이가 아니면 오류를 반환합니다.

  3. input의 첫 번째 문자가 U+0023 번호 기호 문자(#)가 아니면 오류를 반환합니다.

  4. input의 마지막 6문자가 모두 ASCII 16진수 숫자가 아니라면 오류를 반환합니다.

  5. result단순 색상으로 설정합니다.

  6. 두 번째와 세 번째 문자를 16진수 숫자로 해석하고 그 결과를 result의 빨간색 구성 요소로 설정합니다.

  7. 네 번째와 다섯 번째 문자를 16진수 숫자로 해석하고 그 결과를 result의 녹색 구성 요소로 설정합니다.

  8. 여섯 번째와 일곱 번째 문자를 16진수 숫자로 해석하고 그 결과를 result의 파란색 구성 요소로 설정합니다.

  9. result를 반환합니다.

단순 색상 값을 직렬화하는 규칙은 다음 알고리즘에 주어집니다:

  1. result를 U+0023 번호 기호 문자(#) 하나로 구성된 문자열로 설정합니다.

  2. 빨강, 녹색, 파랑 구성 요소를 차례대로 16진수 숫자 두 자리로 변환하고, 필요하면 0으로 채워 result에 이 숫자들을 빨강, 녹색, 파랑 순서로 추가합니다.

  3. result를 반환합니다. 이 값은 유효한 소문자 단순 색상이 됩니다.


몇몇 오래된 레거시 속성들은 더 복잡한 방식으로 색상을 구문 분석하며, 레거시 색상 값을 구문 분석하는 규칙을 사용합니다. 이 알고리즘은 단순 색상 또는 오류를 반환합니다.

  1. input을 구문 분석 중인 문자열로 설정합니다.

  2. input이 빈 문자열이면 오류를 반환합니다.

  3. 선행 및 후행 ASCII 공백input에서 제거합니다.

  4. input이 "transparent" 문자열과 ASCII 대소문자 구분 없이 일치한다면 오류를 반환합니다.

  5. input이름이 지정된 색상 중 하나와 ASCII 대소문자 구분 없이 일치하면 해당 키워드에 해당하는 단순 색상을 반환합니다. [CSSCOLOR]

    CSS2 시스템 색상은 인식되지 않습니다.

  6. input코드 포인트 길이가 4이고, input의 첫 번째 문자가 U+0023(#)이며 마지막 세 문자가 모두 ASCII 16진수 숫자인 경우:

    1. result단순 색상으로 설정합니다.

    2. input의 두 번째 문자를 16진수 숫자로 해석하고 그 결과에 17을 곱하여 result의 빨강 구성 요소로 설정합니다.

    3. input의 세 번째 문자를 16진수 숫자로 해석하고 그 결과에 17을 곱하여 result의 녹색 구성 요소로 설정합니다.

    4. input의 네 번째 문자를 16진수 숫자로 해석하고 그 결과에 17을 곱하여 result의 파랑 구성 요소로 설정합니다.

    5. result를 반환합니다.

  7. 코드 포인트가 U+FFFF를 초과하는 경우, 즉 기본 다국어 평면에 속하지 않는 문자는 "00"이라는 두 문자 문자열로 대체합니다.

  8. input코드 포인트 길이가 128보다 크면 input의 처음 128자만 남겨두고 나머지를 잘라냅니다.

  9. input의 첫 번째 문자가 U+0023 번호 기호 문자(#)이면 이를 제거합니다.

  10. inputASCII 16진수 숫자가 아닌 문자가 있으면 U+0030 숫자 0 문자로 대체합니다.

  11. input코드 포인트 길이가 0이거나 3의 배수가 아닐 경우, input에 U+0030 숫자 0 문자를 추가합니다.

  12. input을 동일한 코드 포인트 길이를 가진 세 문자열로 나누어 세 개의 구성 요소를 얻습니다. length는 각 구성 요소가 가지는 코드 포인트 길이로 설정합니다(input코드 포인트 길이의 3분의 1).

  13. length가 8을 초과하면 각 구성 요소의 앞에서 length-8자리를 제거하고 length를 8로 설정합니다.

  14. length가 2보다 클 때 각 구성 요소의 첫 번째 문자가 U+0030 숫자 0 문자이면, 그 문자를 제거하고 length를 1 줄입니다.

  15. length가 여전히 2보다 크면 각 구성 요소를 잘라 처음 두 글자만 남겨둡니다.

  16. result단순 색상으로 설정합니다.

  17. 첫 번째 구성 요소를 16진수 숫자로 해석하고 그 결과를 result의 빨강 구성 요소로 설정합니다.

  18. 두 번째 구성 요소를 16진수 숫자로 해석하고 그 결과를 result의 녹색 구성 요소로 설정합니다.

  19. 세 번째 구성 요소를 16진수 숫자로 해석하고 그 결과를 result의 파랑 구성 요소로 설정합니다.

  20. result를 반환합니다.


2D 그래픽 컨텍스트에는 불투명도를 처리하는 별도의 색상 구문이 있습니다.

2.3.7 공백으로 구분된 토큰

공백으로 구분된 토큰 세트는 하나 이상의 ASCII 공백으로 구분된 0개 이상의 단어(토큰으로 알려짐)를 포함하는 문자열입니다. 여기서 단어는 ASCII 공백이 아닌 하나 이상의 문자로 구성됩니다.

공백으로 구분된 토큰 세트를 포함하는 문자열은 선행 또는 후행 ASCII 공백을 가질 수 있습니다.

순서가 없는 고유한 공백으로 구분된 토큰 세트는 토큰이 중복되지 않는 공백으로 구분된 토큰 세트입니다.

순서가 있는 고유한 공백으로 구분된 토큰 세트는 토큰의 순서가 의미가 있으며, 토큰이 중복되지 않는 공백으로 구분된 토큰 세트입니다.

공백으로 구분된 토큰 세트는 때때로 허용된 값의 정의된 세트를 가집니다. 허용된 값의 세트가 정의된 경우, 토큰은 모두 해당 허용된 값 목록에서 가져와야 합니다. 다른 값은 비준수 값입니다. 그러한 허용된 값의 세트가 제공되지 않으면, 모든 값은 준수합니다.

공백으로 구분된 토큰 세트의 토큰을 비교하는 방법(예: 대소문자 구분 여부)은 세트별로 정의됩니다.

2.3.8 쉼표로 구분된 토큰

쉼표로 구분된 토큰 세트는 0개 이상의 토큰이 포함된 문자열로, 각 토큰은 다음 토큰과 U+002C 쉼표 문자(,)로 구분되며, 토큰은 ASCII 공백으로 시작하거나 끝나지 않으며, U+002C 쉼표 문자(,)를 포함하지 않고, 선택적으로 ASCII 공백으로 둘러싸일 수 있습니다.

예를 들어, 문자열 " a ,b,,d d "는 "a", "b", 빈 문자열, "d d"의 네 개의 토큰으로 구성됩니다. 각 토큰의 앞뒤 공백은 토큰의 일부로 간주되지 않으며, 빈 문자열도 토큰이 될 수 있습니다.

쉼표로 구분된 토큰 세트는 때때로 유효한 토큰을 구성하는 것에 대한 추가 제한이 있습니다. 이러한 제한이 정의된 경우, 토큰은 모두 해당 제한 내에 있어야 합니다. 그렇지 않은 값은 비준수입니다. 그러한 제한이 명시되지 않은 경우, 모든 값이 준수합니다.

2.3.9 참조

type 유형의 요소에 대한 유효한 해시 이름 참조는 U+0023 번호 기호 문자(#)로 시작하고, 동일한 트리 내에서 type 유형의 요소의 name 속성 값과 정확히 일치하는 문자열로 구성된 문자열입니다.

scope라는 컨텍스트 노드를 사용하여 type 유형의 요소에 대한 해시 이름 참조를 구문 분석하는 규칙은 다음과 같습니다:

  1. 구문 분석 중인 문자열에 U+0023 번호 기호 문자가 포함되지 않거나, 문자열 내 첫 번째 해당 문자가 문자열의 마지막 문자라면 null을 반환합니다.

  2. 구문 분석 중인 문자열에서 첫 번째 U+0023 번호 기호 문자 바로 다음 문자부터 해당 문자열의 끝까지의 문자열을 s라고 합니다.

  3. scope트리에서 type 유형의 첫 번째 요소를 트리 순서로 반환하며, 이 요소는 s와 동일한 값을 가진 id 또는 name 속성을 가지고 있어야 합니다. 해당 요소가 없으면 null을 반환합니다.

id 속성은 구문 분석 시 고려되지만, 값이 유효한 해시 이름 참조인지 여부를 결정할 때는 사용되지 않습니다. 즉, id를 기준으로 요소를 참조하는 해시 이름 참조는 적합성 오류입니다(해당 요소에 동일한 값의 name 속성이 없는 경우).

2.3.10 미디어 쿼리

<media-query-list> 규칙과 일치하는 문자열은 유효한 미디어 쿼리 목록입니다. [MQ]

문자열이 비어 있거나, ASCII 공백 문자로만 이루어져 있거나, Media Queries에 정의된 대로 사용자의 환경과 일치하는 미디어 쿼리 목록이라면, 해당 문자열은 사용자의 환경과 일치합니다. [MQ]

2.3.11 고유 내부 값

고유 내부 값은 직렬화 가능하고, 값으로 비교할 수 있으며, 스크립트에 노출되지 않는 값입니다.

새로운 고유 내부 값을 생성하려면 이 알고리즘에 의해 이전에 반환된 적이 없는 고유 내부 값을 반환합니다.

2.4 URL

2.4.1 용어

문자열이 유효한 비어 있지 않은 URL인 경우, 이는 유효한 URL 문자열이지만, 비어 있는 문자열은 아닙니다.

문자열이 공백으로 둘러싸인 유효한 URL인 경우, 이는 앞뒤 ASCII 공백 제거 후에 유효한 URL 문자열이 됩니다.

문자열이 공백으로 둘러싸인 유효한 비어 있지 않은 URL인 경우, 이는 앞뒤 ASCII 공백 제거 후에 유효한 비어 있지 않은 URL이 됩니다.

이 명세는 URL about:legacy-compat을 예약된, 그러나 해석 불가능한 about: URL로 정의하며, 이는 XML 도구와의 호환성을 위해 DOCTYPEHTML 문서에서 사용됩니다. [ABOUT]

이 명세는 URL about:html-kind을 예약된, 그러나 해석 불가능한 about: URL로 정의하며, 이는 미디어 트랙의 종류를 식별하는 데 사용됩니다. [ABOUT]

이 명세는 URL about:srcdoc을 예약된, 그러나 해석 불가능한 about: URL로 정의하며, 이는 URL로 사용됩니다. 이는 iframe srcdoc 문서[ABOUT]

document 객체 document대체 기본 URL은 다음 단계들을 실행하여 얻어진 URL 레코드입니다:

  1. document iframe srcdoc 문서인 경우:

    1. documentabout 기본 URL이 null이 아님을 단언하십시오.

    2. documentabout 기본 URL을 반환하십시오.

  2. documentURLabout:blank와 일치하고 documentabout 기본 URL이 null이 아닌 경우, documentabout 기본 URL을 반환하십시오.

  3. documentURL을 반환하십시오.

document 객체의 문서 기본 URL은 다음 단계들을 실행하여 얻어진 URL 레코드입니다:

  1. 기본 요소에 href 속성이 없으면 documentdocument대체 기본 URL을 반환하십시오.

  2. 그렇지 않은 경우, 기본 요소 중에서 href 속성을 가진 첫 번째 요소의 고정 기본 URL트리 순서에 따라 반환하십시오.


URL이 다음과 일치하면 about:blank와 일치한다고 합니다: 스킴이 "about"이고, 경로에 "blank"라는 문자열이 하나만 포함되어 있으며, 사용자 이름비밀번호는 빈 문자열이고, 호스트는 null입니다.

이러한 URL의 쿼리프래그먼트는 null이 아닐 수 있습니다. 예를 들어, "about:blank?foo#bar"를 파싱하여 생성된 URL 레코드about:blank와 일치합니다.

URL이 다음과 일치하면 about:srcdoc와 일치한다고 합니다: 스킴이 "about"이고, 경로에 "srcdoc"라는 문자열이 하나만 포함되어 있으며, 쿼리는 null이고, 사용자 이름비밀번호는 빈 문자열이며, 호스트는 null입니다.

about:srcdoc와 일치하는 URL이 쿼리가 null이어야 하는 이유는, URL에 쿼리가 있는 iframe srcdoc 문서를 생성할 수 없기 때문입니다. 반면, about:blank와 일치하는 Document는 이와 다릅니다. 즉, about:srcdoc와 일치하는 모든 URL은 프래그먼트에서만 다릅니다.

2.4.2 URL 파싱

URL을 파싱하는 것은 문자열을 가져와서 이를 나타내는 URL 레코드를 얻는 과정입니다. 이 과정은 URL에서 정의되지만, HTML 표준에서는 기본 URL과 인코딩을 추상화하기 위해 몇 가지 래퍼를 정의합니다. [URL]

대부분의 새로운 API는 URL 파싱을 사용해야 합니다. 오래된 API와 HTML 요소는 인코딩-URL 파싱을 사용할 이유가 있을 수 있습니다. 사용자 지정 기본 URL이 필요하거나 기본 URL이 필요하지 않은 경우에는 URL 파서를 직접 사용할 수도 있습니다.

주어진 문자열 urlDocument 객체 또는 환경 설정 객체 environment를 기준으로 URL을 파싱하려면, 다음 단계를 수행합니다. 이들은 실패 또는 URL을 반환합니다.

  1. environmentDocument 객체인 경우, environment기본 URLbaseURL로 설정하고, 그렇지 않은 경우 environmentAPI 기본 URLbaseURL로 설정합니다.

  2. urlbaseURL을 사용하여 URL 파서를 적용한 결과를 반환합니다.

주어진 문자열 urlDocument 객체 또는 환경 설정 객체 environment를 기준으로 인코딩-URL 파싱하려면, 다음 단계를 수행합니다. 이들은 실패 또는 URL을 반환합니다.

  1. encodingUTF-8로 설정합니다.

  2. environmentDocument 객체인 경우, encodingenvironment문서의 문자 인코딩으로 설정합니다.

  3. 그렇지 않고, environment관련 글로벌 객체Window 객체인 경우, encodingenvironment관련 글로벌 객체관련 Document문자 인코딩으로 설정합니다.

  4. environmentDocument 객체인 경우, environment기본 URLbaseURL로 설정하고, 그렇지 않은 경우 environmentAPI 기본 URLbaseURL로 설정합니다.

  5. urlbaseURLencoding을 사용하여 URL 파서를 적용한 결과를 반환합니다.

주어진 문자열 urlDocument 객체 또는 환경 설정 객체 environment를 기준으로 인코딩-URL 파싱 및 직렬화하려면, 다음 단계를 수행합니다. 이들은 실패 또는 문자열을 반환합니다.

  1. environment를 기준으로 주어진 url에 대해 인코딩-URL 파싱의 결과를 url로 설정합니다.

  2. url이 실패인 경우, 실패를 반환합니다.

  3. url에 대해 URL 직렬화기를 적용한 결과를 반환합니다.

2.4.3 기본 URL의 동적 변경

문서의 문서 기본 URL이 변경되면, 해당 문서의 모든 요소는 기본 URL 변경의 영향을 받습니다.

다음은 기본 URL 변경 단계로, 요소가 기본 URL 변경의 영향을 받을 때 실행됩니다(DOM에 정의된 대로).

요소가 하이퍼링크를 생성하는 경우

하이퍼링크로 식별된 URL이 사용자에게 표시되고 있거나 해당 URL에서 파생된 데이터가 표시를 영향을 미치는 경우, href 속성의 값이 요소의 노드 문서를 기준으로 다시 파싱되고 UI가 적절하게 업데이트되어야 합니다.

예를 들어, CSS의 :link/:visited 의사 클래스가 영향을 받을 수 있습니다.

하이퍼링크에 ping 속성이 있고 그 URL(들)이 사용자에게 표시되는 경우, ping 속성의 토큰이 요소의 노드 문서를 기준으로 다시 파싱되고 UI가 적절하게 업데이트되어야 합니다.

요소가 q, blockquote, ins 또는 del 요소이고 cite 속성이 있는 경우

cite 속성으로 식별된 URL이 사용자에게 표시되거나, 해당 URL에서 파생된 데이터가 표시를 영향을 미치는 경우, cite 속성의 값이 요소의 노드 문서를 기준으로 다시 파싱되고 UI가 적절하게 업데이트되어야 합니다.

그 외의 경우

해당 요소는 직접적으로 영향을 받지 않습니다.

예를 들어, 기본 URL을 변경해도 img 요소에 표시된 이미지에는 영향을 미치지 않지만, 이후 스크립트에서 src IDL 속성에 접근하면 더 이상 표시된 이미지와 일치하지 않을 수 있는 새로운 절대 URL을 반환합니다.

2.5 리소스 가져오기

2.5.1 용어

응답유형이 "basic", "cors", 또는 "default"인 경우, 이를 CORS-동일 출처라고 합니다. [FETCH]

응답유형이 "opaque" 또는 "opaqueredirect"인 경우, 이를 CORS-교차 출처라고 합니다.

응답안전하지 않은 응답내부 응답이 존재할 경우 이를 따르며, 그렇지 않으면 해당 응답 자체를 의미합니다.

잠재적인 CORS 요청을 생성하려면, url, destination, corsAttributeState, 및 선택적 동일 출처 대체 플래그를 사용하여 다음 단계를 수행하십시오:

  1. corsAttributeState아무것도 아님일 경우, mode를 "no-cors"로 설정하고, 그렇지 않으면 "cors"로 설정합니다.

  2. 동일 출처 대체 플래그가 설정되어 있고 mode가 "no-cors"인 경우, mode를 "same-origin"으로 설정합니다.

  3. credentialsMode를 "include"로 설정합니다.

  4. corsAttributeState익명인 경우, credentialsMode를 "same-origin"으로 설정합니다.

  5. requesturlURL로 하고, destination목적지로 하고, mode모드로 하고, credentialsMode자격 증명 모드로 하고, URL 자격 증명 플래그를 설정한 새로운 요청으로 정의하십시오.

2.5.2 리소스 유형 결정

리소스의 Content-Type 메타데이터MIME Sniffing의 요구 사항과 일치하는 방식으로 획득하고 해석해야 합니다. [MIMESNIFF]

리소스의 계산된 MIME 유형MIME Sniffing의 요구 사항에 따라 찾아야 합니다. [MIMESNIFF]

이미지 전용 스니핑 규칙, 텍스트 또는 바이너리 리소스를 구분하는 규칙, 그리고 오디오 및 비디오 전용 스니핑 규칙MIME Sniffing에서 정의됩니다. 이러한 규칙은 결과로 MIME 유형을 반환합니다. [MIMESNIFF]

사용자 에이전트가 서버가 예상하는 것과 다른 콘텐츠 유형 감지 휴리스틱을 사용할 때 보안 문제가 발생할 수 있으므로, MIME Sniffing의 규칙을 정확하게 따라야 합니다. 자세한 내용은 MIME Sniffing을 참조하십시오. [MIMESNIFF]

2.5.3 meta 요소에서 문자 인코딩 추출

s 문자열을 주어진 meta 요소에서 문자 인코딩을 추출하기 위한 알고리즘은 다음과 같습니다. 이 알고리즘은 문자 인코딩 또는 아무것도 반환하지 않습니다.

  1. positions의 시작을 가리키는 포인터로 설정합니다.

  2. 반복: position 이후 s에서 "charset"이라는 단어와 일치하는 ASCII 대소문자 구분 없이 일치하는 첫 번째 7자를 찾습니다. 일치하는 단어를 찾지 못하면 아무것도 반환하지 않습니다.

  3. "charset" 단어 뒤에 바로 나오는 ASCII 공백 문자를 건너뜁니다(공백이 없을 수도 있음).

  4. 다음 문자가 U+003D EQUALS SIGN(=)이 아니면 position을 다음 문자 바로 앞으로 이동시키고, 반복으로 돌아갑니다.

  5. 등호(=) 뒤에 오는 ASCII 공백 문자를 건너뜁니다(공백이 없을 수도 있음).

  6. 다음 문자를 다음과 같이 처리합니다:

    만약 그것이 U+0022 QUOTATION MARK 문자(")이고 s에 나중에 나타나는 U+0022 QUOTATION MARK 문자가 있을 경우
    만약 그것이 U+0027 APOSTROPHE 문자(')이고 s에 나중에 나타나는 U+0027 APOSTROPHE 문자가 있을 경우
    이 문자와 다음에 나타나는 동일한 문자 사이의 부분 문자열에서 인코딩을 얻는 결과를 반환합니다.
    만약 그것이 일치하지 않는 U+0022 QUOTATION MARK 문자(")일 경우
    만약 그것이 일치하지 않는 U+0027 APOSTROPHE 문자(')일 경우
    다음 문자가 없을 경우
    아무것도 반환하지 않습니다.
    그 외의 경우
    이 문자에서 시작하여 첫 번째 ASCII 공백 문자 또는 U+003B SEMICOLON 문자(;)까지 또는 s의 끝까지의 부분 문자열에서 인코딩을 얻는 결과를 반환합니다.

이 알고리즘은 HTTP 명세의 알고리즘과 다릅니다(예: HTTP는 작은 따옴표 사용을 허용하지 않으며, 이 알고리즘에서는 지원되지 않는 백슬래시 이스케이프 메커니즘을 지원해야 합니다). 이 알고리즘은 역사적으로 HTTP와 관련된 맥락에서 사용되었지만, 구현에 따른 구문은 오래 전에 달라졌습니다. [HTTP]

2.5.4 CORS 설정 속성

Attributes/crossorigin

모든 최신 엔진에서 지원됩니다.

Firefox8+Safari6+Chrome13+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

CORS 설정 속성은 다음 키워드와 상태를 가진 열거된 속성입니다:

키워드 상태 간단한 설명
anonymous 익명 요청 모드는 "cors"로 설정되며, 자격 증명 모드는 "same-origin"으로 설정됩니다.
(빈 문자열)
use-credentials 자격 증명 사용 요청 모드는 "cors"로 설정되며, 자격 증명 모드는 "include"로 설정됩니다.

속성의 누락된 값 기본값CORS 없음 상태이며, 잘못된 값 기본값익명 상태입니다. 반영의 목적을 위해 표준 키워드익명 상태에 대한 anonymous 키워드입니다.

대부분의 CORS 설정 속성에 의해 관리되는 페치는 잠재적인 CORS 요청 만들기 알고리즘을 통해 이루어집니다.

보다 현대적인 기능에서는 요청의 모드가 항상 "cors"로 설정되며, 특정 CORS 설정 속성은 약간 다른 의미를 가지도록 재정의되었으며, 이는 요청자격 증명 모드에만 영향을 미칩니다. 이 변환을 수행하기 위해, 우리는 주어진 CORS 설정 속성에 대한 CORS 설정 속성 자격 증명 모드를 다음 상태에 따라 결정합니다:

CORS 없음
익명
"same-origin"
자격 증명 사용
"include"

2.5.5 리퍼러 정책 속성

리퍼러 정책 속성열거된 속성입니다. 이 속성의 각 리퍼러 정책(빈 문자열 포함)은 이 속성의 키워드이며, 동일한 이름의 상태와 매핑됩니다.

속성의 누락된 값 기본값잘못된 값 기본값은 모두 빈 문자열 상태입니다.

이 상태들이 다양한 페치의 처리 모델에 미치는 영향은 이 명세서 전체와 Fetch, Referrer Policy에서 자세히 정의되어 있습니다. [FETCH] [REFERRERPOLICY]

여러 신호들이 주어진 페치에 대해 사용되는 처리 모델에 기여할 수 있으며, 리퍼러 정책 속성은 그 중 하나일 뿐입니다. 일반적으로 이러한 신호들이 처리되는 순서는 다음과 같습니다:

  1. 첫 번째로, `noreferrer` 링크 타입의 존재;

  2. 그 다음으로, 리퍼러 정책 속성의 값;

  3. 그 다음으로, `meta` 요소에 `name` 속성이 `referrer`로 설정된 요소의 존재;

  4. 마지막으로, `Referrer-Policy` HTTP 헤더.

2.5.6 넌스 속성

Global_attributes/nonce

모든 현재 엔진에서 지원됨.

Firefox31+Safari지원됨Chrome지원됨
Opera?Edge지원됨
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

nonce 콘텐츠 속성은 Content Security Policy에서 주어진 fetch가 진행될 수 있는지를 결정하기 위해 사용할 수 있는 암호화 넌스("한 번 사용된 숫자")를 나타냅니다. 값은 텍스트입니다. [CSP]

nonce 콘텐츠 속성이 있는 요소는 암호화 넌스가 스크립트에만 노출되고(CSS 속성 선택자와 같은 사이드 채널에는 노출되지 않음) 콘텐츠 속성에서 값을 가져와 [[CryptographicNonce]]라는 내부 슬롯에 넣고, HTMLOrSVGElement 인터페이스 믹스인을 통해 스크립트에 노출하며, 콘텐츠 속성을 빈 문자열로 설정합니다. 별도로 명시되지 않은 한, 슬롯의 값은 빈 문자열입니다.

element.nonce

element의 암호화 넌스에 설정된 값을 반환합니다. 세터가 사용되지 않았다면, 이는 nonce 콘텐츠 속성에서 원래 찾은 값이 될 것입니다.

element.nonce = value

element의 암호화 넌스 값을 업데이트합니다.

HTMLElement/nonce

Firefox75+🔰 10+Chrome61+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

nonce IDL 속성은 가져올 때 이 요소의 [[CryptographicNonce]]의 값을 반환해야 하며, 설정할 때 이 요소의 [[CryptographicNonce]]를 주어진 값으로 설정해야 합니다.

nonce IDL 속성의 세터가 해당하는 콘텐츠 속성을 업데이트하지 않는다는 점에 주목하십시오. 이는 요소가 탐색 컨텍스트에 연결될 때 nonce 콘텐츠 속성을 빈 문자열로 설정하는 것과 함께, 콘텐츠 속성을 쉽게 읽을 수 있는 메커니즘(예: 선택자)을 통해 넌스 값이 유출되는 것을 방지하기 위한 것입니다. 이 동작은 issue #2369에서 도입되었습니다.

다음 속성 변경 단계nonce 콘텐츠 속성에 사용됩니다:

  1. elementHTMLOrSVGElement를 포함하지 않는다면, 반환합니다.

  2. localNamenonce가 아니거나 namespace가 null이 아니라면, 반환합니다.

  3. value가 null이라면, element[[CryptographicNonce]]를 빈 문자열로 설정합니다.

  4. 그렇지 않으면, element[[CryptographicNonce]]value로 설정합니다.

HTMLOrSVGElement를 포함하는 요소가 탐색 컨텍스트에 연결될 때, 사용자 에이전트는 element에 대해 다음 단계를 실행해야 합니다:

  1. CSP 목록element그림자 포함 루트정책 컨테이너CSP 목록으로 설정합니다.

  2. CSP 목록nonce 콘텐츠 속성이 포함되어 있고 attr의 값이 빈 문자열이 아니라면, 다음 단계를 실행합니다:

    1. nonceelement[[CryptographicNonce]]로 설정합니다.

    2. element에 대해 "nonce"와 빈 문자열을 사용하여 속성 값을 설정합니다.

    3. element[[CryptographicNonce]]nonce로 설정합니다.

    element[[CryptographicNonce]]가 복원되지 않으면 이 시점에서 빈 문자열이 됩니다.

HTMLOrSVGElement복제하는 단계는 복제된 요소의 [[CryptographicNonce]] 슬롯을 복제되는 요소의 슬롯 값으로 설정해야 합니다.

2.5.7 지연 로딩 속성

Lazy_loading

모든 현재 엔진에서 지원됨.

Firefox75+Safari15.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지연 로딩 속성은 다음과 같은 키워드 및 상태를 가지는 열거형 속성입니다:

키워드 상태 간단한 설명
lazy 지연 일부 조건이 충족될 때까지 리소스 가져오기를 연기하는 데 사용됩니다.
eager 즉시 리소스를 즉시 가져오도록 사용됩니다. 기본 상태입니다.

이 속성은 사용자 에이전트가 리소스를 즉시 가져오도록 지시하거나, 속성의 현재 상태에 따라 요소와 관련된 일부 조건이 충족될 때까지 가져오기를 연기하도록 지시합니다.

속성의 누락된 값 기본값유효하지 않은 값 기본값은 모두 즉시 상태입니다.


지연 로딩 요소 단계는 요소 element가 주어졌을 때 다음과 같은 단계로 진행됩니다:

  1. element에 대해 스크립팅이 비활성화된 경우, false를 반환합니다.

    이것은 추적 방지 조치입니다. 스크립팅이 비활성화된 경우에도 사용자 에이전트가 지연 로딩을 지원하면, 페이지의 마크업에 이미지를 전략적으로 배치하여 서버가 이미지 요청의 수와 시점을 추적함으로써 사용자의 대략적인 스크롤 위치를 추적할 수 있기 때문입니다.

  2. element지연 로딩 속성지연 상태에 있으면, true를 반환합니다.

  3. false를 반환합니다.

imgiframe 요소는 초기에는 null로 설정된 지연 로드 재개 단계를 가집니다.

지연 로드될 imgiframe 요소에 대해, 이러한 단계는 지연 로드 교차 관찰자의 콜백에서 실행되거나, 지연 로딩 속성즉시 상태로 설정될 때 실행됩니다. 이는 요소가 계속 로드되도록 합니다.

document는 초기에는 null로 설정된 지연 로드 교차 관찰자를 가지며, IntersectionObserver 인스턴스로 설정될 수 있습니다.

element를 지연 로딩 요소로 교차 관찰을 시작하기 위해, 다음 단계를 실행합니다:

  1. docelement노드 문서로 설정합니다.

  2. 만약 doc지연 로드 교차 관찰자가 null이라면, 이를 다음과 같이 초기화된 새 IntersectionObserver 인스턴스로 설정합니다:

    이 스펙에서는 JavaScript로 노출된 생성자를 사용할 수밖에 없지만, 원래의 IntersectionObserver 생성자를 사용하려고 합니다. Intersection Observer가 스펙에 사용할 수 있는 저수준의 훅을 노출할 때까지, 이 방식으로 진행합니다. 관련 이슈는 w3c/IntersectionObserver#464에서 확인할 수 있습니다. [INTERSECTIONOBSERVER]

  3. doc지연 로드 교차 관찰자observe 메서드를 element를 인수로 하여 호출합니다.

    원래의 observe 메서드를 사용하려고 합니다. 자세한 내용은 w3c/IntersectionObserver#464를 참조하십시오. [INTERSECTIONOBSERVER]

지연 로딩 요소의 교차 관찰을 중지하기 위해 element에 대해 다음 단계를 실행합니다:

  1. docelement노드 문서로 설정합니다.

  2. 확인: doc지연 로드 교차 관찰자가 null이 아님을 확인합니다.

  3. doc지연 로드 교차 관찰자unobserve 메서드를 element를 인수로 하여 호출합니다.

    원래의 unobserve 메서드를 사용하려고 합니다. 자세한 내용은 w3c/IntersectionObserver#464를 참조하십시오. [INTERSECTIONOBSERVER]

(이것은 추적 벡터입니다.) 지연 로드 스크롤 여백구현 정의된 값이지만, 다음과 같은 고려 사항이 있습니다:

개인정보 보호를 위해 지연 로드 스크롤 여백이 추가적인 정보를 유출하지 않도록 하는 것이 중요합니다. 예를 들어, 현재 장치에서의 일반적인 스크롤 속도가 새로운 지문 생성 벡터를 도입하지 않도록 부정확할 수 있습니다.

2.5.8 차단 속성

차단 속성은 외부 리소스를 가져오는 작업을 차단해야 함을 명시적으로 나타냅니다. 차단할 수 있는 작업은 다음 표에 나열된 문자열인 가능한 차단 토큰으로 표시됩니다:

가능한 차단 토큰 설명
"render" 이 요소는 렌더링을 차단할 가능성이 있습니다.

미래에는 더 많은 가능한 차단 토큰이 추가될 수 있습니다.

차단 속성정렬되지 않은 고유한 공백으로 구분된 토큰의 집합이어야 하며, 각 토큰은 가능한 차단 토큰 중 하나여야 합니다. 지원되는 토큰가능한 차단 토큰입니다. 하나의 요소는 최대 하나의 차단 속성만 가질 수 있습니다.

요소 el차단 토큰 집합은 다음 단계의 결과입니다:

  1. el차단 속성의 값을 value로 설정하거나, 해당 속성이 없으면 빈 문자열로 설정합니다.

  2. valueASCII 소문자로 변환value로 설정합니다.

  3. rawTokensvalue를 ASCII 공백으로 분할한 결과로 설정합니다.

  4. rawTokens의 요소 중에서 가능한 차단 토큰에 해당하는 요소를 포함하는 집합을 반환합니다.

요소가 렌더링을 차단할 가능성이 있는 경우는 해당 요소의 차단 토큰 집합에 "render"가 포함된 경우이며, 또는 개별 요소에서 정의될 암묵적으로 렌더링을 차단할 가능성이 있는 경우입니다. 기본적으로 요소는 암묵적으로 렌더링을 차단할 가능성이 없습니다.

2.5.9 가져오기 우선순위 속성

가져오기 우선순위 속성은 다음과 같은 키워드와 상태를 가진 열거형 속성입니다:

키워드 상태 간단한 설명
high high 동일한 목적지를 가진 다른 리소스에 비해 높은 우선순위를 나타냅니다.
low low 동일한 목적지를 가진 다른 리소스에 비해 낮은 우선순위를 나타냅니다.
auto auto 동일한 목적지를 가진 다른 리소스에 비해 가져오기 우선순위를 자동으로 결정합니다.

이 속성의 값이 없는 경우의 기본값유효하지 않은 값의 기본값은 모두 auto 상태입니다.

2.6 공통 DOM 인터페이스

2.6.1 IDL 속성에서 콘텐츠 속성 반영

반영의 구성 요소는 다음과 같습니다:

반영된 IDL 속성반영하도록 정의될 수 있습니다. 반영된 콘텐츠 속성 이름을 가진 반영된 대상입니다. 일반적으로 이는 IDL 속성 getter가 콘텐츠 속성의 현재 값을 반환하고, setter는 콘텐츠 속성의 값을 주어진 값으로 변경함을 의미합니다.

반영된 대상이 요소인 경우, 반영된 IDL 속성은 추가로 ElementInternals를 지원하도록 선언할 수 있습니다. 이는 ElementInternals 인터페이스도 동일한 식별자를 가진 반영된 IDL 속성을 가지며, 반영된 IDL 속성이 동일한 반영된 콘텐츠 속성 이름반영함을 의미합니다.

fooBar IDL 속성은 반영해야 하며, foobar 콘텐츠 속성을 지원해야 합니다. ElementInternals.

반영된 대상은 다음과 같은 관련 알고리즘을 가집니다:

반영된 대상이 요소 element인 경우, 다음과 같이 정의됩니다:

get the element
  1. element를 반환합니다.

get the content attribute
  1. attribute네임스페이스 및 로컬 이름으로 속성 가져오기를 실행한 결과이며, null, 반영된 콘텐츠 속성 이름, element이 주어집니다.

  2. attribute가 null인 경우 null을 반환합니다.

  3. attribute을 반환합니다.

set the content attribute with a string value
  1. 속성 값을 설정하고, element, 반영된 콘텐츠 속성 이름, value를 줍니다.

delete the content attribute
  1. 네임스페이스 및 로컬 이름으로 속성 제거를 실행하며, null, 반영된 콘텐츠 속성 이름, element이 주어집니다.

반영된 대상ElementInternals 객체 elementInternals인 경우, 다음과 같이 정의됩니다:

get the element
  1. elementInternals대상 요소를 반환합니다.

get the content attribute
  1. 만약 elementInternals대상 요소내부 콘텐츠 속성 맵[ 반영된 콘텐츠 속성 이름]이 존재하지 않는다면, null을 반환합니다.

  2. elementInternals대상 요소내부 콘텐츠 속성 맵[ 반영된 콘텐츠 속성 이름]을 반환합니다.

set the content attribute with a string value
  1. 설정하고, elementInternals대상 요소내부 콘텐츠 속성 맵[ 반영된 콘텐츠 속성 이름]을 value로 설정합니다.

delete the content attribute
  1. 제거하고, elementInternals대상 요소내부 콘텐츠 속성 맵[ 반영된 콘텐츠 속성 이름]을 제거합니다.

이는 ElementInternals 객체의 데이터 구조가 다소 중복되는 결과를 낳습니다. 이는 대상 요소내부 콘텐츠 속성 맵이 직접 조작될 수 없으며, 이로 인해 반영이 단일 방향으로만 이루어지기 때문입니다. 그럼에도 불구하고 이는 반영된 대상 간에 공유되는 IDL 속성을 정의할 때 발생할 수 있는 오류를 줄이고, 공통 API 시맨틱의 이점을 얻기 위해 선택된 접근 방식입니다.


IDL 속성 타입이 DOMString 또는 DOMString?이며, 반영열거된 콘텐츠 속성을 가지는 경우, 알려진 값으로만 제한될 수 있습니다. 아래의 처리 모델에 따라, 이러한 IDL 속성의 getter는 해당 열거된 속성에 대한 키워드만 반환하거나, 빈 문자열 또는 null을 반환하게 됩니다.

반영된 IDL 속성DOMString 타입을 가지고 있는 경우:

반영된 IDL 속성DOMString? 타입을 가지고 있는 경우:

반영된 IDL 속성USVString 타입을 가지고 있는 경우:

반영된 IDL 속성boolean 타입을 가지고 있는 경우:

이는 부울 콘텐츠 속성에 대한 규칙에 해당합니다.

만약 반영된 IDL 속성long 타입을 가지고 있으며, 선택적으로 음수가 아닌 숫자만으로 제한된 경우, 또는 선택적으로 기본 값 defaultValue를 가진 경우:

만약 반영된 IDL 속성unsigned long 타입을 가지고 있으며, 선택적으로 양수로만 제한된, 양수로만 제한되고 폴백이 있는, 또는 범위로 제한된 [clampedMin, clampedMax] 경우, 그리고 선택적으로 기본 값 defaultValue을 가진 경우:

만약 반영된 IDL 속성double 타입을 가지고 있으며, 선택적으로 양수로만 제한된 경우, 그리고 선택적으로 기본 값 defaultValue을 가진 경우:

무한대(Infinity) 및 숫자가 아님(NaN) 값들은 Web IDL에 정의된 대로 설정 시 예외를 발생시킵니다. [WEBIDL]

만약 반영된 IDL 속성DOMTokenList 타입을 가지고 있다면, 해당 속성의 getter 단계는 DOMTokenList 객체를 반환하는 것입니다. 이 객체의 관련된 요소는 this이며, 관련된 속성의 로컬 이름은 반영된 콘텐츠 속성 이름입니다. 사양 작성자는 이 유형의 IDL 속성에 대해 ElementInternals 지원을 사용할 수 없습니다.

만약 반영된 IDL 속성T? 타입을 가지고 있고, 여기서 TElement 또는 Element를 상속하는 인터페이스인 경우, attr반영된 콘텐츠 속성 이름이 됩니다:

이 유형의 반영된 IDL 속성은 일관성을 위해 식별자가 "Element"로 끝나도록 강력히 권장됩니다.

만약 반영된 IDL 속성FrozenArray<T>? 타입을 가지고 있고, 여기서 TElement 또는 Element를 상속하는 인터페이스인 경우, attr반영된 콘텐츠 속성 이름이 됩니다:

이 유형의 반영된 IDL 속성은 일관성을 위해 식별자가 "Elements"로 끝나도록 강력히 권장됩니다.

2.6.2 명세에서 reflect 사용하기

Reflection은 주로 웹 개발자의 작업 효율성을 높이기 위해 반영된 IDL 속성을 통해 콘텐츠 속성에 타입이 지정된 접근을 제공하는 것입니다. 웹 플랫폼이 기반을 두고 있는 궁극적인 진실의 출처는 바로 콘텐츠 속성들 자체입니다. 즉, 명세 작성자는 반영된 IDL 속성의 getter나 setter 단계를 사용해서는 안 되며, 대신 콘텐츠 속성의 존재 여부와 값을 사용해야 합니다. (또는 열거된 속성과 같은 추상화를 사용할 수 있습니다.)

이와 관련하여 두 가지 중요한 예외는 다음과 같은 타입의 반영된 IDL 속성입니다:

이러한 경우, 명세 작성자는 해당 반영된 대상attr 관련 요소 가져오기attr 관련 요소들 가져오기를 각각 사용해야 합니다. 콘텐츠 속성의 존재 여부와 값은 완전히 동기화될 수 없기 때문에 사용해서는 안 됩니다.

반영된 대상명시적으로 설정된 attr 요소, 명시적으로 설정된 attr 요소들, 캐시된 attr 관련 요소들, 및 캐시된 attr 관련 요소 객체는 내부 구현 세부 사항으로 간주되며, 이를 기반으로 구축해서는 안 됩니다.

2.6.3 컬렉션

HTMLFormControlsCollectionHTMLOptionsCollection 인터페이스는 HTMLCollection 인터페이스에서 파생된 컬렉션입니다. HTMLAllCollection 인터페이스도 컬렉션이지만, 이와 같이 파생된 것은 아닙니다.

2.6.3.1 HTMLAllCollection 인터페이스

HTMLAllCollection 인터페이스는 레거시 document.all 속성을 위해 사용됩니다. 이 인터페이스는 HTMLCollection과 유사하게 동작합니다. 주요 차이점은 메서드의 다양한 (남용된) 사용이 항상 어떤 결과를 반환하도록 허용하며, 속성 접근 외에도 함수로 호출할 수 있다는 점입니다.

모든 HTMLAllCollection 객체는 Document에 루팅되며, 모든 요소와 일치하는 필터를 가지므로 HTMLAllCollection 객체의 컬렉션에 의해 표현된 요소들은 루트 Document의 모든 하위 요소로 구성됩니다.

HTMLAllCollection 인터페이스를 구현하는 객체들은 추가 [[Call]] 내부 메서드가 포함된 레거시 플랫폼 객체이며, [[IsHTMLDDA]] 내부 슬롯도 가집니다.

HTMLAllCollection 인터페이스를 구현하는 객체들은 [[IsHTMLDDA]] 내부 슬롯을 가지기 때문에 몇 가지 특이한 동작을 합니다:

이 특수 동작들은 레거시 콘텐츠와의 호환성을 유지하기 위해 설계되었습니다: 한 쪽은 document.all 객체의 존재를 사용하여 레거시 사용자 에이전트를 감지하고, 다른 한 쪽은 이러한 레거시 사용자 에이전트만 지원하며 document.all 객체의 존재를 확인하지 않고도 이를 사용합니다. [JAVASCRIPT]

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface HTMLAllCollection {
  readonly attribute unsigned long length;
  getter Element (unsigned long index);
  getter (HTMLCollection or Element)? namedItem(DOMString name);
  (HTMLCollection or Element)? item(optional DOMString nameOrIndex);

  // Note: HTMLAllCollection objects have a custom [[Call]] internal method and an [[IsHTMLDDA]] internal slot.
};

객체의 지원되는 속성 인덱스HTMLCollection 객체들에 대해 정의된 대로입니다.

지원되는 속성 이름은 컬렉션에 의해 표현된 모든 요소의 id 속성의 비어있지 않은 값들, 그리고 컬렉션에 의해 표현된 모든 "all"-명명된 요소들name 속성의 비어있지 않은 값들로 구성됩니다. 이 값들은 트리 순서에 따라 정렬되며, 중복된 이후 항목들은 무시되고, 요소의 idname을 앞서며, 두 값이 다르고 둘 중 어느 것도 이전 항목의 중복이 아닐 때 그 순서대로 정렬됩니다.

length 게터 단계는 컬렉션에 의해 표현된 노드의 수를 반환하는 것입니다.

인덱스 속성 게터는 전달된 인덱스를 주어진 this에서 모든 인덱스 요소를 가져오는 것의 결과를 반환해야 합니다.

namedItem(name) 메서드 단계는 주어진 name에 대해 모든 명명된 요소를 가져오는 것의 결과를 this에서 반환하는 것입니다.

item(nameOrIndex) 메서드 단계는 다음과 같습니다:

  1. nameOrIndex가 제공되지 않은 경우 null을 반환합니다.

  2. 주어진 nameOrIndex에 대해 모든 인덱스 또는 명명된 요소를 가져오는 것의 결과를 반환합니다.


다음 요소들은 "all"-명명된 요소들입니다: a, button, embed, form, frame, frameset, iframe, img, input, map, meta, object, select, 그리고 textarea

"모든 인덱스 요소를 가져오기"HTMLAllCollection collection에서 주어진 인덱스 index의 요소를 반환하거나, 그런 index 번째 요소가 없는 경우 null을 반환하는 것을 의미합니다.

"모든 명명된 요소를 가져오기"HTMLAllCollection collection에서 주어진 이름 name의 요소를 가져오는 것을 의미합니다.

  1. name이 빈 문자열인 경우 null을 반환합니다.

  2. subCollectioncollection과 같은 Document에 루팅된 HTMLCollection 객체로 정의하고, 이 객체의 필터는 다음 조건을 만족하는 요소들만 일치하도록 합니다:

  3. 만약 subCollection에 요소가 하나만 있다면, 그 요소를 반환합니다.

  4. 그렇지 않고, subCollection이 비어있다면 null을 반환합니다.

  5. 그렇지 않은 경우, subCollection을 반환합니다.

"모든 인덱스 또는 명명된 요소를 가져오기"HTMLAllCollection collection에서 nameOrIndex에 따라 요소를 가져오는 것을 의미합니다:

  1. nameOrIndex가 JavaScript 문자열로 배열 인덱스 속성 이름으로 변환된 경우, 주어진 nameOrIndex에 대해 모든 인덱스 요소를 가져오는 것의 결과를 반환합니다.

  2. 그렇지 않은 경우, 주어진 nameOrIndex에 대해 모든 명명된 요소를 가져오는 것의 결과를 반환합니다.

2.6.3.1.1 [[Call]] ( thisArgument, argumentsList )
  1. 만약 argumentsList크기가 0이거나, argumentsList[0]이 undefined라면 null을 반환합니다.

  2. nameOrIndex변환하는 것의 결과로 설정합니다. argumentsList[0]을 DOMString으로 변환합니다.

  3. result모든 인덱스 또는 명명된 요소를 가져오는 것의 결과로 설정합니다. 이 HTMLAllCollection에서 nameOrIndex에 대해 실행합니다.

  4. result를 ECMAScript 값으로 변환하는 것의 결과를 반환합니다.

thisArgument는 무시되며, 따라서 Function.prototype.call.call(document.all, null, "x")와 같은 코드는 여전히 요소를 검색합니다. (document.all.call은 존재하지 않으며, document.allFunction.prototype에서 상속되지 않기 때문입니다.)

2.6.3.2 The HTMLFormControlsCollection interface

The HTMLFormControlsCollection 인터페이스는 form 요소 내의 컬렉션리스트된 요소들을 위해 사용됩니다.

HTMLFormControlsCollection

현재 모든 엔진에서 지원합니다.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원하지 않음
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

RadioNodeList

현재 모든 엔진에서 지원합니다.

Firefox33+Safari7+Chrome21+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=Window]
interface HTMLFormControlsCollection : HTMLCollection {
// inherits length and item()
getter (RadioNodeList or Element)? namedItem(DOMString name); // shadows inherited namedItem()
};

[Exposed=Window]
interface RadioNodeList : NodeList {
attribute DOMString value;
};
collection.length

collection 내 요소의 수를 반환합니다.

element = collection.item(index)
element = collection[index]

collectionindex에 위치한 항목을 반환합니다. 항목들은 트리 순서로 정렬됩니다.

element = collection.namedItem(name)

HTMLFormControlsCollection/namedItem

현재 모든 엔진에서 지원합니다.

Firefox33+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원하지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
radioNodeList = collection.namedItem(name)
element = collection[name]
radioNodeList = collection[name]

collection에서 ID 또는 name name을 가진 항목을 반환합니다.

여러 개의 일치하는 항목이 있는 경우, 그러한 모든 요소들을 포함하는 RadioNodeList 객체를 반환합니다.

radioNodeList.value

radioNodeList에 의해 표현된 첫 번째 선택된 라디오 버튼의 값을 반환합니다.

radioNodeList.value = value

value와 일치하는 값을 가진 radioNodeList에 의해 표현된 첫 번째 라디오 버튼을 선택합니다.

객체의 지원되는 속성 인덱스HTMLCollection 객체에 대해 정의된 것과 동일합니다.

지원되는 속성 이름컬렉션에 의해 표현된 모든 요소의 빈 값이 아닌 idname 속성 값으로 구성됩니다. 이러한 속성 이름들은 트리 순서에 따라 정렬되며, 이후의 중복 항목은 무시됩니다. 요소의 idname보다 우선하여 기여되며, 서로 다르고 이전 항목의 중복이 아닌 경우에 한합니다.

namedItem(name) 메서드는 다음 알고리즘에 따라 동작해야 합니다:

  1. name이 빈 문자열인 경우 null을 반환하고 알고리즘을 중지합니다.
  2. 메서드가 호출될 당시 컬렉션에 name과 일치하는 id 또는 name 속성을 가진 노드가 정확히 하나만 있는 경우, 해당 노드를 반환하고 알고리즘을 중지합니다.
  3. 그렇지 않고, 컬렉션에 name과 일치하는 id 또는 name 속성을 가진 노드가 없는 경우 null을 반환하고 알고리즘을 중지합니다.
  4. 그렇지 않으면, 새로운 RadioNodeList 객체를 생성하여 HTMLFormControlsCollection 객체의 뷰를 필터링합니다. 이 RadioNodeList 객체 내 노드는 name과 일치하는 id 또는 name 속성을 가진 노드들로만 구성됩니다. 이 RadioNodeList 객체 내 노드는 트리 순서에 따라 정렬되어야 합니다.
  5. 해당 RadioNodeList 객체를 반환합니다.

RadioNodeList 인터페이스의 멤버는 NodeList 인터페이스로부터 상속된 동작을 수행해야 합니다.

RadioNodeList/value

현재 모든 엔진에서 지원합니다.

Firefox33+Safari7+Chrome21+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

value IDL 속성은 RadioNodeList 객체에 대해 다음과 같은 단계를 실행하여 값을 반환해야 합니다:

  1. elementinput 요소 중 라디오 버튼 상태에 있는 첫 번째 요소로 설정하고 checkedness가 true인 요소를 RadioNodeList 객체로 반환합니다. 그렇지 않으면 null로 설정합니다.

  2. element가 null인 경우 빈 문자열을 반환합니다.

  3. elementvalue 속성이 없는 요소인 경우 문자열 "on"을 반환합니다.

  4. 그렇지 않으면 elementvalue 속성의 값을 반환합니다.

value IDL 속성을 설정할 때 다음과 같은 단계를 실행해야 합니다:

  1. 새 값이 "on" 문자열인 경우: elementinput 요소 중 라디오 버튼 상태에 있고 새 값이 일치하거나 속성이 없는 첫 번째 요소로 설정합니다. 해당 요소가 없으면 대신 element를 null로 설정합니다.

    그렇지 않은 경우: elementinput 요소 중 라디오 버튼 상태에 있으며, 새 값이 일치하는 속성이 있는 첫 번째 요소로 설정합니다. 해당 요소가 없으면 대신 element를 null로 설정합니다.

  2. element가 null이 아닌 경우 checkedness를 true로 설정합니다.

2.6.3.3 HTMLOptionsCollection 인터페이스

HTMLOptionsCollection

현재 모든 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

HTMLOptionsCollection 인터페이스는 option 요소의 컬렉션을 나타내며, 항상 select 요소에 루팅되며 해당 요소의 하위 요소를 조작하는 속성과 메서드를 가집니다.

[Exposed=Window]
interface HTMLOptionsCollection : HTMLCollection {
  // 상속받은 item(), namedItem()
  [CEReactions] attribute unsigned long length; // 상속받은 length()를 덮어씁니다.
  [CEReactions] setter undefined (unsigned long index, HTMLOptionElement? option);
  [CEReactions] undefined add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  [CEReactions] undefined remove(long index);
  attribute long selectedIndex;
};
collection.length

collection에 있는 요소의 수를 반환합니다.

collection.length = value

기존 길이보다 작은 숫자로 설정하면 collection에 해당하는 컨테이너에 있는 option 요소의 수를 줄입니다.

기존 길이보다 큰 숫자로 설정하면 100000 이하일 경우, collection에 해당하는 컨테이너에 빈 option 요소를 추가합니다.

element = collection.item(index)
element = collection[index]

collection에서 인덱스 index에 있는 항목을 반환합니다. 항목들은 트리 순서로 정렬됩니다.

collection[index] = element

indexcollection에 있는 항목 수보다 큰 숫자인 경우, 해당 컨테이너에 빈 option 요소를 추가합니다.

null로 설정하면 collection에서 인덱스 index에 있는 항목을 제거합니다.

option 요소로 설정하면 collectionindex에 해당 요소를 추가하거나 교체합니다.

element = collection.namedItem(name)
element = collection[name]

collection에서 name과 일치하는 ID 또는 name을 가진 항목을 반환합니다.

일치하는 항목이 여러 개 있을 경우, 첫 번째 항목이 반환됩니다.

collection.add(element[, before])

elementbefore로 지정된 노드 앞에 삽입합니다.

before 인수는 숫자일 수 있으며, 이 경우 element가 해당 숫자의 항목 앞에 삽입됩니다. 또는 collection의 요소인 경우, element가 해당 요소 앞에 삽입됩니다.

before이 생략되거나 null이거나 범위를 벗어난 숫자인 경우 element는 목록의 끝에 추가됩니다.

element가 삽입될 요소의 상위 요소인 경우 "HierarchyRequestError" DOMException을 던집니다.

collection.remove(index)

collection에서 인덱스 index에 있는 항목을 제거합니다.

collection.selectedIndex

선택된 첫 번째 항목의 인덱스를 반환하거나, 선택된 항목이 없으면 −1을 반환합니다.

collection.selectedIndex = index

collection에서 인덱스 index에 있는 option 요소를 선택으로 변경합니다.

이 객체의 지원되는 속성 인덱스HTMLCollection 객체에 대해 정의된 것과 동일합니다.

length getter 단계는 컬렉션이 컬렉션으로 표현된 노드 수를 반환합니다.

length setter 단계는 다음과 같습니다:

  1. current를 컬렉션이 컬렉션으로 표현된 노드 수로 설정합니다.

  2. 주어진 값이 current보다 크면:

    1. 주어진 값이 100,000보다 크면 반환합니다.

    2. nvaluecurrent로 설정합니다.

    3. 속성이나 자식 노드가 없는 새 option 요소 n 개를 컬렉션이 루팅된 select 요소에 추가합니다. Mutation 이벤트는 새 DocumentFragment 요소가 삽입된 것처럼 발생해야 합니다.

  3. 주어진 값이 current보다 작으면:

    1. ncurrentvalue로 설정합니다.

    2. 컬렉션에서 마지막 n 개의 노드를 부모 노드에서 제거합니다.

length를 설정해도 optgroup 요소를 제거하거나 추가하지 않으며, 기존 optgroup 요소에 새로운 자식을 추가하지 않습니다(자식을 제거할 수는 있습니다).

지원되는 속성 이름은 모든 요소의 비어 있지 않은 idname 속성 값으로 구성됩니다. 이 요소들은 컬렉션으로 표현된 요소들이며, 트리 순서에 따라 배열됩니다. 나중에 중복된 항목은 무시되며, 요소의 idname보다 우선하여 적용됩니다. 이 두 속성이 다르며, 어느 것도 이전 항목의 중복이 아닌 경우에 한합니다.

사용자가 새로운 인덱스 속성의 값을 설정하거나 기존 인덱스 속성의 값을 설정해야 할 때, 다음 알고리즘을 실행해야 합니다:

  1. value가 null이면 remove 메서드의 단계를 index를 인수로 실행하고 반환합니다.

  2. length를 컬렉션이 컬렉션으로 표현된 노드 수로 설정합니다.

  3. nindex 마이너스 length로 설정합니다.

  4. 만약 n이 0보다 크면, 속성과 자식 노드가 없는 option 요소 n-1개로 구성된 DocumentFragmentselect 요소에 추가합니다. 이 요소는 HTMLOptionsCollection의 루트입니다.

  5. 만약 n이 0보다 크거나 같다면, valueselect 요소에 추가합니다. 그렇지 않으면, index번째 요소를 value로 교체합니다.

add(element, before) 메서드는 다음 알고리즘에 따라 작동해야 합니다:

  1. element가 컬렉션이 루팅된 select 요소의 상위 요소이면 "HierarchyRequestError" DOMException을 던져야 합니다.

  2. before가 요소인 경우, 해당 요소가 컬렉션이 루팅된 select 요소의 하위 요소가 아니라면 "NotFoundError" DOMException을 던져야 합니다.

  3. elementbefore가 동일한 요소인 경우, 반환합니다.

  4. before가 노드인 경우 reference를 해당 노드로 설정합니다. 그렇지 않으면, before가 정수이며 컬렉션에 before번째 노드가 있으면 reference를 해당 노드로 설정합니다. 그렇지 않으면 reference를 null로 설정합니다.

  5. reference가 null이 아닌 경우 parentreference의 부모 노드로 설정합니다. 그렇지 않으면 parent를 컬렉션이 루팅된 select 요소로 설정합니다.

  6. 삽입 전 elementparent 노드에 reference 앞에 삽입합니다.

remove(index) 메서드는 다음 알고리즘에 따라 작동해야 합니다:

  1. 컬렉션이 컬렉션으로 표현된 노드 수가 0이면 반환합니다.

  2. index가 0 이상이며 컬렉션이 컬렉션으로 표현된 노드 수보다 작은 수가 아니면 반환합니다.

  3. element를 컬렉션에서 index번째 요소로 설정합니다.

  4. element를 부모 노드에서 제거합니다.

selectedIndex IDL 속성은 select 요소에서 동일한 이름의 속성과 동일하게 동작해야 합니다. 이 속성은 컬렉션이 HTMLOptionsCollection에 루팅된 요소입니다.

2.6.4 DOMStringList 인터페이스

DOMStringList

모든 현재 엔진에서 지원됨.

Firefox1+Safari5.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

DOMStringList 인터페이스는 문자열 목록을 나타내는 구식 레트로 방식입니다.

[Exposed=(Window,Worker)]
            interface DOMStringList {
              readonly attribute unsigned long length;
              getter DOMString? item(unsigned long index);
              boolean contains(DOMString string);
            };

새 API는 sequence<DOMString> 또는 그에 상응하는 것을 사용해야 하며, DOMStringList를 사용해서는 안 됩니다.

strings.length

strings에 있는 문자열의 수를 반환합니다.

strings[index]
strings.item(index)

strings에서 index에 해당하는 문자열을 반환합니다.

strings.contains(string)

stringsstring이 포함되어 있으면 true를, 그렇지 않으면 false를 반환합니다.

DOMStringList 객체는 리스트와 연결되어 있습니다.

DOMStringList 인터페이스는 인덱스 속성을 지원합니다. 지원되는 속성 인덱스인덱스입니다. this의 연결된 리스트의 인덱스입니다.

DOMStringList/length

모든 현재 엔진에서 지원됨.

Firefox1+Safari5.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

length getter 단계는 연결된 리스트의 this크기를 반환하는 것입니다.

DOMStringList/item

모든 현재 엔진에서 지원됨.

Firefox1+Safari5.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

item(index) 메서드 단계는 연결된 리스트에서 index번째 항목을 반환하거나, index가 리스트의 크기보다 클 경우 null을 반환하는 것입니다.

DOMStringList/contains

모든 현재 엔진에서 지원됨.

Firefox1.5+Safari5.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

contains(string) 메서드 단계는 연결된 리스트에 string이 포함되어 있으면 true를 반환하고, 그렇지 않으면 false를 반환하는 것입니다.

2.7 구조화된 데이터의 안전한 전달

JavaScript 객체(예: 플랫폼 객체 포함)를 Realm 경계를 넘어 전달하기 위해, 이 명세는 객체를 직렬화 및 역직렬화하기 위한 다음과 같은 인프라를 정의합니다. 일부 경우에는 데이터를 복사하는 대신 기본 데이터를 전송하기도 합니다. 이 직렬화/역직렬화 프로세스는 "구조화된 복제"라고 통칭되지만, 대부분의 API는 별도의 직렬화 및 역직렬화 단계를 수행합니다. (주목할 예외는 structuredClone() 메서드입니다.)

이 섹션에서는 JavaScript 명세의 용어 및 서체 표기법을 사용합니다. [JAVASCRIPT]

2.7.1 직렬화 가능한 객체

/developer.mozilla.org/en-US/docs/Glossary/Serializable_object

Firefox103+SafariNoChrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

/developer.mozilla.org/en-US/docs/Glossary/Serializable_object

Firefox103+SafariNoChrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

/developer.mozilla.org/en-US/docs/Glossary/Serializable_object

Firefox103+SafariNoChrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

/developer.mozilla.org/en-US/docs/Glossary/Serializable_object

Firefox103+SafariNoChrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

/developer.mozilla.org/en-US/docs/Glossary/Serializable_object

Firefox103+SafariNoChrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

/developer.mozilla.org/en-US/docs/Glossary/Serializable_object

Firefox103+SafariNoChrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

직렬화 가능한 객체는 특정 realm에 독립적으로 직렬화되고 나중에 역직렬화될 수 있습니다. 이렇게 하면 디스크에 저장되었다가 나중에 복원되거나, agent 및 심지어 agent cluster 경계를 넘어 복제될 수 있습니다.

모든 객체가 직렬화 가능한 객체는 아니며, 직렬화 가능한 객체인 모든 객체의 모든 측면이 직렬화될 때 반드시 보존되는 것은 아닙니다.

플랫폼 객체직렬화 가능한 객체일 수 있으며, 그 주 인터페이스[Serializable] IDL 확장 속성으로 장식된 경우에만 가능합니다. 이러한 인터페이스는 또한 다음 알고리즘을 정의해야 합니다:

직렬화 단계, 플랫폼 객체 value, 기록 serialized, 및 boolean forStorage를 포함하는 단계를 설명합니다.

value의 데이터를 serialized 필드로 직렬화하는 단계입니다. serialized에 직렬화된 결과 데이터는 realm에 독립적이어야 합니다.

이 단계는 직렬화가 불가능한 경우 예외를 발생시킬 수 있습니다.

이 단계는 중첩된 데이터 구조를 직렬화하기 위해 하위 직렬화를 수행할 수 있습니다. memory 인수를 생략하게 되므로 StructuredSerialize를 직접 호출해서는 안 됩니다.

이 단계의 도입에서 forStorage 인수가 알고리즘과 관련이 없는 경우 언급을 생략해야 합니다.

역직렬화 단계, 기록 serialized, 플랫폼 객체 value, 및 realm targetRealm를 포함하는 단계를 설명합니다.

serialized의 데이터를 역직렬화하여 value를 적절하게 설정하는 단계입니다. value는 해당 플랫폼 객체 유형의 새로 생성된 인스턴스가 되며, 내부 데이터가 설정되지 않습니다. 이러한 설정은 이 단계의 작업입니다.

이 단계는 역직렬화가 불가능한 경우 예외를 발생시킬 수 있습니다.

이 단계는 중첩된 데이터 구조를 역직렬화하기 위해 하위 역직렬화를 수행할 수 있습니다. targetRealmmemory 인수를 생략하게 되므로 StructuredDeserialize를 직접 호출해서는 안 됩니다.

개별 플랫폼 객체의 정의에 따라 이러한 단계에서 직렬화 및 역직렬화되는 데이터가 결정됩니다. 일반적으로 단계는 매우 대칭적입니다.

[Serializable] 확장 속성은 인수를 받아들이지 않아야 하며, 인터페이스에만 나타나야 합니다. 인터페이스에 한 번 이상 나타나서는 안 됩니다.

주어진 플랫폼 객체의 경우 (역)직렬화 프로세스에서 고려되는 것은 객체의 주 인터페이스뿐입니다. 따라서 상속이 인터페이스 정의에 관여하는 경우 상속 체인의 각 [Serializable]-주석 인터페이스는 독립적인 직렬화 단계역직렬화 단계를 정의해야 하며, 상속된 인터페이스에서 올 수 있는 중요한 데이터를 고려해야 합니다.

Person이라는 플랫폼 객체를 정의하고, 이에 두 개의 연관된 데이터를 연결한다고 가정해 봅시다:

그런 다음 Person 인스턴스를 직렬화 가능한 객체로 정의할 수 있으며, [Serializable] 확장 속성으로 Person 인터페이스에 주석을 달고, 다음 동반 알고리즘을 정의합니다:

직렬화 단계
  1. serialized.[[Name]]에 value의 연결된 이름 값을 설정합니다.

  2. serializedBestFriendvalue의 연결된 최고의 친구 값을 하위 직렬화합니다.

  3. serialized.[[BestFriend]]에 serializedBestFriend를 설정합니다.

역직렬화 단계
  1. value의 연결된 이름 값을 serialized.[[Name]]으로 설정합니다.

  2. deserializedBestFriendserialized.[[BestFriend]]를 하위 역직렬화합니다.

  3. value의 연결된 최고의 친구 값을 deserializedBestFriend로 설정합니다.

JavaScript 사양에서 정의된 객체는 StructuredSerialize 추상 작업에 의해 직접 처리됩니다.

원래 이 사양은 한 realm에서 다른 realm으로 복제할 수 있는 "복제 가능한 객체" 개념을 정의했습니다. 그러나 더 복잡한 상황에서의 동작을 더 잘 명시하기 위해 모델이 업데이트되어 직렬화 및 역직렬화가 명시적으로 이루어졌습니다.

2.7.2 전송 가능한 객체

전송 가능한 객체agent 간에 전송되는 것을 지원합니다. 전송은 기본 데이터를 공유하면서 객체를 다시 생성한 다음 전송된 객체를 분리하는 것입니다. 이는 비용이 많이 드는 리소스의 소유권을 이전하는 데 유용합니다. 모든 객체가 전송 가능한 객체인 것은 아니며, 전송 가능한 객체의 모든 측면이 전송될 때 반드시 보존되는 것은 아닙니다.

전송은 되돌릴 수 없는 비멱등 연산입니다. 한 번 객체가 전송되면 다시 전송하거나 사용될 수 없습니다.

플랫폼 객체전송 가능한 객체일 수 있으며, 그 주 인터페이스[Transferable] IDL 확장 속성으로 장식된 경우에만 가능합니다. 이러한 인터페이스는 또한 다음 알고리즘을 정의해야 합니다:

전송 단계, 플랫폼 객체 value기록 dataHolder를 포함하는 단계를 설명합니다.

value의 데이터를 dataHolder의 필드로 전송하는 단계입니다. dataHolder에 보관된 결과 데이터는 realm에 독립적이어야 합니다.

이 단계는 전송이 불가능한 경우 예외를 발생시킬 수 있습니다.

전송 수신 단계, 기록 dataHolder플랫폼 객체 value를 포함하는 단계를 설명합니다.

dataHolder의 데이터를 수신하여 value를 적절하게 설정하는 단계입니다. value는 해당 플랫폼 객체 유형의 새로 생성된 인스턴스가 되며, 내부 데이터가 설정되지 않습니다. 이러한 설정은 이 단계의 작업입니다.

이 단계는 전송 수신이 불가능한 경우 예외를 발생시킬 수 있습니다.

개별 플랫폼 객체의 정의에 따라 이 단계에서 전송되는 데이터가 결정됩니다. 일반적으로 단계는 매우 대칭적입니다.

[Transferable] 확장 속성은 인수를 받아들이지 않아야 하며, 인터페이스에만 나타나야 합니다. 인터페이스에 한 번 이상 나타나서는 안 됩니다.

주어진 플랫폼 객체의 경우 전송 프로세스에서 고려되는 것은 객체의 주 인터페이스뿐입니다. 따라서 상속이 인터페이스 정의에 관여하는 경우 상속 체인의 각 [Transferable]-주석 인터페이스는 독립적인 전송 단계전송 수신 단계를 정의해야 하며, 상속된 인터페이스에서 올 수 있는 중요한 데이터를 고려해야 합니다.

플랫폼 객체전송 가능한 객체인 경우 내부 슬롯 [[Detached]]를 가집니다. 이를 통해 한 번 전송된 플랫폼 객체가 다시 전송되지 않도록 보장합니다.

JavaScript 사양에서 정의된 객체는 StructuredSerializeWithTransfer 추상 작업에 의해 직접 처리됩니다.

2.7.3 StructuredSerializeInternal ( value, forStorage [ , memory ] )

StructuredSerializeInternal 추상 연산은 JavaScript 값 value를 입력으로 받아 이를 realm에 독립적인 형태로 직렬화합니다. 여기서는 이를 레코드(Record)로 나타냅니다. 이 직렬화된 형식에는 나중에 다른 realm에서 새 JavaScript 값으로 역직렬화하는 데 필요한 모든 정보가 포함되어 있습니다.

이 과정은 예를 들어 직렬화할 수 없는 객체를 직렬화하려고 할 때 예외를 발생시킬 수 있습니다.

  1. 만약 memory가 제공되지 않았다면, memory를 빈 으로 설정합니다.

    memory 맵의 목적은 객체를 두 번 직렬화하는 것을 방지하는 것입니다. 이는 사이클을 유지하고 그래프 내 중복 객체의 동일성을 유지하게 됩니다.

  2. 만약 memory[value]가 존재한다면 memory[value]를 반환합니다.

  3. deep를 false로 설정합니다.

  4. 만약 Type(value)이 Undefined, Null, Boolean, Number, BigInt, 또는 String인 경우, { [[Type]]: "primitive", [[Value]]: value }를 반환합니다.

  5. 만약 Type(value)이 Symbol인 경우, "DataCloneError" DOMException을 발생시킵니다.

  6. serialized를 초기화되지 않은 값으로 설정합니다.

  7. 만약 value가 [[BooleanData]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "Boolean", [[BooleanData]]: value.[[BooleanData]] }로 설정합니다.

  8. 그렇지 않다면, 만약 value가 [[NumberData]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "Number", [[NumberData]]: value.[[NumberData]] }로 설정합니다.

  9. 그렇지 않다면, 만약 value가 [[BigIntData]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "BigInt", [[BigIntData]]: value.[[BigIntData]] }로 설정합니다.

  10. 그렇지 않다면, 만약 value가 [[StringData]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "String", [[StringData]]: value.[[StringData]] }로 설정합니다.

  11. 그렇지 않다면, 만약 value가 [[DateValue]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "Date", [[DateValue]]: value.[[DateValue]] }로 설정합니다.

  12. 그렇지 않다면, 만약 value가 [[RegExpMatcher]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "RegExp", [[RegExpMatcher]]: value.[[RegExpMatcher]], [[OriginalSource]]: value.[[OriginalSource]], [[OriginalFlags]]: value.[[OriginalFlags]] }로 설정합니다.

  13. 그렇지 않다면, 만약 value가 [[ArrayBufferData]] 내부 슬롯을 가지고 있다면:

    1. 만약 IsSharedArrayBuffer(value)이 true라면:

      1. 만약 현재 설정 객체교차 출처 고립성 기능이 false라면, "DataCloneError" DOMException을 발생시킵니다.

        이 확인은 직렬화 시에만 필요하며, 역직렬화 시에는 필요하지 않습니다. 이는 교차 출처 고립성 기능은 시간이 지나도 변하지 않으며, SharedArrayBuffer에이전트 클러스터를 벗어날 수 없기 때문입니다.

      2. 만약 forStorage가 true라면, "DataCloneError" DOMException을 발생시킵니다.

      3. 만약 value가 [[ArrayBufferMaxByteLength]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "GrowableSharedArrayBuffer", [[ArrayBufferData]]: value.[[ArrayBufferData]], [[ArrayBufferByteLengthData]]: value.[[ArrayBufferByteLengthData]], [[ArrayBufferMaxByteLength]]: value.[[ArrayBufferMaxByteLength]], [[AgentCluster]]: 주변 에이전트에이전트 클러스터 }로 설정합니다.

      4. 그렇지 않다면, serialized를 { [[Type]]: "SharedArrayBuffer", [[ArrayBufferData]]: value.[[ArrayBufferData]], [[ArrayBufferByteLength]]: value.[[ArrayBufferByteLength]], [[AgentCluster]]: 주변 에이전트에이전트 클러스터 }로 설정합니다.

    2. 그렇지 않다면:

      1. 만약 IsDetachedBuffer(value)이 true라면, "DataCloneError" DOMException을 발생시킵니다.

      2. sizevalue.[[ArrayBufferByteLength]]로 설정합니다.

      3. dataCopy를 ? CreateByteDataBlock(size)으로 설정합니다.

        이는 할당 실패 시 RangeError 예외를 발생시킬 수 있습니다.

      4. CopyDataBlockBytes(dataCopy, 0, value.[[ArrayBufferData]], 0, size)를 수행합니다.

      5. 만약 value가 [[ArrayBufferMaxByteLength]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "ResizableArrayBuffer", [[ArrayBufferData]]: dataCopy, [[ArrayBufferByteLength]]: size, [[ArrayBufferMaxByteLength]]: value.[[ArrayBufferMaxByteLength]] }로 설정합니다.

      6. 그렇지 않다면, serialized를 { [[Type]]: "ArrayBuffer", [[ArrayBufferData]]: dataCopy, [[ArrayBufferByteLength]]: size }로 설정합니다.

  14. 그렇지 않다면, 만약 value가 [[ViewedArrayBuffer]] 내부 슬롯을 가지고 있다면:

    1. 만약 IsArrayBufferViewOutOfBounds(value)이 true라면, "DataCloneError" DOMException을 발생시킵니다.

    2. buffervalue의 [[ViewedArrayBuffer]] 내부 슬롯 값으로 설정합니다.

    3. bufferSerialized를 ? StructuredSerializeInternal(buffer, forStorage, memory)로 설정합니다.

    4. Assert: bufferSerialized.[[Type]]이 "ArrayBuffer", "ResizableArrayBuffer", "SharedArrayBuffer", 또는 "GrowableSharedArrayBuffer"입니다.

    5. 만약 value가 [[DataView]] 내부 슬롯을 가지고 있다면, serialized를 { [[Type]]: "ArrayBufferView", [[Constructor]]: "DataView", [[ArrayBufferSerialized]]: bufferSerialized, [[ByteLength]]: value.[[ByteLength]], [[ByteOffset]]: value.[[ByteOffset]] }로 설정합니다.

    6. 그렇지 않다면:

      1. Assert: value가 [[TypedArrayName]] 내부 슬롯을 가지고 있습니다.

      2. serialized를 { [[Type]]: "ArrayBufferView", [[Constructor]]: value.[[TypedArrayName]], [[ArrayBufferSerialized]]: bufferSerialized, [[ByteLength]]: value.[[ByteLength]], [[ByteOffset]]: value.[[ByteOffset]], [[ArrayLength]]: value.[[ArrayLength]] }로 설정합니다.

  15. 그렇지 않다면, 만약 value가 [[MapData]] 내부 슬롯을 가지고 있다면:

    1. serialized를 { [[Type]]: "Map", [[MapData]]: 새 빈 리스트(List) }로 설정합니다.

    2. deep을 true로 설정합니다.

  16. 그렇지 않다면, 만약 value가 [[SetData]] 내부 슬롯을 가지고 있다면:

    1. serialized를 { [[Type]]: "Set", [[SetData]]: 새 빈 리스트(List) }로 설정합니다.

    2. deep을 true로 설정합니다.

  17. 그렇지 않다면, value가 [[ErrorData]] 내부 슬롯을 가지고 있으며 value플랫폼 객체가 아니라면:

    1. name을 ? Get(value, "name")으로 설정합니다.

    2. 만약 name이 "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", 또는 "URIError" 중 하나가 아니라면, name을 "Error"로 설정합니다.

    3. valueMessageDesc을 ? value.[[GetOwnProperty]]("message")로 설정합니다.

    4. 만약 IsDataDescriptor(valueMessageDesc)이 false라면, message를 undefined로 설정하고, 그렇지 않다면 ? ToString(valueMessageDesc.[[Value]])으로 설정합니다.

    5. serialized를 { [[Type]]: "Error", [[Name]]: name, [[Message]]: message }로 설정합니다.

    6. 사용자 에이전트는 serialized에 현재 명시되지 않은, 특히 stack 속성과 같은 흥미로운 동반 데이터를 직렬화된 표현으로 추가해야 합니다.

      이 데이터에 대한 명세 작업이 진행 중인 Error Stacks 제안을 참조하십시오. [JSERRORSTACKS]

  18. 그렇지 않다면, value가 배열 이국 객체인 경우:

    1. valueLenDescriptor을 ? OrdinaryGetOwnProperty(value, "length")으로 설정합니다.

    2. valueLenvalueLenDescriptor.[[Value]]로 설정합니다.

    3. serialized를 { [[Type]]: "Array", [[Length]]: valueLen, [[Properties]]: 새 빈 리스트(List) }로 설정합니다.

    4. deep을 true로 설정합니다.

  19. 그렇지 않다면, value플랫폼 객체이며 직렬화 가능한 객체라면:

    1. 만약 value가 [[Detached]] 내부 슬롯이 true인 경우, "DataCloneError" DOMException을 발생시킵니다.

    2. typeStringvalue기본 인터페이스의 식별자로 설정합니다.

    3. serialized를 { [[Type]]: typeString }로 설정합니다.

    4. deep을 true로 설정합니다.

  20. 그렇지 않다면, value플랫폼 객체라면, "DataCloneError" DOMException을 발생시킵니다.

  21. 그렇지 않다면, IsCallable(value)이 true라면, "DataCloneError" DOMException을 발생시킵니다.

  22. 그렇지 않다면, value가 [[Prototype]], [[Extensible]], 또는 [[PrivateElements]]를 제외한 내부 슬롯을 가지고 있다면, "DataCloneError" DOMException을 발생시킵니다.

    예를 들어, [[PromiseState]] 또는 [[WeakMapData]] 내부 슬롯이 있습니다.

  23. 그렇지 않다면, value가 이국 객체이며 value%Object.prototype%와 관련된 어떤 realm의 본질적인 객체가 아니라면, "DataCloneError" DOMException을 발생시킵니다.

    예를 들어, 프록시 객체입니다.

  24. 그렇지 않다면:

    1. serialized를 { [[Type]]: "Object", [[Properties]]: 새 빈 리스트(List) }로 설정합니다.

    2. deep을 true로 설정합니다.

    %Object.prototype%는 이 단계와 후속 단계를 통해 처리됩니다. 최종 결과는 이국 객체 특성이 무시되며, 역직렬화 후 결과는 빈 객체가 될 것입니다( 불변 프로토타입 이국 객체는 아님).

  25. Set memory[value]을 serialized로 설정합니다.

  26. 만약 deep이 true라면:

    1. 만약 value가 [[MapData]] 내부 슬롯을 가지고 있다면:

      1. copiedList를 새 빈 리스트(List)로 설정합니다.

      2. 각각에 대해 레코드(Record) { [[Key]], [[Value]] } entryvalue.[[MapData]]에 포함된 경우:

        1. copiedEntry를 새 레코드(Record) { [[Key]]: entry.[[Key]], [[Value]]: entry.[[Value]] }로 설정합니다.

        2. 만약 copiedEntry.[[Key]]가 특별한 값 empty가 아니라면, append copiedEntrycopiedList에 추가합니다.

      3. 각각에 대해 레코드(Record) { [[Key]], [[Value]] } entrycopiedList에 포함된 경우:

        1. serializedKey를 ? StructuredSerializeInternal(entry.[[Key]], forStorage, memory)으로 설정합니다.

        2. serializedValue를 ? StructuredSerializeInternal(entry.[[Value]], forStorage, memory)으로 설정합니다.

        3. Append { [[Key]]: serializedKey, [[Value]]: serializedValue }를 serialized.[[MapData]]에 추가합니다.

    2. 그렇지 않다면, value가 [[SetData]] 내부 슬롯을 가지고 있다면:

      1. copiedList를 새 빈 리스트(List)로 설정합니다.

      2. 각각에 대해 entryvalue.[[SetData]]에 포함된 경우:

        1. 만약 entry가 특별한 값 empty가 아니라면, append entrycopiedList에 추가합니다.

      3. 각각에 대해 entrycopiedList에 포함된 경우:

        1. serializedEntry를 ? StructuredSerializeInternal(entry, forStorage, memory)으로 설정합니다.

        2. append serializedEntryserialized.[[SetData]]에 추가합니다.

    3. 그렇지 않다면, value플랫폼 객체이며 직렬화 가능한 객체라면, 직렬화 단계를 수행하여 value기본 인터페이스를 주어진 value, serialized, 및 forStorage에 대해 직렬화합니다.

      직렬화 단계하위 직렬화를 수행해야 할 수 있습니다. 이는 값을 입력으로 받아, StructuredSerializeInternal(subValue, forStorage, memory)을 반환하는 연산입니다. (즉, 하위 직렬화는 이 호출 내에서 일관성을 유지하기 위해 StructuredSerializeInternal의 특수화입니다.)

    4. 그렇지 않다면, ! EnumerableOwnProperties(value, key) 내의 각각의 key에 대해:

      1. ! HasOwnProperty(value, key)이 true라면:

        1. inputValue를 ? value.[[Get]](key, value)으로 설정합니다.

        2. outputValue를 ? StructuredSerializeInternal(inputValue, forStorage, memory)으로 설정합니다.

        3. append { [[Key]]: key, [[Value]]: outputValue }를 serialized.[[Properties]]에 추가합니다.

  27. serialized를 반환합니다.

StructuredSerializeInternal에 의해 생성된 레코드(Record)는 다른 레코드로의 "포인터"를 포함하여 순환 참조를 생성할 수 있다는 점을 인식하는 것이 중요합니다. 예를 들어, 다음 JavaScript 객체를 StructuredSerializeInternal에 전달하면:

const o = {};
o.myself = o;

다음과 같은 결과가 생성됩니다:

{
  [[Type]]: "Object",
  [[Properties]]: «
    {
      [[Key]]: "myself",
      [[Value]]: <a pointer to this whole structure>
    }
  »
}

2.7.4 StructuredSerialize ( value )

  1. ? StructuredSerializeInternal(value, false)를 반환합니다.

2.7.5 StructuredSerializeForStorage ( value )

  1. ? StructuredSerializeInternal(value, true)를 반환합니다.

2.7.6 StructuredDeserialize ( serialized, targetRealm [ , memory ] )

StructuredDeserialize 추상 연산은 입력으로 레코드(Record) serialized를 사용하며, 이는 이전에 StructuredSerialize 또는 StructuredSerializeForStorage에 의해 생성되었으며, 이를 사용하여 targetRealm에 새로운 JavaScript 값을 역직렬화합니다.

이 과정은 예를 들어 새로운 객체(특히 ArrayBuffer 객체)의 메모리 할당을 시도할 때 예외를 던질 수 있습니다.

  1. 만약 memory가 제공되지 않았다면, memory를 빈 으로 설정합니다.

    memory 맵의 목적은 객체를 두 번 역직렬화하지 않도록 하는 것입니다. 이는 그래프에서 중복 객체의 순환과 아이덴티티를 유지하게 됩니다.

  2. 만약 memory[serialized]가 존재한다면, memory[serialized]을 반환합니다.

  3. deep을 false로 설정합니다.

  4. value를 초기화되지 않은 값으로 설정합니다.

  5. 만약 serialized.[[Type]]이 "primitive"라면, valueserialized.[[Value]]로 설정합니다.

  6. 그렇지 않으면, serialized.[[Type]]이 "Boolean"인 경우, valuetargetRealm에서 [[BooleanData]] 내부 슬롯 값이 serialized.[[BooleanData]]인 새로운 Boolean 객체로 설정합니다.

  7. 그렇지 않으면, serialized.[[Type]]이 "Number"인 경우, valuetargetRealm에서 [[NumberData]] 내부 슬롯 값이 serialized.[[NumberData]]인 새로운 Number 객체로 설정합니다.

  8. 그렇지 않으면, serialized.[[Type]]이 "BigInt"인 경우, valuetargetRealm에서 [[BigIntData]] 내부 슬롯 값이 serialized.[[BigIntData]]인 새로운 BigInt 객체로 설정합니다.

  9. 그렇지 않으면, serialized.[[Type]]이 "String"인 경우, valuetargetRealm에서 [[StringData]] 내부 슬롯 값이 serialized.[[StringData]]인 새로운 String 객체로 설정합니다.

  10. 그렇지 않으면, serialized.[[Type]]이 "Date"인 경우, valuetargetRealm에서 [[DateValue]] 내부 슬롯 값이 serialized.[[DateValue]]인 새로운 Date 객체로 설정합니다.

  11. 그렇지 않으면, serialized.[[Type]]이 "RegExp"인 경우, valuetargetRealm에서 [[RegExpMatcher]] 내부 슬롯 값이 serialized.[[RegExpMatcher]]이며, [[OriginalSource]] 내부 슬롯 값이 serialized.[[OriginalSource]]이고, [[OriginalFlags]] 내부 슬롯 값이 serialized.[[OriginalFlags]]인 새로운 RegExp 객체로 설정합니다.

  12. 그렇지 않으면, serialized.[[Type]]이 "SharedArrayBuffer"인 경우:

    1. 만약 targetRealm의 대응하는 에이전트 클러스터serialized.[[AgentCluster]]가 아니라면, "DataCloneError" DOMException을 던집니다.

    2. 그렇지 않으면, valuetargetRealm에서 [[ArrayBufferData]] 내부 슬롯 값이 serialized.[[ArrayBufferData]]이며, [[ArrayBufferByteLength]] 내부 슬롯 값이 serialized.[[ArrayBufferByteLength]]인 새로운 SharedArrayBuffer 객체로 설정합니다.

  13. 그렇지 않으면, serialized.[[Type]]이 "GrowableSharedArrayBuffer"인 경우:

    1. 만약 targetRealm의 대응하는 에이전트 클러스터serialized.[[AgentCluster]]가 아니라면, "DataCloneError" DOMException을 던집니다.

    2. 그렇지 않으면, valuetargetRealm에서 [[ArrayBufferData]] 내부 슬롯 값이 serialized.[[ArrayBufferData]]이며, [[ArrayBufferByteLengthData]] 내부 슬롯 값이 serialized.[[ArrayBufferByteLengthData]]이고, [[ArrayBufferMaxByteLength]] 내부 슬롯 값이 serialized.[[ArrayBufferMaxByteLength]]인 새로운 SharedArrayBuffer 객체로 설정합니다.

  14. 그렇지 않으면, serialized.[[Type]]이 "ArrayBuffer"인 경우, valuetargetRealm에서 [[ArrayBufferData]] 내부 슬롯 값이 serialized.[[ArrayBufferData]]이며, [[ArrayBufferByteLength]] 내부 슬롯 값이 serialized.[[ArrayBufferByteLength]]인 새로운 ArrayBuffer 객체로 설정합니다.

    이 단계에서 예외가 발생하면, 이를 catch한 다음, "DataCloneError" DOMException을 던집니다.

    이 단계에서는 메모리가 부족하여 해당 ArrayBuffer 객체를 생성할 수 없는 경우 예외가 발생할 수 있습니다.

  15. 그렇지 않으면, serialized.[[Type]]이 "ResizableArrayBuffer"인 경우, valuetargetRealm에서 [[ArrayBufferData]] 내부 슬롯 값이 serialized.[[ArrayBufferData]]이며, [[ArrayBufferByteLength]] 내부 슬롯 값이 serialized.[[ArrayBufferByteLength]]이고, [[ArrayBufferMaxByteLength]] 내부 슬롯 값이 serialized.[[ArrayBufferMaxByteLength]]인 새로운 ArrayBuffer 객체로 설정합니다.

    이 단계에서 예외가 발생하면, 이를 catch한 다음, "DataCloneError" DOMException을 던집니다.

    이 단계에서는 메모리가 부족하여 해당 ArrayBuffer 객체를 생성할 수 없는 경우 예외가 발생할 수 있습니다.

  16. 그렇지 않으면, serialized.[[Type]]이 "ArrayBufferView"인 경우:

    1. deserializedArrayBuffer를 ? StructuredDeserialize(serialized.[[ArrayBufferSerialized]], targetRealm, memory)로 설정합니다.

    2. 만약 serialized.[[Constructor]]가 "DataView"라면, valuetargetRealm에서 [[ViewedArrayBuffer]] 내부 슬롯 값이 deserializedArrayBuffer이고, [[ByteLength]] 내부 슬롯 값이 serialized.[[ByteLength]]이며, [[ByteOffset]] 내부 슬롯 값이 serialized.[[ByteOffset]]인 새로운 DataView 객체로 설정합니다.

    3. 그렇지 않으면, valuetargetRealm에서 생성자 serialized.[[Constructor]]을 사용하여 생성된 새로운 타입 배열 객체로 설정합니다. 이 객체의 [[ViewedArrayBuffer]] 내부 슬롯 값은 deserializedArrayBuffer, [[TypedArrayName]] 내부 슬롯 값은 serialized.[[Constructor]], [[ByteLength]] 내부 슬롯 값은 serialized.[[ByteLength]], [[ByteOffset]] 내부 슬롯 값은 serialized.[[ByteOffset]], 그리고 [[ArrayLength]] 내부 슬롯 값은 serialized.[[ArrayLength]]입니다.

  17. 그렇지 않으면, serialized.[[Type]]이 "Map"인 경우:

    1. valuetargetRealm에서 [[MapData]] 내부 슬롯 값이 빈 리스트인 새로운 Map 객체로 설정합니다.

    2. deep을 true로 설정합니다.

  18. 그렇지 않으면, serialized.[[Type]]이 "Set"인 경우:

    1. valuetargetRealm에서 [[SetData]] 내부 슬롯 값이 빈 리스트인 새로운 Set 객체로 설정합니다.

    2. deep을 true로 설정합니다.

  19. 그렇지 않으면, serialized.[[Type]]이 "Array"인 경우:

    1. outputPrototargetRealm.[[Intrinsics]].[[%Array.prototype%]]로 설정합니다.

    2. value를 ! ArrayCreate(serialized.[[Length]], outputProto)로 설정합니다.

    3. deep을 true로 설정합니다.

  20. 그렇지 않으면, serialized.[[Type]]이 "Object"인 경우:

    1. valuetargetRealm에서 새로운 객체로 설정합니다.

    2. deep을 true로 설정합니다.

  21. 그렇지 않으면, serialized.[[Type]]이 "Error"인 경우:

    1. prototype%Error.prototype%로 설정합니다.

    2. 만약 serialized.[[Name]]이 "EvalError"라면, prototype%EvalError.prototype%로 설정합니다.

    3. 만약 serialized.[[Name]]이 "RangeError"라면, prototype%RangeError.prototype%로 설정합니다.

    4. 만약 serialized.[[Name]]이 "ReferenceError"라면, prototype%ReferenceError.prototype%로 설정합니다.

    5. 만약 serialized.[[Name]]이 "SyntaxError"라면, prototype%SyntaxError.prototype%로 설정합니다.

    6. 만약 serialized.[[Name]]이 "TypeError"라면, prototype%TypeError.prototype%로 설정합니다.

    7. 만약 serialized.[[Name]]이 "URIError"라면, prototype%URIError.prototype%로 설정합니다.

    8. messageserialized.[[Message]]로 설정합니다.

    9. valueOrdinaryObjectCreate(prototype, « [[ErrorData]] »)로 설정합니다.

    10. messageDescPropertyDescriptor{ [[Value]]: message, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }로 설정합니다.

    11. 만약 message가 undefined가 아니라면, ! OrdinaryDefineOwnProperty(value, "message", messageDesc)을 수행합니다.

    12. serialized에 연결된 중요한 동반 데이터는 역직렬화되어 value에 연결되어야 합니다.

  22. 그렇지 않으면:

    1. interfaceNameserialized.[[Type]]으로 설정합니다.

    2. 만약 interfaceName으로 식별된 인터페이스가 targetRealm에서 노출되지 않았다면, "DataCloneError" DOMException을 던집니다.

    3. valueinterfaceName으로 식별된 인터페이스의 새로운 인스턴스로 설정합니다. 이 인스턴스는 targetRealm에서 생성됩니다.

    4. deep을 true로 설정합니다.

  23. Set memory[serialized]를 value로 설정합니다.

  24. 만약 deep이 true라면:

    1. 만약 serialized.[[Type]]이 "Map"이라면:

      1. 각각레코드(Record) { [[Key]], [[Value]] } entry에 대해, serialized.[[MapData]]를 반복합니다:

        1. deserializedKey를 ? StructuredDeserialize(entry.[[Key]], targetRealm, memory)로 설정합니다.

        2. deserializedValue를 ? StructuredDeserialize(entry.[[Value]], targetRealm, memory)로 설정합니다.

        3. Append { [[Key]]: deserializedKey, [[Value]]: deserializedValue }를 value.[[MapData]]에 추가합니다.

    2. 그렇지 않으면, serialized.[[Type]]이 "Set"인 경우:

      1. 각각entry에 대해, serialized.[[SetData]]를 반복합니다:

        1. deserializedEntry를 ? StructuredDeserialize(entry, targetRealm, memory)로 설정합니다.

        2. Append deserializedEntryvalue.[[SetData]]에 추가합니다.

    3. 그렇지 않으면, serialized.[[Type]]이 "Array" 또는 "Object"인 경우:

      1. 각각레코드(Record) { [[Key]], [[Value]] } entry에 대해, serialized.[[Properties]]를 반복합니다:

        1. deserializedValue를 ? StructuredDeserialize(entry.[[Value]], targetRealm, memory)로 설정합니다.

        2. result를 ! CreateDataProperty(value, entry.[[Key]], deserializedValue)로 설정합니다.

        3. Assert: result가 true임을 확인합니다.

    4. 그렇지 않으면:

      1. 적절한 역직렬화 단계를 수행합니다. 이 인터페이스는 serialized.[[Type]]으로 식별되며, serialized, valuetargetRealm을 입력으로 받습니다.

        역직렬화 단계하위 역직렬화를 수행해야 할 수 있습니다. 이는 이전에 직렬화된 레코드(Record) subSerialized을 입력으로 받아 StructuredDeserialize(subSerialized, targetRealm, memory)를 반환합니다. (즉, 하위 역직렬화는 이 호출 내에서 일관성을 유지하기 위해 StructuredDeserialize의 특수화된 버전입니다.)

  25. value를 반환합니다.

2.7.7 StructuredSerializeWithTransfer ( value, transferList )

  1. memory를 빈 맵(map)으로 설정합니다.

    StructuredSerializeInternal에 의해 사용되는 일반적인 방식 외에도, 이 알고리즘에서는 memory를 사용하여 transferList의 항목을 무시하게 하고, 직접 처리할 수 있도록 합니다.

  2. 각각transferable에 대해 transferList를 반복합니다:

    1. 만약 transferable이 [[ArrayBufferData]] 내부 슬롯이나 [[Detached]] 내부 슬롯을 가지고 있지 않다면, "DataCloneError" DOMException을 던집니다.

    2. 만약 transferable이 [[ArrayBufferData]] 내부 슬롯을 가지고 있고 IsSharedArrayBuffer(transferable)가 true라면, "DataCloneError" DOMException을 던집니다.

    3. 만약 memory[transferable]가 존재한다면, "DataCloneError" DOMException을 던집니다.

    4. Set memory[transferable]을 { [[Type]]: 초기화되지 않은 값 }으로 설정합니다.

      transferable은 아직 전송되지 않았습니다. 왜냐하면 전송에는 부작용이 있으며 StructuredSerializeInternal이 먼저 예외를 던질 수 있어야 하기 때문입니다.

  3. serialized를 ? StructuredSerializeInternal(value, false, memory)로 설정합니다.

  4. transferDataHolders를 빈 리스트(List)로 설정합니다.

  5. 각각transferable에 대해 transferList를 반복합니다:

    1. 만약 transferable이 [[ArrayBufferData]] 내부 슬롯을 가지고 있고, IsDetachedBuffer(transferable)가 true라면, "DataCloneError" DOMException을 던집니다.

    2. 만약 transferable[[Detached]] 내부 슬롯을 가지고 있고, transferable.[[Detached]]가 true라면, "DataCloneError" DOMException을 던집니다.

    3. dataHoldermemory[transferable]로 설정합니다.

    4. 만약 transferable이 [[ArrayBufferData]] 내부 슬롯을 가지고 있다면:

      1. 만약 transferable이 [[ArrayBufferMaxByteLength]] 내부 슬롯을 가지고 있다면:

        1. dataHolder.[[Type]]을 "ResizableArrayBuffer"로 설정합니다.

        2. dataHolder.[[ArrayBufferData]]를 transferable.[[ArrayBufferData]]로 설정합니다.

        3. dataHolder.[[ArrayBufferByteLength]]를 transferable.[[ArrayBufferByteLength]]로 설정합니다.

        4. dataHolder.[[ArrayBufferMaxByteLength]]를 transferable.[[ArrayBufferMaxByteLength]]로 설정합니다.

      2. 그렇지 않다면:

        1. dataHolder.[[Type]]을 "ArrayBuffer"로 설정합니다.

        2. dataHolder.[[ArrayBufferData]]를 transferable.[[ArrayBufferData]]로 설정합니다.

        3. dataHolder.[[ArrayBufferByteLength]]를 transferable.[[ArrayBufferByteLength]]로 설정합니다.

      3. ? DetachArrayBuffer(transferable)을 수행합니다.

        명세서는 [[ArrayBufferDetachKey]] 내부 슬롯을 사용하여 ArrayBuffer가 분리되지 않도록 할 수 있습니다. 예를 들어, WebAssembly JavaScript Interface에서 사용됩니다. [WASMJS]

    5. 그렇지 않다면:

      1. Assert: transferable플랫폼 객체(platform object)이며 전송 가능한 객체(transferable object)라는 것을 확인합니다.

      2. interfaceNametransferable주 인터페이스(primary interface)의 식별자로 설정합니다.

      3. dataHolder.[[Type]]을 interfaceName으로 설정합니다.

      4. 식별된 인터페이스에 대해 적절한 전송 단계(transfer steps)를 수행합니다.

      5. transferable.[[Detached]]를 true로 설정합니다.

    6. Append dataHoldertransferDataHolders에 추가합니다.

  6. { [[Serialized]]: serialized, [[TransferDataHolders]]: transferDataHolders }을 반환합니다.

2.7.8 StructuredDeserializeWithTransfer (serializeWithTransferResult, targetRealm)

  1. memory를 빈 맵(map)으로 설정합니다.

    StructuredSerializeWithTransfer와 유사하게, StructuredDeserialize에서 일반적으로 사용되는 방식 외에도, 이 알고리즘에서 memory를 사용하여 serializeWithTransferResult.[[TransferDataHolders]]의 항목을 무시하게 하고, 직접 처리할 수 있도록 합니다.

  2. transferredValues를 새로운 빈 리스트(List)로 설정합니다.

  3. 각각transferDataHolder에 대해 serializeWithTransferResult.[[TransferDataHolders]]를 반복합니다:

    1. value를 초기화되지 않은 값으로 설정합니다.

    2. 만약 transferDataHolder.[[Type]]이 "ArrayBuffer"라면, valuetargetRealm의 새로운 ArrayBuffer 객체로 설정하고, 이 객체의 [[ArrayBufferData]] 내부 슬롯 값은 transferDataHolder.[[ArrayBufferData]]로, [[ArrayBufferByteLength]] 내부 슬롯 값은 transferDataHolder.[[ArrayBufferByteLength]]로 설정합니다.

      [[ArrayBufferData]]에 의해 점유된 원래 메모리가 역직렬화 동안 접근 가능하다면, 이 단계에서 예외가 발생할 가능성은 낮습니다. 이는 새 메모리를 할당할 필요가 없기 때문이며, 대신 [[ArrayBufferData]]에 의해 점유된 메모리가 새 ArrayBuffer로 전송됩니다. 예를 들어, 소스와 대상 realm이 동일한 프로세스 내에 있을 때 이럴 수 있습니다.

    3. 그렇지 않고, 만약 transferDataHolder.[[Type]]이 "ResizableArrayBuffer"라면, valuetargetRealm의 새로운 ArrayBuffer 객체로 설정하고, 이 객체의 [[ArrayBufferData]] 내부 슬롯 값은 transferDataHolder.[[ArrayBufferData]], [[ArrayBufferByteLength]] 내부 슬롯 값은 transferDataHolder.[[ArrayBufferByteLength]], 그리고 [[ArrayBufferMaxByteLength]] 내부 슬롯 값은 transferDataHolder.[[ArrayBufferMaxByteLength]]로 설정합니다.

      이전 단계와 같은 이유로, 이 단계에서도 예외가 발생할 가능성은 낮습니다.

    4. 그렇지 않다면:

      1. interfaceNametransferDataHolder.[[Type]]으로 설정합니다.

      2. 만약 interfaceName으로 식별된 인터페이스가 targetRealm에서 노출되지 않은 경우, "DataCloneError" DOMException을 던집니다.

      3. valueinterfaceName으로 식별된 인터페이스의 targetRealm에 생성된 새로운 인스턴스로 설정합니다.

      4. interfaceName으로 식별된 인터페이스에 대해 적절한 전송 수신 단계transferDataHoldervalue에 대해 수행합니다.

    5. Set memory[transferDataHolder]를 value로 설정합니다.

    6. Append valuetransferredValues에 추가합니다.

  4. deserialized를 ? StructuredDeserialize(serializeWithTransferResult.[[Serialized]], targetRealm, memory)로 설정합니다.

  5. { [[Deserialized]]: deserialized, [[TransferredValues]]: transferredValues }을 반환합니다.

2.7.9 다른 명세에서의 직렬화 및 전송 수행

다른 명세에서 여기에 정의된 추상 연산을 사용할 수 있습니다. 다음은 각 추상 연산이 일반적으로 언제 유용한지, 예제와 함께 제공된 가이드입니다.

StructuredSerializeWithTransfer
StructuredDeserializeWithTransfer

전송 목록과 함께 값을 다른 realm으로 복제하지만, 대상 realm이 미리 알려지지 않은 경우입니다. 이 경우 직렬화 단계는 즉시 수행할 수 있으며, 역직렬화 단계는 대상 realm이 알려질 때까지 지연될 수 있습니다.

messagePort.postMessage()는 이러한 추상 연산 쌍을 사용하며, 대상 realm은 MessagePort전송된 후에야 알 수 있습니다.

StructuredSerialize
StructuredSerializeForStorage
StructuredDeserialize

주어진 값의 realm 독립적인 스냅샷을 생성하여 무기한 저장할 수 있으며, 나중에 JavaScript 값으로 다시 구현할 수 있고, 이를 여러 번 수행할 수 있습니다.

StructuredSerializeForStorage는 직렬화가 realms 간에 전달되는 대신 영구적으로 저장될 것으로 예상되는 상황에 사용할 수 있습니다. 공유 메모리를 저장하는 것은 의미가 없으므로 SharedArrayBuffer 객체를 직렬화하려고 할 때 예외를 발생시킵니다. 마찬가지로, forStorage 인수가 true일 때 사용자 정의 직렬화 단계를 가진 플랫폼 객체가 주어지면 예외를 발생시키거나 다른 동작을 할 수 있습니다.

history.pushState()history.replaceState()는 작성자 제공 상태 객체에 대해 StructuredSerializeForStorage를 사용하여 직렬화된 상태로 저장하고, 적절한 세션 기록 항목에 저장합니다. 그런 다음 StructuredDeserialize를 사용하여 history.state 속성이 원래 제공된 상태 객체의 복제본을 반환할 수 있도록 합니다.

broadcastChannel.postMessage()는 입력에 대해 StructuredSerialize를 사용한 다음, 결과에 대해 StructuredDeserialize를 여러 번 사용하여 각 대상에 브로드캐스트될 새 복제본을 생성합니다. 여러 대상이 있는 상황에서는 전송이 의미가 없습니다.

JavaScript 값을 파일 시스템에 영구 저장하는 모든 API는 입력에 대해 StructuredSerializeForStorage를 사용하고, 출력에 대해 StructuredDeserialize를 사용합니다.

일반적으로 호출 위치는 JavaScript 값 대신 Web IDL 값을 전달할 수 있습니다. 이는 이러한 알고리즘을 호출하기 전에 JavaScript 값으로 암묵적인 변환을 수행하는 것으로 이해해야 합니다.


작성자 코드가 사용자 에이전트 메서드에 동기적으로 호출되는 결과로 호출되지 않는 호출 위치는 임의의 객체에 대해 StructuredSerialize, StructuredSerializeForStorage, 또는 StructuredSerializeWithTransfer 추상 연산을 호출하기 전에 스크립트를 실행할 준비를 하고 콜백을 실행할 준비를 제대로 해야 합니다. 이는 직렬화 프로세스가 최종 깊은 직렬화 단계의 일부로 작성자 정의 접근자를 호출할 수 있으며, 이러한 접근자는 entryincumbent 개념이 적절히 설정되는 작업에 의존할 수 있기 때문에 필요합니다.

window.postMessage()는 인수에 대해 StructuredSerializeWithTransfer를 수행하지만, 알고리즘의 동기화된 부분 내에서 즉시 수행하여 스크립트를 실행할 준비를 하고 콜백을 실행할 준비를 할 필요 없이 이 알고리즘을 사용할 수 있습니다.

대조적으로, 작성자 제공 객체를 주기적으로 직렬화하기 위해 StructuredSerialize를 사용한 가상 API가 작업(task)에서 직접 이벤트 루프에서 수행되었다면, 적절한 준비를 수행해야 합니다. 현재로서는 플랫폼에 이러한 API가 없으며, 일반적으로 직렬화를 작성자 코드의 동기적 결과로 미리 수행하는 것이 더 간단합니다.

2.7.10 구조화된 클로닝 API

result = self.structuredClone(value[, { transfer }])

입력 값을 받아 구조화된 클론 알고리즘을 수행하여 깊은 복사를 반환합니다. 전송 가능한 객체전송 배열에 나열된 경우, 단순히 복제되는 것이 아니라 전송되어 입력 값에서 더 이상 사용할 수 없게 됩니다.

입력 값의 일부가 직렬화 가능하지 않은 경우 "DataCloneError" DOMException을 발생시킵니다.

structuredClone

모든 현재 엔진에서 지원합니다.

Firefox94+Safari15.4+Chrome98+
Opera?Edge98+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

structuredClone(value, options) 메서드의 단계는 다음과 같습니다:

  1. serialized를 ? StructuredSerializeWithTransfer(value, options["transfer"])로 설정합니다.

  2. deserializeRecord를 ? StructuredDeserializeWithTransfer(serialized, this관련 realm)로 설정합니다.

  3. deserializeRecord.[[Deserialized]]를 반환합니다.

3 HTML 문서의 의미, 구조, 및 API

3.1 문서

HTML UA에서의 모든 XML 및 HTML 문서는 Document 객체로 표현됩니다. [DOM]

Document 객체의 URLDOM에서 정의됩니다. 이는 Document 객체가 생성될 때 초기 설정되지만, Document 객체의 수명 동안 변경될 수 있습니다. 예를 들어, 사용자가 페이지에서 네비게이트하여 프래그먼트로 이동할 때나, pushState() 메서드가 새로운 URL로 호출될 때 변경됩니다. [DOM]

인터랙티브 사용자 에이전트는 일반적으로 사용자 인터페이스에서 Document 객체의 URL을 노출합니다. 이는 사용자가 사이트가 다른 사이트로 가장하려고 하는지 여부를 확인할 수 있는 주요 메커니즘입니다.

Document 객체의 원본(origin)DOM에서 정의되어 있습니다. 이는 Document 객체가 생성될 때 초기 설정되며, document.domain을 설정할 때만 Document의 수명 동안 변경될 수 있습니다. Document원본(origin)URL의 원본(origin)과 다를 수 있습니다. 예를 들어, 하위 내비게이블생성될 때, 해당 활성 문서원본(origin)부모활성 문서원본(origin)을 상속받습니다. 비록 해당 활성 문서URLabout:blank일지라도 그렇습니다. [DOM]

Document스크립트에 의해 createDocument() 또는 createHTMLDocument() 메서드를 사용하여 생성될 때, Document는 즉시 로드 후 작업 준비가 됩니다.

문서의 리퍼러URL을 나타내는 문자열로서, Document가 생성될 때 설정될 수 있습니다. 명시적으로 설정되지 않은 경우, 그 값은 빈 문자열입니다.

3.1.1 Document 객체

Document

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera3+ Edge79+
Edge (Legacy)12+ Internet Explorer4+
Firefox Android? Safari iOS? Chrome Android? WebView Android37+ Samsung Internet? Opera Android10.1+

DOMDocument 인터페이스를 정의하며, 이 사양은 이를 상당히 확장합니다.

enum DocumentReadyState { "loading", "interactive", "complete" };
enum DocumentVisibilityState { "visible", "hidden" };
typedef (HTMLScriptElement or SVGScriptElement) HTMLOrSVGScriptElement;

[LegacyOverrideBuiltIns]
partial interface Document {
  static Document parseHTMLUnsafe((TrustedHTML or DOMString) html);

  // resource metadata management
  [PutForwards=href, LegacyUnforgeable] readonly attribute Location? location;
  attribute USVString domain;
  readonly attribute USVString referrer;
  attribute USVString cookie;
  readonly attribute DOMString lastModified;
  readonly attribute DocumentReadyState readyState;

  // DOM tree accessors
  getter object (DOMString name);
  [CEReactions] attribute DOMString title;
  [CEReactions] attribute DOMString dir;
  [CEReactions] attribute HTMLElement? body;
  readonly attribute HTMLHeadElement? head;
  [SameObject] readonly attribute HTMLCollection images;
  [SameObject] readonly attribute HTMLCollection embeds;
  [SameObject] readonly attribute HTMLCollection plugins;
  [SameObject] readonly attribute HTMLCollection links;
  [SameObject] readonly attribute HTMLCollection forms;
  [SameObject] readonly attribute HTMLCollection scripts;
  NodeList getElementsByName(DOMString elementName);
  readonly attribute HTMLOrSVGScriptElement? currentScript; // classic scripts in a document tree only

  // dynamic markup insertion
  [CEReactions] Document open(optional DOMString unused1, optional DOMString unused2); // both arguments are ignored
  WindowProxy? open(USVString url, DOMString name, DOMString features);
  [CEReactions] undefined close();
  [CEReactions] undefined write((TrustedHTML or DOMString)... text);
  [CEReactions] undefined writeln((TrustedHTML or DOMString)... text);

  // user interaction
  readonly attribute WindowProxy? defaultView;
  boolean hasFocus();
  [CEReactions] attribute DOMString designMode;
  [CEReactions] boolean execCommand(DOMString commandId, optional boolean showUI = false, optional DOMString value = "");
  boolean queryCommandEnabled(DOMString commandId);
  boolean queryCommandIndeterm(DOMString commandId);
  boolean queryCommandState(DOMString commandId);
  boolean queryCommandSupported(DOMString commandId);
  DOMString queryCommandValue(DOMString commandId);
  readonly attribute boolean hidden;
  readonly attribute DocumentVisibilityState visibilityState;

  // special event handler IDL attributes that only apply to Document objects
  [LegacyLenientThis] attribute EventHandler onreadystatechange;
  attribute EventHandler onvisibilitychange;

  // also has obsolete members
};
Document includes GlobalEventHandlers;

Document에는 정책 컨테이너(정책 컨테이너)가 있으며, 초기 상태는 새로운 정책 컨테이너로, Document에 적용되는 정책들을 포함합니다.

Document에는 권한 정책이 있으며, 이는 초기에는 비어 있는 권한 정책입니다.

Document에는 모듈 맵이 있으며, 이는 초기에는 비어 있는 모듈 맵입니다.

Document에는 교차 출처 열기 정책이 있으며, 초기에는 새로운 교차 출처 열기 정책인 교차 출처 열기 정책입니다.

Document에는 초기 about:blank 여부라는 불리언 값이 있으며, 초기 값은 false입니다.

Document에는 WebDriver BiDi용 로딩 중 탐색 ID가 있으며, 이는 초기에는 null인 탐색 ID 또는 null입니다.

이 이름이 나타내듯, 이는 WebDriver BiDi 사양과 인터페이스하기 위해 사용되며, 이 사양은 Document의 생명 주기 초기에 발생하는 특정 사건에 대해 원래 탐색을 생성한 탐색 ID와 연관된 정보를 필요로 합니다. WebDriver BiDi가 로딩 프로세스가 완료되었다고 간주하면 이 값은 다시 null로 설정됩니다. [BIDI]

Document에는 about 기본 URL이 있으며, 이는 초기에는 null인 URL 또는 null입니다.

이 값은 "about:" 스킴이 있는 Document에만 채워집니다.

Document에는 DOM 변경 이벤트 플래그가 있으며, 초기 값은 true인 불리언 값입니다.

이 플래그는 일반적으로 발생하는 DOM 변경 이벤트의 발생을 억제하기 위한 것입니다. 변경 이벤트를 설명하는 사양은 적극적으로 유지 관리되지 않으므로 이 플래그를 고려하지 않지만, 구현체는 이 플래그가 있는 것처럼 작동해야 합니다. [UIEVENTS]

Document에는 bfcache 차단 세부 정보가 있으며, 이는 초기에는 비어 있는 순서가 지정된 집합복원되지 않은 이유의 세부 정보입니다.

3.1.2 DocumentOrShadowRoot 인터페이스

DOM은 이 사양이 확장하는 DocumentOrShadowRoot 믹스인을 정의합니다.

partial interface mixin DocumentOrShadowRoot {
  readonly attribute Element? activeElement;
};

3.1.3 리소스 메타데이터 관리

document.referrer

Document/referrer

모든 최신 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

사용자가 이 문서로 이동한 출발지 문서의 URL을 반환합니다. 다만, 차단되었거나 그런 문서가 없었던 경우에는 빈 문자열을 반환합니다.

noreferrer 링크 유형을 사용하여 참조자를 차단할 수 있습니다.

referrer 속성은 문서의 참조자를 반환해야 합니다.


document.cookie [ = value ]

document에 적용되는 HTTP 쿠키를 반환합니다. 쿠키가 없거나 이 리소스에 쿠키를 적용할 수 없는 경우 빈 문자열이 반환됩니다.

새 쿠키를 추가하기 위해 설정할 수 있습니다.

내용이 iframesandbox 속성을 사용하여 불투명한 출처로 샌드박스화된 경우 "SecurityError" DOMException이 발생합니다.

Document/cookie

모든 최신 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

cookie 속성은 문서의 URL로 식별된 리소스의 쿠키를 나타냅니다.

다음 조건 중 하나에 해당하는 document 객체는 쿠키 비호환 문서 객체입니다:

(이것은 추적 벡터입니다.) 가져올 때, 문서가 쿠키 비호환 문서 객체이면 사용자 에이전트는 빈 문자열을 반환해야 합니다. 그렇지 않은 경우 문서의 기원불투명한 기원이면 사용자 에이전트는 "SecurityError" DOMException을 발생시켜야 합니다. 그렇지 않으면 사용자 에이전트는 문서의 URL에 대한 "비-HTTP" API로 쿠키 문자열을 반환해야 하며, BOM 없이 UTF-8로 디코딩하여 반환해야 합니다. [COOKIES]

설정할 때, 문서가 쿠키 비호환 문서 객체이면 사용자 에이전트는 아무것도 하지 않아야 합니다. 그렇지 않은 경우 문서의 기원불투명한 기원이면 사용자 에이전트는 "SecurityError" DOMException을 발생시켜야 합니다. 그렇지 않으면 사용자 에이전트는 새 값을 포함하여 문서의 URL에 대해 "비-HTTP" API로 UTF-8로 인코딩된 set-cookie 문자열을 수신할 때처럼 작동해야 합니다. [COOKIES] [ENCODING]

cookie 속성은 프레임 간 접근 가능하므로, 쿠키에 대한 경로 제한은 사이트의 어떤 부분에 쿠키를 전송할지 관리하기 위한 도구일 뿐, 보안 기능은 아닙니다.

cookie 속성의 getter와 setter는 공유 상태에 동기적으로 접근합니다. 잠금 메커니즘이 없기 때문에, 멀티프로세스 사용자 에이전트의 다른 탐색 맥락은 스크립트가 실행되는 동안 쿠키를 수정할 수 있습니다. 예를 들어, 사이트가 쿠키를 읽고 값을 증가시킨 다음 다시 기록하여 쿠키의 새 값을 세션의 고유 식별자로 사용하는 경우, 동일한 "고유" 식별자를 두 개의 다른 브라우저 창에서 동시에 두 번 사용할 수 있으며, 이는 잠재적으로 치명적인 영향을 미칠 수 있습니다.


document.lastModified

Document/lastModified

모든 최신 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

서버에서 보고한 대로 사용자의 로컬 시간대로 "MM/DD/YYYY hh:mm:ss" 형식으로 문서의 마지막 수정 날짜를 반환합니다.

마지막 수정 날짜를 알 수 없는 경우 현재 시간이 대신 반환됩니다.

lastModified 속성은 사용자의 로컬 시간대로 document 소스 파일의 마지막 수정 날짜와 시간을 반환해야 합니다. 반환 형식은 다음과 같습니다:

  1. 날짜의 월 구성 요소.

  2. U+002F SOLIDUS 문자 (/).

  3. 날짜의 일 구성 요소.

  4. U+002F SOLIDUS 문자 (/).

  5. 날짜의 년 구성 요소.

  6. U+0020 SPACE 문자.

  7. 시간의 시 구성 요소.

  8. U+003A COLON 문자 (:).

  9. 시간의 분 구성 요소.

  10. U+003A COLON 문자 (:).

  11. 시간의 초 구성 요소.

위의 모든 숫자 구성 요소는 년도를 제외하고는 필요할 경우 0으로 패딩하여 두 자리의 ASCII 숫자로 주어져야 합니다. 년도는 필요할 경우 0으로 패딩된 네 자리 이상의 ASCII 숫자로 주어져야 합니다.

document 소스 파일의 마지막 수정 날짜와 시간은 사용된 네트워킹 프로토콜의 관련 기능에서 파생되어야 합니다. 예를 들어, 문서의 HTTP `Last-Modified` 헤더의 값 또는 로컬 파일의 파일 시스템 메타데이터에서 파생될 수 있습니다. 마지막 수정 날짜와 시간을 알 수 없는 경우 이 속성은 위의 형식으로 현재 날짜와 시간을 반환해야 합니다.

3.1.4 문서 로딩 상태 보고

document.readyState

document가 로딩 중일 때는 "loading"을 반환하고, 파싱이 완료되었지만 하위 리소스를 여전히 로딩 중일 때는 "interactive"을 반환하며, 로딩이 완료되면 "complete"을 반환합니다.

이 값이 변경되면 readystatechange 이벤트가 document 객체에서 발생합니다.

DOMContentLoaded 이벤트는 "interactive"로 전환된 후, "complete"로 전환되기 전에 모든 async 스크립트 요소를 제외한 모든 하위 리소스가 로드된 시점에 발생합니다.

Document/readyState

모든 최신 엔진에서 지원됨.

Firefox3.6+Safari1+Chrome1+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

document는 초기값이 "complete"인 현재 문서 준비 상태를 가집니다.

Document 객체는 Document 객체 생성 및 초기화 알고리즘에 의해 생성된 경우, document.readyState 값이 스크립트에 의해 관찰되기 전에 즉시 "loading"으로 재설정됩니다. 이 기본 동작은 초기 about:blank Document 또는 탐색 컨텍스트가 없는 Document의 경우에도 적용됩니다.

readyState getter는 현재 문서 준비 상태를 반환해야 합니다.

document현재 문서 준비 상태 업데이트준비 상태 값으로 수행하려면:

  1. 만약 document현재 문서 준비 상태준비 상태 값과 같다면 반환합니다.

  2. document현재 문서 준비 상태준비 상태 값으로 설정합니다.

  3. documentHTML 파서와 연결되어 있다면:

    1. now현재 고해상도 시간으로 설정하며, document관련 글로벌 객체를 기준으로 합니다.

    2. 만약 준비 상태 값이 "complete"이고 document로드 타이밍 정보DOM 완료 시간이 0이라면, document로드 타이밍 정보DOM 완료 시간now로 설정합니다.

    3. 그렇지 않고 준비 상태 값이 "interactive"이고 document로드 타이밍 정보DOM 상호작용 시간이 0이라면, document로드 타이밍 정보DOM 상호작용 시간now로 설정합니다.

  4. 이벤트document에 대해 readystatechange 이름으로 발생시킵니다.


documentHTML 파서 또는 XML 파서와 연결되어 있으며, 아직 중지 또는 중단되지 않은 경우 활성 파서를 가지고 있다고 합니다.


document문서 로드 타이밍 정보라는 로드 타이밍 정보를 가지고 있습니다.

document문서 언로드 타이밍 정보라는 이전 문서 언로드 타이밍을 가지고 있습니다.

document크로스 오리진 리디렉션을 통해 생성됨이라는 부울 값을 가지며, 초기값은 false입니다.

문서 로드 타이밍 정보 구조체에는 다음과 같은 항목이 있습니다:

네비게이션 시작 시간 (기본값 0)
숫자
DOM 상호작용 시간 (기본값 0)
DOM 콘텐츠 로드 이벤트 시작 시간 (기본값 0)
DOM 콘텐츠 로드 이벤트 종료 시간 (기본값 0)
DOM 완료 시간 (기본값 0)
로드 이벤트 시작 시간 (기본값 0)
로드 이벤트 종료 시간 (기본값 0)
DOMHighResTimeStamp 값들

문서 언로드 타이밍 정보 구조체에는 다음과 같은 항목이 있습니다:

언로드 이벤트 시작 시간 (기본값 0)
언로드 이벤트 종료 시간 (기본값 0)
DOMHighResTimeStamp 값들

3.1.5 렌더링 차단 메커니즘

document렌더링 차단 요소 집합을 가지며, 이는 초기에는 비어 있는 집합입니다.

document document렌더링 차단 요소 추가를 허용하며, document콘텐츠 유형이 "text/html"이고, documentbody 요소가 null인 경우에 해당합니다.

document document는 다음 두 조건이 모두 참일 때 렌더링 차단 상태가 됩니다:

요소 elel노드 문서 document렌더링 차단 상태이며, eldocument렌더링 차단 요소 집합에 포함되어 있을 때 렌더링 차단 요소로 간주됩니다.

요소 el에 대해 렌더링 차단을 수행하려면:

  1. el노드 문서document로 설정합니다.

  2. 만약 document렌더링 차단 요소 추가를 허용한다면, append를 사용하여 eldocument렌더링 차단 요소 집합에 추가합니다.

요소 el에 대해 렌더링 차단 해제를 수행하려면:

  1. el노드 문서document로 설정합니다.

  2. 제거를 사용하여 eldocument렌더링 차단 요소 집합에서 제거합니다.

렌더링 차단 요소 el탐색 컨텍스트에서 분리되거나, el차단 속성의 값이 변경되어 el이 더 이상 잠재적 렌더링 차단 요소가 아닌 경우, 렌더링 차단을 해제해야 합니다.

3.1.6 DOM 트리 접근자

문서의 html 요소는 해당 문서의 문서 요소이며, html 요소일 경우에 해당하며, 그렇지 않으면 null입니다.


document.head

Document/head

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome4+
Opera11+Edge79+
Edge (레거시)12+Internet Explorer9+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

head 요소를 반환합니다.

문서의 head 요소html 요소의 자식인 첫 번째 head 요소이며, 그렇지 않으면 null입니다.

head 속성은, 가져올 때 문서의 head 요소를 반환해야 합니다 (head 요소 또는 null).


document.title [ = value ]

HTML에서는 title 요소에 의해, SVG에서는 SVG title 요소에 의해 문서의 제목이 반환됩니다.

설정할 때, 문서의 제목을 업데이트합니다. 적절한 요소가 없는 경우 새 값은 무시됩니다.

문서의 title 요소는 문서 내의 첫 번째 title 요소입니다 (트리 순서로), 그렇지 않으면 null입니다.

Document/title

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

다음 알고리즘을 실행할 때 title 속성은 반환되어야 합니다:

  1. 만약 문서 요소SVG svg 요소라면, value첫 번째 자식 텍스트 내용으로 설정합니다.

  2. 그 외의 경우, valuetitle 요소자식 텍스트 내용으로 설정하거나, title 요소가 null이면 빈 문자열로 설정합니다.

  3. ASCII 공백을 제거하고 축소한 다음 value를 반환합니다.

설정할 때, 다음 목록에서 첫 번째 일치 조건에 해당하는 단계를 실행해야 합니다:

만약 문서 요소SVG svg 요소라면
  1. 만약 SVG title 요소가 문서 요소의 자식으로 존재하면, element를 그 요소로 설정합니다.

  2. 그렇지 않은 경우:

    1. element요소를 생성하여 문서 요소노드 문서로 설정하고, titleSVG 네임스페이스를 사용합니다.

    2. element첫 번째 자식으로 문서 요소에 삽입합니다.

  3. 문자열을 전체 대체하여 주어진 값으로 element 내에서 바꿉니다.

만약 문서 요소HTML 네임스페이스 내에 있다면
  1. title 요소가 null이고 head 요소가 null이면 반환합니다.

  2. title 요소가 null이 아니면, elementtitle 요소로 설정합니다.

  3. 그렇지 않은 경우:

    1. element요소를 생성하여 문서 요소노드 문서로 설정하고, titleHTML 네임스페이스를 사용합니다.

    2. element를 head 요소에 추가합니다.

  4. 문자열을 전체 대체하여 주어진 값으로 element 내에서 바꿉니다.

그 외의 경우

아무 것도 하지 않습니다.


document.body [ = value ]

Document/body

모든 최신 엔진에서 지원됩니다.

Firefox60+Safari1+Chrome1+
Opera9.6+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

body 요소를 반환합니다.

새 값을 설정하여 body 요소를 교체할 수 있습니다.

새로운 값이 body 또는 frameset 요소가 아닌 경우, 이는 "HierarchyRequestError" DOMException을 발생시킵니다.

문서의 body 요소html 요소의 자식 중 첫 번째 body 요소 또는 frameset 요소이며, 그런 요소가 없다면 null입니다.

body 속성은 가져올 때 문서의 body 요소를 반환해야 하며 (이는 body 요소, frameset 요소 또는 null일 수 있음), 설정 시에는 다음 알고리즘을 실행해야 합니다:

  1. 새로운 값이 body 또는 frameset 요소가 아닌 경우, "HierarchyRequestError" DOMException을 발생시킵니다.
  2. 그렇지 않은 경우, 새로운 값이 body 요소와 동일하다면, 반환합니다.
  3. 그렇지 않다면, body 요소가 null이 아니면, 새로운 값으로 교체하고, body 요소의 부모 내에서 새로운 값을 설정하고 반환합니다.
  4. 그렇지 않다면, 문서 요소가 없는 경우, "HierarchyRequestError" DOMException을 발생시킵니다.
  5. 그렇지 않다면, body 요소가 null이지만, 문서 요소가 있는 경우, 새로운 값을 문서 요소에 추가합니다.

body getter에 의해 반환된 값이 setter에 전달된 값과 항상 일치하는 것은 아닙니다.

이 예제에서, setter는 body 요소를 성공적으로 삽입합니다 (그러나 이는 비표준으로, SVG에서는 SVG svg 요소의 자식으로 body 요소를 허용하지 않음). 그러나 getter는 문서 요소가 html이 아니기 때문에 null을 반환합니다.

<svg xmlns="http://www.w3.org/2000/svg">
 <script>
  document.body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
  console.assert(document.body === null);
 </script>
</svg>

document.images

Document/images

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLCollection을 반환하며, 이는 documentimg 요소를 포함합니다.

document.embeds

Document/embeds

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari10.1+Chrome64+
Opera51+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

HTMLCollection을 반환하며, 이는 documentembed 요소를 포함합니다.

document.plugins

Document/plugins

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari10.1+Chrome64+
Opera51+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS10.3+Chrome Android?WebView Android?Samsung Internet?Opera Android47+

HTMLCollection을 반환하며, 이는 documentaarea 요소 중 href 속성이 있는 요소를 포함합니다.

document.forms

Document/forms

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLCollection을 반환하며, 이는 documentform 요소를 포함합니다.

document.scripts

Document/scripts

모든 최신 엔진에서 지원됩니다.

Firefox9+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLCollection을 반환하며, 이는 documentscript 요소를 포함합니다.

images 속성은 HTMLCollection을 반환해야 하며, document 노드에서 루팅되고 필터는 img 요소만 일치해야 합니다.

embeds 속성은 HTMLCollection을 반환해야 하며, document 노드에서 루팅되고 필터는 embed 요소만 일치해야 합니다.

plugins 속성은 embeds 속성이 반환하는 것과 동일한 객체를 반환해야 합니다.

links 속성은 HTMLCollection을 반환해야 하며, document 노드에서 루팅되고 필터는 a 요소 중 href 속성이 있는 요소 및 area 요소 중 href 속성이 있는 요소만 일치해야 합니다.

forms 속성은 HTMLCollection을 반환해야 하며, document 노드에서 루팅되고 필터는 form 요소만 일치해야 합니다.

scripts 속성은 HTMLCollection을 반환해야 하며, document 노드에서 루팅되고 필터는 script 요소만 일치해야 합니다.


collection = document.getElementsByName(name)

Document/getElementsByName

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera5+Edge79+
Edge (레거시)12+Internet Explorer5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

NodeList를 반환하며, 이는 document에서 name 속성 값을 가진 요소들을 포함합니다.

getElementsByName(elementName) 메서드 단계는 다음과 같이 live NodeList를 반환합니다. 이 컬렉션은 document에서 elementName 인수와 동일한 값을 가진 name 속성이 있는 모든 HTML 요소를 포함하며, 트리 순서에 따라 정렬됩니다. 동일한 인수를 사용하여 메서드가 다시 호출될 경우, 사용자 에이전트는 이전 호출에서 반환된 것과 동일한 객체를 반환할 수 있습니다. 다른 경우에는 새로운 NodeList 객체를 반환해야 합니다.


document.currentScript

Document/currentScript

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari8+Chrome29+
Opera?Edge79+
Edge (레거시)12+Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 실행 중인 script 요소 또는 SVG script 요소를 반환합니다. 이 요소가 클래식 스크립트를 나타내는 경우에만 해당됩니다. 재진입 스크립트 실행의 경우, 아직 실행이 완료되지 않은 스크립트 중 가장 최근에 시작된 스크립트를 반환합니다.

현재 document에서 스크립트 또는 SVG 스크립트 요소가 실행 중이 아니거나, 현재 실행 중인 스크립트 또는 SVG 스크립트 요소가 모듈 스크립트를 나타내는 경우 null을 반환합니다.

currentScript 속성은 가장 최근에 설정된 값을 반환해야 합니다. document가 생성될 때, currentScript는 null로 초기화되어야 합니다.

이 API는 스크립트 또는 SVG 스크립트 요소를 전역적으로 노출하므로, 구현자 및 표준 커뮤니티에서 더 이상 선호되지 않습니다. 따라서, 모듈 스크립트 실행 시나 섀도우 트리 내에서 스크립트를 실행할 때는 사용할 수 없습니다. 이러한 컨텍스트에서 실행 중인 스크립트를 식별하기 위한 새로운 솔루션을 찾고 있습니다. 이는 전역적으로 노출되지 않으며, 이슈 #1013를 참조하십시오.


Document 인터페이스는 이름 있는 속성을 지원합니다. document 객체 document지원되는 속성 이름은 특정 시점에서 다음과 같으며, 요소가 기여한 순서에 따라 트리 순서에 따라 정렬되고, 나중에 중복된 값은 무시되며, 동일한 요소가 id 속성에서 나오는 값이 name 속성에서 나오는 값보다 먼저 나타납니다:

이름 있는 속성의 값을 결정하기 위해 namedocument 객체에서 반환하기 위해 사용자는 다음 단계를 사용하여 얻은 값을 반환해야 합니다:

  1. elements라는 목록을 정의합니다. 이 목록에는 name이라는 이름을 가진 이름 있는 요소가 포함되며, 이 요소들은 document를 루트로 가진 루트와 함께 문서 트리에 있습니다.

    이 알고리즘이 Web IDL에 의해 호출되지 않는다면, 이러한 요소는 하나 이상 존재하지 않습니다.

  2. 만약 elements에 단 하나의 요소가 있으며, 해당 요소가 iframe 요소이고, 그 iframe 요소의 콘텐츠 네비게이팅 가능 항목이 null이 아닌 경우, 요소의 콘텐츠 네비게이팅 가능활성 WindowProxy를 반환합니다.

  3. 그렇지 않고 elements에 단 하나의 요소가 있는 경우, 그 요소를 반환합니다.

  4. 그 외의 경우, 루트가 document 노드인 HTMLCollection을 반환하며, 필터는 name과 일치하는 이름 있는 요소만 일치합니다.

name을 가진 이름 있는 요소는 위 알고리즘의 목적에 따라 다음 중 하나에 해당하는 요소입니다:

embed 또는 object 요소는 상위에 노출된 object 조상이 없고, object 요소의 경우 대체 콘텐츠를 표시하지 않거나 object 또는 embed 하위 요소가 없을 때 노출된 것으로 간주됩니다.


dir 속성은 Document 인터페이스에 dir 콘텐츠 속성과 함께 정의됩니다.

3.2 요소

3.2.1 의미

HTML의 요소, 속성 및 속성 값은 특정 의미(시맨틱)를 가지도록 정의되어 있습니다(이 명세서에 의해). 예를 들어, ol 요소는 순서가 있는 목록을 나타내며, lang 속성은 콘텐츠의 언어를 나타냅니다.

이러한 정의는 웹 브라우저나 검색 엔진과 같은 HTML 프로세서가 저자가 고려하지 않았을 수도 있는 다양한 맥락에서 문서와 애플리케이션을 표시하고 사용할 수 있도록 합니다.

간단한 예로, 데스크탑 웹 브라우저만을 고려하여 작성된 웹 페이지를 생각해 보십시오:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>My Page</title>
 </head>
 <body>
  <h1>Welcome to my page</h1>
  <p>I like cars and lorries and have a big Jeep!</p>
  <h2>Where I live</h2>
  <p>I live in a small hut on a mountain!</p>
 </body>
</html>

HTML이 의미를 전달하기 때문에 프레젠테이션이 아닌 동일한 페이지는 모바일 폰의 작은 브라우저에서도 변경 없이 사용할 수 있습니다. 예를 들어, 데스크탑에서처럼 헤딩이 큰 글자로 표시되는 대신, 모바일 폰의 브라우저는 페이지 전체에 동일한 크기의 텍스트를 사용하지만 헤딩은 굵게 표시할 수 있습니다.

하지만 이는 화면 크기의 차이만을 의미하지 않습니다. 동일한 페이지는 음성 합성 기반 브라우저를 사용하는 시각 장애 사용자에게도 사용할 수 있습니다. 이 경우 페이지는 화면에 표시되는 대신 사용자의 이어폰을 통해 음성으로 읽어줍니다. 헤딩이 큰 글자로 표시되는 대신, 음성 브라우저는 다른 음량이나 더 느린 목소리를 사용할 수 있습니다.

그것뿐만이 아닙니다. 브라우저가 페이지의 어느 부분이 헤딩인지 알고 있기 때문에, 사용자가 문서 내에서 빠르게 탐색할 수 있도록 문서 개요를 생성할 수 있습니다. "다음 헤딩으로 이동" 또는 "이전 헤딩으로 이동"과 같은 키를 사용하여 쉽게 탐색할 수 있는 기능은 특히 음성 브라우저에서 매우 유용하며, 그렇지 않으면 사용자가 페이지를 빠르게 탐색하기 어렵습니다.

브라우저를 넘어서는 소프트웨어도 이 정보를 활용할 수 있습니다. 검색 엔진은 헤딩을 사용하여 페이지를 더 효과적으로 인덱싱하거나 검색 결과에서 페이지의 하위 섹션으로 빠르게 이동할 수 있는 링크를 제공할 수 있습니다. 도구는 이 헤딩을 사용하여 목차를 생성할 수 있으며, 이 명세서의 목차도 이러한 방식으로 생성됩니다.

이 예시는 헤딩에 집중했지만, HTML의 모든 시맨틱에도 동일한 원칙이 적용됩니다.

저자는 요소, 속성 또는 속성 값을 그들이 의도된 시맨틱 목적 외의 용도로 사용해서는 안 됩니다. 그렇게 하면 소프트웨어가 페이지를 올바르게 처리하는 것을 방해합니다.

예를 들어, 다음 코드 조각은 기업 사이트의 헤딩을 나타내기 위해 작성된 것으로, 두 번째 줄이 하위 섹션의 헤딩이 아니라 단순히 부제목이므로 비표준적입니다(같은 섹션의 보조 헤딩).

<body>
<h1>ACME Corporation</h1>
<h2>The leaders in arbitrary fast delivery since 1920</h2>
...

hgroup 요소는 이러한 상황에 사용할 수 있습니다:

<body>
<hgroup>
<h1>ACME Corporation</h1>
<p>The leaders in arbitrary fast delivery since 1920</p>
</hgroup>
...

다음 예시의 문서도 구문상 올바르더라도 표 형식의 데이터가 명확히 아닌 데이터를 셀에 배치했기 때문에 유사하게 비표준적이며, cite 요소가 잘못 사용되었습니다:

<!DOCTYPE HTML>
<html lang="en-GB">
 <head> <title> Demonstration </title> </head>
 <body>
  <table>
   <tr> <td> My favourite animal is the cat. </td> </tr>
   <tr>
    <td><a href="https://example.org/~ernest/"><cite>Ernest</cite></a>,
     in an essay from 1992
    </td>
   </tr>
  </table>
 </body>
</html>

이렇게 하면 이러한 시맨틱에 의존하는 소프트웨어가 실패할 수 있습니다. 예를 들어, 시각 장애 사용자가 문서의 표를 탐색할 수 있도록 하는 음성 브라우저는 위 인용문을 표로 보고하여 사용자를 혼란스럽게 할 수 있으며, 페이지에서 작업 제목을 추출하는 도구는 "Ernest"를 작업 제목으로 잘못 추출할 수 있습니다. 실제로 이는 사람의 이름일 뿐 제목이 아닙니다.

이 문서의 수정된 버전은 다음과 같을 수 있습니다:

<!DOCTYPE HTML>
<html lang="en-GB">
 <head> <title> Demonstration </title> </head>
 <body>
  <blockquote>
   <p> My favourite animal is the cat. </p>
  </blockquote>
  <p><a href="https://example.org/~ernest/">Ernest</a>,
   in an essay from 1992
  </p>
 </body>
</html>

저자는 이 명세서 또는 다른 적용 가능한 명세서에 의해 허용되지 않은 요소, 속성 또는 속성 값을 사용해서는 안 됩니다. 그렇게 하면 언어를 미래에 확장하는 것이 상당히 어려워집니다.

다음 예시에서는 비표준 속성 값("carpet")과 이 명세서에서 허용되지 않는 비표준 속성("texture")이 있습니다:

<label>Carpet: <input type="carpet" name="c" texture="deep pile"></label>

다음은 이를 수정한 올바른 마크업입니다:

<label>Carpet: <input type="text" class="carpet" name="c" data-texture="deep pile"></label>

DOM 노드의 노드 문서브라우징 컨텍스트가 null인 경우, 문서 적합성 요구 사항에서 HTML 구문 요구 사항 및 XML 구문 요구 사항을 제외한 모든 문서 적합성 요구 사항에서 면제됩니다.

특히, template 요소의 템플릿 내용노드 문서브라우징 컨텍스트는 null입니다. 예를 들어, 콘텐츠 모델 요구 사항과 속성 값 마이크로 구문 요구 사항은 template 요소의 템플릿 내용에 적용되지 않습니다. 이 예시에서 img 요소는 template 요소 외부에서는 유효하지 않은 플레이스홀더 값을 가지고 있습니다.

<template>
 <article>
  <img src="{{src}}" alt="{{alt}}">
  <h1></h1>
 </article>
</template>

그러나 위의 마크업에서 </h1> 종료 태그를 생략하면 HTML 구문을 위반한 것이 되며, 적합성 검사 도구에서 오류로 플래그를 지정합니다.

스크립팅 및 기타 메커니즘을 통해 속성 값, 텍스트 및 문서의 전체 구조가 사용자 에이전트가 처리하는 동안 동적으로 변경될 수 있습니다. 특정 시점에서 문서의 의미는 그 시점에서 문서의 상태에 의해 표현되며, 따라서 문서의 의미는 시간이 지남에 따라 변경될 수 있습니다. 사용자 에이전트는 이러한 변화가 발생할 때마다 문서의 프레젠테이션을 업데이트해야 합니다.

HTML에는 진행 바를 설명하는 progress 요소가 있습니다. 이 요소의 "value" 속성이 스크립트에 의해 동적으로 업데이트되면 사용자 에이전트는 렌더링을 업데이트하여 진행 상황이 변경되는 것을 표시합니다.

3.2.2 DOM의 요소

DOM에서 HTML 요소를 나타내는 노드는 이 명세서의 관련 섹션에 나열된 인터페이스를 구현하고 스크립트에 노출해야 합니다. 여기에는 HTML 요소가 포함되며, XML 문서에서도, 이 문서들이 다른 컨텍스트에 있을 때 (예: XSLT 변환 내)도 마찬가지입니다.

DOM의 요소는 무언가를 나타냅니다. 즉, 요소는 내재적인 의미를 가지며, 이는 시맨틱스라고도 불립니다.

예를 들어, ol 요소는 순서가 있는 목록을 나타냅니다.

요소는 명시적이거나 암시적인 방식으로 참조될 수 있습니다. DOM의 요소가 명시적으로 참조될 수 있는 한 가지 방법은 요소에 id 속성을 부여한 다음, 해당 id 속성 값을 프래그먼트로 사용하는 하이퍼링크를 생성하는 것입니다. 그러나 참조를 위해 하이퍼링크가 반드시 필요한 것은 아닙니다. 해당 요소를 참조하는 어떤 방식도 충분합니다.

다음 figure 요소를 고려해보세요. 이 요소에는 id 속성이 부여되어 있습니다:

<figure id="module-script-graph">
          <img src="module-script-graph.svg"
               alt="Module A depends on module B, which depends
                    on modules C and D.">
          <figcaption>Figure 27: a simple module graph</figcaption>
        </figure>

하이퍼링크 기반 참조a 요소를 사용하여 다음과 같이 생성될 수 있습니다:

As we can see in <a href="#module-script-graph">figure 27</a>, ...

그러나, figure 요소를 참조하는 다른 방법들도 많이 있습니다. 예를 들어:

모든 HTML 요소의 인터페이스가 상속받아야 하는 기본 인터페이스는 HTMLElement 인터페이스이며, 추가 요구 사항이 없는 요소들은 이 인터페이스를 사용해야 합니다.

HTMLElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android1+Samsung Internet?Opera Android10.1+

HTMLUnknownElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari6+Chrome15+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface HTMLElement : Element {
  [HTMLConstructor] constructor();

  // metadata attributes
  [CEReactions] attribute DOMString title;
  [CEReactions] attribute DOMString lang;
  [CEReactions] attribute boolean translate;
  [CEReactions] attribute DOMString dir;

  // user interaction
  [CEReactions] attribute (boolean or unrestricted double or DOMString)? hidden;
  [CEReactions] attribute boolean inert;
  undefined click();
  [CEReactions] attribute DOMString accessKey;
  readonly attribute DOMString accessKeyLabel;
  [CEReactions] attribute boolean draggable;
  [CEReactions] attribute boolean spellcheck;
  [CEReactions] attribute DOMString writingSuggestions;
  [CEReactions] attribute DOMString autocapitalize;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString innerText;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString outerText;

  ElementInternals attachInternals();

  // The popover API
  undefined showPopover();
  undefined hidePopover();
  boolean togglePopover(optional boolean force);
  [CEReactions] attribute DOMString? popover;
};

HTMLElement includes GlobalEventHandlers;
HTMLElement includes ElementContentEditable;
HTMLElement includes HTMLOrSVGElement;

[Exposed=Window]
interface HTMLUnknownElement : HTMLElement {
  // Note: intentionally no [HTMLConstructor]
};

HTMLElement 인터페이스는 여러 가지 다양한 기능과 관련된 메서드 및 속성을 포함하고 있으며, 이 인터페이스의 구성원들은 이 명세서의 여러 다른 섹션에서 설명됩니다.


name을 가진 요소에 대한 요소 인터페이스는 다음과 같이 결정됩니다:

  1. nameapplet, bgsound, blink, isindex, keygen, multicol, nextid, 또는 spacer인 경우, HTMLUnknownElement를 반환합니다.

  2. nameacronym, basefont, big, center, nobr, noembed, noframes, plaintext, rb, rtc, strike, 또는 tt인 경우, HTMLElement를 반환합니다.

  3. namelisting 또는 xmp인 경우, HTMLPreElement를 반환합니다.

  4. 이 명세서가 name에 대응하는 요소 유형에 적합한 인터페이스를 정의한 경우, 해당 인터페이스를 반환합니다.

  5. 다른 관련 명세서name에 적합한 인터페이스를 정의한 경우, 그 인터페이스를 반환합니다.

  6. name유효한 커스텀 요소 이름인 경우, HTMLElement를 반환합니다.

  7. HTMLUnknownElement를 반환합니다.

유효한 커스텀 요소 이름의 경우 HTMLUnknownElement 대신 HTMLElement를 사용하는 이유는, 잠재적인 미래 업그레이드HTMLUnknownElement에서 관련 없는 서브클래스로의 수평적 전환 대신 HTMLElement에서 서브클래스로의 선형 전환만을 초래하도록 보장하기 위해서입니다.

HTML과 SVG 요소가 공유하는 기능들은 HTMLOrSVGElement 인터페이스 믹스인을 사용합니다: [SVG]

interface mixin HTMLOrSVGElement {
  [SameObject] readonly attribute DOMStringMap dataset;
  attribute DOMString nonce; // intentionally no [CEReactions]

  [CEReactions] attribute boolean autofocus;
  [CEReactions] attribute long tabIndex;
  undefined focus(optional FocusOptions options = {});
  undefined blur();
};

HTML 또는 SVG 요소가 아닌 요소의 예는 다음과 같이 생성된 요소입니다:

const el = document.createElementNS("some namespace", "example");
console.assert(el.constructor === Element);

3.2.3 HTML 요소 생성자

커스텀 요소 기능을 지원하기 위해, 모든 HTML 요소는 특별한 생성자 동작을 가집니다. 이는 [HTMLConstructor] IDL 확장 속성을 통해 표시됩니다. 이 확장 속성은 주어진 인터페이스 객체가 호출될 때 특정 동작을 가지게 된다는 것을 나타내며, 아래에 자세히 정의되어 있습니다.

[HTMLConstructor] 확장 속성은 인수를 받을 수 없으며, 생성자 작업에서만 나타나야 합니다. 이는 생성자 작업에 단 한 번만 나타나야 하며, 해당 인터페이스는 단일 주석이 달린 생성자 작업만을 포함하고, 그 외에는 아무 것도 포함하지 않아야 합니다. 주석이 달린 생성자 작업은 인수를 받지 않도록 선언되어야 합니다.

[HTMLConstructor] 확장 속성으로 주석이 달린 생성자 작업이 선언된 인터페이스는 다음과 같은 재정의된 생성자 단계를 가집니다:

  1. registry현재 전역 객체CustomElementRegistry 객체로 설정합니다.

  2. NewTarget활성 함수 객체와 동일한 경우, TypeError를 발생시킵니다.

    이러한 상황은 생성자를 요소 인터페이스로 정의한 커스텀 요소를 사용할 때 발생할 수 있습니다:

    customElements.define("bad-1", HTMLButtonElement);
    new HTMLButtonElement(); // (1)
    document.createElement("bad-1"); // (2)

    이 경우, HTMLButtonElement의 실행 중 (1번과 같이 명시적으로 또는 2번과 같이 암시적으로) 활성 함수 객체NewTarget이 모두 HTMLButtonElement이 됩니다. 이 검사가 없으면 로컬 이름이 bad-1HTMLButtonElement 인스턴스를 생성할 수 있게 됩니다.

  3. definitionregistry에서 생성자NewTarget과 동일한 항목으로 설정합니다. 그러한 정의가 없으면 TypeError를 발생시킵니다.

    이는 registry생성자가 정의되지 않은 경우에도 적용되며, 이는 HTML 요소 생성자가 함수로 호출될 때도 발생합니다 (이 경우 NewTarget이 정의되지 않기 때문에).

  4. is value를 null로 설정합니다.

  5. definition로컬 이름definition이름과 동일한 경우 (즉, definition독립 커스텀 요소인 경우), 다음을 수행합니다:

    1. 활성 함수 객체HTMLElement가 아닌 경우, TypeError를 발생시킵니다.

      이러한 상황은 커스텀 요소가 로컬 이름을 확장하지 않지만, HTMLElement 클래스가 아닌 클래스를 상속하는 경우에 발생할 수 있습니다:

      customElements.define("bad-2", class Bad2 extends HTMLParagraphElement {});

      이 경우, Bad2 인스턴스를 생성할 때 발생하는 (암시적인) super() 호출 중에 활성 함수 객체HTMLParagraphElement이며, HTMLElement가 아닙니다.

  6. 그 외의 경우 (즉, definition맞춤형 내장 요소인 경우):

    1. 유효한 로컬 이름을 이 명세서나 다른 관련 명세서에 정의된 로컬 이름 목록으로 설정합니다. 이 목록은 활성 함수 객체요소 인터페이스로 사용하는 요소를 포함합니다.

    2. 유효한 로컬 이름definition로컬 이름이 포함되어 있지 않은 경우, TypeError를 발생시킵니다.

      이 상황은 커스텀 요소가 주어진 로컬 이름을 확장하지만, 잘못된 클래스를 상속하는 경우에 발생할 수 있습니다:

      customElements.define("bad-3", class Bad3 extends HTMLQuoteElement {}, { extends: "p" });

      이 경우, Bad3 인스턴스를 생성할 때 발생하는 (암시적인) super() 호출 중에 유효한 로컬 이름 목록은 qblockquote를 포함하지만, definition로컬 이름은 그 목록에 포함되지 않은 p입니다.

    3. is valuedefinition이름으로 설정합니다.

  7. definition생성 스택이 비어 있는 경우:

    1. 인터페이스를 구현하는 새로운 객체를 내부적으로 생성한 결과를 element로 설정합니다.

    2. element노드 문서현재 전역 객체관련 문서로 설정합니다.

    3. element네임스페이스HTML 네임스페이스로 설정합니다.

    4. element네임스페이스 접두사를 null로 설정합니다.

    5. element로컬 이름definition로컬 이름으로 설정합니다.

    6. element커스텀 요소 상태를 "custom"으로 설정합니다.

    7. element커스텀 요소 정의definition으로 설정합니다.

    8. elementisis value로 설정합니다.

    9. element를 반환합니다.

      이 단계는 저자 스크립트가 예를 들어 new MyCustomElement()와 같이 커스텀 요소를 직접 생성할 때 일반적으로 도달합니다.

  8. prototype을 ? Get(NewTarget, "prototype")으로 설정합니다.

  9. Type(prototype)이 Object가 아닌 경우:

    1. realm을 ? GetFunctionRealm(NewTarget)으로 설정합니다.

    2. prototyperealm의 인터페이스가 활성 함수 객체와 동일한 인터페이스인 인터페이스 프로토타입 객체로 설정합니다.

    활성 함수 객체의 realm이 realm이 아닐 수도 있으므로, 우리는 realms 간에 "동일한 인터페이스"의 일반적인 개념을 사용하고 있습니다. 이는 인터페이스 객체의 동등성을 찾는 것이 아닙니다. 이러한 백업 동작은 인터페이스를 구현하는 새로운 객체를 내부적으로 생성 알고리즘과 일치하도록 설계되었습니다.

  10. elementdefinition생성 스택의 마지막 항목으로 설정합니다.

  11. element이미 생성됨 표시자인 경우, "InvalidStateError" DOMException을 발생시킵니다.

    이러한 상황은 커스텀 요소 생성자 내부에서 저자 코드가 super()를 호출하기 전에 생성 중인 클래스의 또 다른 인스턴스를 생성하는 경우 발생할 수 있습니다:

    let doSillyThing = true;
    
    class DontDoThis extends HTMLElement {
      constructor() {
        if (doSillyThing) {
          doSillyThing = false;
          new DontDoThis();
          // 이제 생성 스택에는 이미 생성된 표시자가 포함됩니다.
        }
    
        // 이로 인해 "InvalidStateError" DOMException이 발생합니다:
        super();
      }
    }

    또한 사용자 코드가 커스텀 요소 생성자 내부에서 super()를 두 번 호출하는 경우에도 발생할 수 있습니다. 이는 JavaScript 명세에 따라 이 알고리즘을 두 번 실행하게 되며, 오류를 발생시키기 전에 수퍼클래스 생성자를 두 번 호출하기 때문입니다:

    class DontDoThisEither extends HTMLElement {
      constructor() {
        super();
    
        // 이것은 오류를 발생시키지만, HTMLElement 생성자에 이미 호출이 들어간 후에 발생합니다.
        super();
      }
    }
  12. ? element.[[SetPrototypeOf]](prototype)를 수행합니다.

  13. definition생성 스택의 마지막 항목을 이미 생성됨 표시자로 교체합니다.

  14. element를 반환합니다.

    이 단계는 일반적으로 업그레이드 중에 기존 요소를 반환하는 경우 도달합니다. 이는 커스텀 요소 생성자 내부에서 super() 호출이 해당 기존 요소를 this로 할당하도록 하기 위함입니다.


[HTMLConstructor]로 암시된 생성자 동작 외에도, 일부 요소는 명명된 생성자(실제로는 수정된 prototype 속성을 가진 팩토리 함수)를 가질 수 있습니다.

HTML 요소에 대한 명명된 생성자는 또한 커스텀 요소 생성자를 정의할 때 extends 절에서도 사용할 수 있습니다:

class AutoEmbiggenedImage extends Image {
  constructor(width, height) {
    super(width * 10, height * 10);
  }
}

customElements.define("auto-embiggened", AutoEmbiggenedImage, { extends: "img" });

const image = new AutoEmbiggenedImage(15, 20);
console.assert(image.width === 150);
console.assert(image.height === 200);

3.2.4 요소 정의

이 명세서의 각 요소는 다음 정보를 포함하는 정의를 가지고 있습니다:

카테고리

요소가 속하는 카테고리 목록입니다. 이 목록은 각 요소의 콘텐츠 모델을 정의할 때 사용됩니다.

이 요소를 사용할 수 있는 맥락

요소를 사용할 수 있는 위치에 대한 비규범적인 설명입니다. 이 정보는 이 요소를 자식으로 허용하는 요소들의 콘텐츠 모델과 중복되며, 단지 편의성을 위해 제공됩니다.

간단하게 하기 위해, 가장 구체적인 기대 사항만 나열됩니다.

예를 들어, 모든 구문 콘텐츠흐름 콘텐츠입니다. 따라서, 구문 콘텐츠는 "구문 콘텐츠가 예상되는 위치"로만 나열되며, 이는 더 구체적인 기대 사항입니다. 흐름 콘텐츠가 예상되는 모든 곳에서도 구문 콘텐츠가 예상되므로, 이 기대를 충족시킵니다.

콘텐츠 모델

요소의 자식 및 후손으로 포함되어야 하는 콘텐츠에 대한 규범적인 설명입니다.

text/html에서 태그 생략

text/html 구문에서 시작 태그를 생략할 수 있는지에 대한 비규범적인 설명입니다. 이 정보는 선택적 태그 섹션에 주어진 규범적인 요구 사항과 중복되며, 요소 정의에 편의성만을 위해 제공됩니다.

콘텐츠 속성

요소에 지정될 수 있는 속성(달리 금지되지 않은 경우) 목록과 그 속성에 대한 비규범적인 설명이 포함된 규범적인 목록입니다. (대시 왼쪽의 콘텐츠는 규범적이며, 오른쪽의 콘텐츠는 비규범적입니다.)

접근성 고려사항

작성자용: ARIA rolearia-* 속성 사용에 대한 적합성 요구 사항은 ARIA in HTML에 정의되어 있습니다. [ARIA] [ARIAHTML]

구현자용: 접근성 API 시맨틱 구현에 대한 사용자 에이전트 요구 사항은 HTML 접근성 API 매핑에 정의되어 있습니다. [HTMLAAM]

DOM 인터페이스

요소가 구현해야 하는 DOM 인터페이스의 규범적인 정의입니다.

이후 요소가 표현하는 내용에 대한 설명과 저자 및 구현에 적용될 수 있는 추가적인 규범적인 적합성 기준이 따라옵니다. 경우에 따라 예제가 포함될 수 있습니다.

3.2.4.1 속성

속성 값은 문자열입니다. 별도로 명시되지 않는 한, HTML 요소의 속성 값은 빈 문자열을 포함한 모든 문자열 값일 수 있으며, 해당 속성 값에 어떤 텍스트가 지정될 수 있는지에 대한 제한은 없습니다.

3.2.5 콘텐츠 모델

이 명세서에서 정의된 각 요소는 콘텐츠 모델을 가지고 있습니다: 요소의 예상 내용물에 대한 설명입니다. HTML 요소는 해당 요소의 콘텐츠 모델에 설명된 요구 사항과 일치하는 내용물을 가져야 합니다. 요소의 내용물은 DOM에서 그 자식들입니다.

ASCII 공백 문자는 항상 요소 사이에 허용됩니다. 사용자 에이전트는 소스 마크업의 요소 사이에 있는 이 문자를 DOM에서 텍스트 노드로 표시합니다. 빈 텍스트 노드 및 이러한 문자들의 시퀀스로만 구성된 텍스트 노드는 요소 간 공백으로 간주됩니다.

요소 간 공백, 주석 노드 및 처리 명령 노드는 요소의 내용물이 그 요소의 콘텐츠 모델과 일치하는지 여부를 결정할 때 무시해야 하며, 문서 및 요소의 시맨틱을 정의하는 알고리즘을 따를 때도 무시해야 합니다.

따라서, 요소 A는 두 번째 요소 B가 같은 부모 노드를 가지며 그들 사이에 다른 요소 노드 또는 텍스트 노드(다만 요소 간 공백은 제외)가 없는 경우 선행되거나 후행된다고 할 수 있습니다. 마찬가지로, 어떤 노드가 그 요소의 유일한 자식인 경우, 그 요소가 요소 간 공백, 주석 노드 및 처리 명령 노드 외에는 다른 노드를 포함하지 않는 경우입니다.

작성자는 HTML 요소를 각 요소에 대해 정의된 대로 명시적으로 허용된 곳 이외에는 사용해서는 안 되며, 다른 명세서에 의해 명시적으로 요구되는 경우를 제외하고는 사용해서는 안 됩니다. XML 복합 문서의 경우, 이러한 맥락은 관련 맥락을 제공하도록 정의된 다른 네임스페이스의 요소 내에 있을 수 있습니다.

Atom Syndication Formatcontent 요소를 정의합니다. 그 type 속성에 xhtml 값이 있을 때, Atom Syndication Format은 해당 요소가 단일 HTML div 요소를 포함하도록 요구합니다. 따라서 이 맥락에서는 div 요소가 허용되며, 이는 이 명세서에 명시적으로 규범적으로 명시된 것은 아닙니다. [ATOM]

또한, HTML 요소는 고아 노드(즉, 부모 노드가 없는 상태)일 수 있습니다.

예를 들어, td 요소를 생성하고 스크립트에서 전역 변수에 저장하는 것은 규범적이며, td 요소가 tr 요소 내에서만 사용되어야 함에도 불구하고 이를 벗어날 수 있습니다.

var data = {
  name: "Banana",
  cell: document.createElement('td'),
};
3.2.5.1 "nothing" 콘텐츠 모델

요소의 콘텐츠 모델이 nothing일 때, 해당 요소는 텍스트 노드( 요소 간 공백 제외) 및 요소 노드를 포함해서는 안 됩니다.

콘텐츠 모델이 "nothing"인 대부분의 HTML 요소는 편의상 빈 요소(종료 태그가 없는 요소)인 경우가 많습니다. 그러나, 이는 완전히 별개의 개념입니다.

3.2.5.2 콘텐츠 종류

HTML의 각 요소는 유사한 특성을 가진 요소들을 함께 그룹화하는 하나 이상의 카테고리에 속합니다. 이 명세서에서는 다음과 같은 광범위한 카테고리를 사용합니다:

일부 요소는 또한 이 명세서의 다른 부분에서 정의된 다른 카테고리에 속할 수 있습니다.

이 카테고리들은 다음과 같이 관련됩니다:

섹셔닝 콘텐츠, 헤딩 콘텐츠, 문장 콘텐츠, 임베디드 콘텐츠 및 인터랙티브 콘텐츠는 모두 흐름 콘텐츠의 유형입니다. 메타데이터는 때때로 흐름 콘텐츠이기도 합니다. 메타데이터와 인터랙티브 콘텐츠는 때때로 문장 콘텐츠이기도 합니다. 임베디드 콘텐츠는 또한 문장 콘텐츠의 한 유형이며, 때때로 인터랙티브 콘텐츠이기도 합니다.

다른 카테고리들은 특정 목적을 위해 사용되며, 예를 들어 폼 컨트롤은 공통 요구 사항을 정의하기 위해 여러 카테고리를 사용하여 지정됩니다. 일부 요소는 고유한 요구 사항을 가지며 특정 카테고리에 맞지 않을 수 있습니다.

3.2.5.2.1 메타데이터 콘텐츠

메타데이터 콘텐츠는 나머지 콘텐츠의 표현이나 동작을 설정하거나, 문서와 다른 문서들 사이의 관계를 설정하거나, 다른 "대역 외" 정보를 전달하는 콘텐츠입니다.

주로 메타데이터와 관련된 의미론을 가진 다른 네임스페이스의 요소들(예: RDF)도 메타데이터 콘텐츠입니다.

따라서, XML 직렬화에서 다음과 같이 RDF를 사용할 수 있습니다:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:r="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xml:lang="en">
 <head>
  <title>Hedral's Home Page</title>
  <r:RDF>
   <Person xmlns="http://www.w3.org/2000/10/swap/pim/contact#"
           r:about="https://hedral.example.com/#">
    <fullName>Cat Hedral</fullName>
    <mailbox r:resource="mailto:hedral@damowmow.com"/>
    <personalTitle>Sir</personalTitle>
   </Person>
  </r:RDF>
 </head>
 <body>
  <h1>My home page</h1>
  <p>I like playing with string, I guess. Sister says squirrels are fun
  too so sometimes I follow her to play with them.</p>
 </body>
</html>

그러나, HTML 직렬화에서는 이것이 불가능합니다.

3.2.5.2.2 플로우 콘텐츠

문서 및 애플리케이션 본문에서 사용되는 대부분의 요소는 플로우 콘텐츠로 분류됩니다.

3.2.5.2.3 구획 콘텐츠

구획 콘텐츠headerfooter 요소의 범위를 정의하는 콘텐츠입니다.

3.2.5.2.4 제목 콘텐츠

제목 콘텐츠는 섹션의 제목을 정의합니다(섹션화 콘텐츠 요소를 사용하여 명시적으로 표시하거나 제목 콘텐츠 자체에 의해 암시됩니다).

3.2.5.2.5 구문 콘텐츠

구문 콘텐츠는 문서의 텍스트와 그 텍스트를 단락 내부에서 마크업하는 요소들입니다. 구문 콘텐츠의 연속은 단락을 형성합니다.

구문 콘텐츠로 분류되는 대부분의 요소는 구문 콘텐츠로 분류된 요소들만 포함할 수 있으며, 흐름 콘텐츠를 포함할 수 없습니다.

텍스트는 콘텐츠 모델의 맥락에서 아무것도 아니거나 텍스트 노드입니다. 텍스트는 때때로 독자적인 콘텐츠 모델로 사용되지만, 구문 콘텐츠이기도 하며, 요소 간 공백이 될 수 있습니다(텍스트 노드가 비어 있거나 단순히 ASCII 공백 문자만 포함하는 경우).

텍스트 노드와 속성 값은 스칼라 값으로 구성되어야 하며, 비문자제어 문자(ASCII 공백 문자 제외)를 제외합니다. 이 명세서는 텍스트 노드와 속성 값의 정확한 값에 대한 추가 제약을 포함합니다.

3.2.5.2.6 임베디드 콘텐츠

임베디드 콘텐츠는 문서에 다른 리소스를 가져오거나, 다른 어휘의 콘텐츠를 문서에 삽입하는 콘텐츠입니다.

HTML 네임스페이스 외의 네임스페이스에서 온 요소로, 콘텐츠를 전달하지만 메타데이터는 아닌 요소들은 이 명세서에서 정의된 콘텐츠 모델의 목적상 임베디드 콘텐츠로 간주됩니다. (예: MathML 또는 SVG)

일부 임베디드 콘텐츠 요소는 대체 콘텐츠를 가질 수 있습니다. 이는 외부 리소스를 사용할 수 없을 때(예: 지원되지 않는 형식일 때) 사용되는 콘텐츠입니다. 요소 정의는 대체 콘텐츠가 있는 경우 그 내용을 명시합니다.

3.2.5.2.7 인터랙티브 콘텐츠

인터랙티브 콘텐츠는 사용자의 상호작용을 위해 특별히 의도된 콘텐츠입니다.

3.2.5.2.8 Palpable content

일반적으로, 콘텐츠 모델이 flow content 또는 phrasing content를 허용하는 요소는 contentspalpable content가 하나 이상 포함되어야 하며, hidden 속성이 지정되지 않아야 합니다.

Palpable content는 요소를 비어 있지 않게 만들어 주며, 후손에 비어 있지 않은 text를 제공하거나, 사용자가 들을 수 있는 것(audio 요소) 또는 볼 수 있는 것(video, img, 또는 canvas 요소) 또는 다른 방식으로 상호작용할 수 있는 것(예: 인터랙티브 폼 컨트롤)을 제공합니다.

이 요구 사항은 엄격한 요구 사항은 아니며, 요소가 비어 있어도 정당한 경우가 많이 있습니다. 예를 들어, 나중에 스크립트로 채워질 자리 표시자로 사용되는 경우나 템플릿의 일부로 요소가 있으며 대부분의 페이지에서는 채워지지만 일부 페이지에서는 관련이 없는 경우가 있습니다.

적합성 검사기는 작성자 보조 도구로서 이 요구 사항을 충족하지 않는 요소를 찾을 수 있는 메커니즘을 제공하는 것이 좋습니다.

다음 요소들은 palpable content입니다:

3.2.5.2.9 스크립트 지원 요소

스크립트 지원 요소는 자체적으로 아무것도 나타내지 않지만(즉, 렌더링되지 않음), 스크립트를 지원하기 위해 사용되는 요소들입니다. 예를 들어, 사용자에게 기능을 제공하기 위해 사용됩니다.

다음 요소들이 스크립트 지원 요소입니다:

3.2.5.3 투명한 콘텐츠 모델

일부 요소는 투명하다고 설명되며, 콘텐츠 모델 설명에 "투명"이라는 용어가 포함됩니다. 투명 요소의 콘텐츠 모델은 부모 요소의 콘텐츠 모델에서 파생됩니다. 투명한 요소가 포함된 부모 요소의 콘텐츠 모델 부분에서 필요한 요소는 투명한 요소의 콘텐츠 모델에서도 동일하게 요구됩니다.

예를 들어, ins 요소가 ruby 요소 안에 있는 경우, rt 요소를 포함할 수 없습니다. 이는 ruby 요소의 콘텐츠 모델에서 ins 요소를 허용하는 부분이 phrasing content를 허용하는 부분이고, rt 요소는 phrasing content가 아니기 때문입니다.

일부 경우 투명한 요소가 서로 중첩된 경우, 이 과정을 반복적으로 적용해야 합니다.

다음 마크업 조각을 고려하십시오:

<p><object><param><ins><map><a href="/">Apples</a></map></ins></object></p>

"Apples"가 a 요소 안에 허용되는지 확인하기 위해 콘텐츠 모델을 검사합니다. a 요소의 콘텐츠 모델은 투명하며, map 요소의 콘텐츠 모델도 투명하고, ins 요소의 콘텐츠 모델도 투명하며, object 요소의 투명한 부분에 ins 요소가 포함됩니다. object 요소는 p 요소 안에 있으며, 이 요소의 콘텐츠 모델은 phrasing content입니다. 따라서 "Apples"는 텍스트가 phrasing content이므로 허용됩니다.

투명한 요소에 부모가 없을 때, 그 콘텐츠 모델의 "투명한" 부분은 대신에 어떤 flow content라도 허용되는 것으로 취급해야 합니다.

3.2.5.4 문단

이 섹션에서 정의된 문단 용어는 p 요소의 정의에만 사용되는 것이 아니라, 여기서 정의된 문단 개념은 문서를 해석하는 방법을 설명하는 데 사용됩니다. p 요소는 문단을 마크업하는 여러 가지 방법 중 하나일 뿐입니다.

문단은 일반적으로 특정 주제를 다루는 하나 이상의 문장으로 구성된 텍스트 블록을 형성하는 phrasing content의 연속이지만, 보다 일반적인 주제별 그룹화에도 사용할 수 있습니다. 예를 들어, 주소도 문단이고, 양식의 일부, 서명, 또는 시의 연도 문단으로 간주될 수 있습니다.

다음 예제에서는 섹션에 두 개의 문단이 있습니다. 또한 문단이 아닌 phrasing content를 포함하는 제목도 있습니다. 주석과 inter-element whitespace가 문단을 형성하지 않는 것에 유의하십시오.

<section>
  <h2>Example of paragraphs</h2>
  This is the <em>first</em> paragraph in this example.
  <p>This is the second.</p>
  <!-- This is not a paragraph. -->
</section>

flow content의 문단은 문서가 a, ins, del, map 요소가 없는 상태로 표시되는 것과 관련하여 정의됩니다. 이러한 요소들은 하이브리드 콘텐츠 모델을 가지고 있어서 문단 경계를 가로지를 수 있기 때문입니다. 아래 첫 번째 두 예제에서 보여주듯이 말입니다.

일반적으로 요소가 문단 경계를 가로지르지 않도록 하는 것이 좋습니다. 이러한 마크업을 유지하는 것은 어렵습니다.

다음 예제는 앞서 예제에서 사용한 마크업에 insdel 요소를 추가하여 일부 마크업이 변경되었음을 나타냅니다(이 경우 변경 사항이 별 의미가 없음을 인정합니다). 이 예제는 ins 요소와 del 요소에도 불구하고 이전 예제와 동일한 문단을 가지고 있습니다. ins 요소는 제목과 첫 번째 문단을 가로지르고, del 요소는 두 문단 사이의 경계를 가로지릅니다.

<section>
  <ins><h2>Example of paragraphs</h2>
  This is the <em>first</em> paragraph in</ins> this example<del>.
  <p>This is the second.</p></del>
  <!-- This is not a paragraph. -->
</section>

view가 DOM의 모든 a, ins, del, map 요소를 해당 contents로 대체한 뷰라고 가정하십시오. 그러면 view에서, 문단을 허용하는 요소의 모든 형제 phrasing content 노드들 사이에서 다른 유형의 콘텐츠가 끼어들지 않은 연속된 노드들 중 첫 번째 노드를 first라 하고 마지막 노드를 last라 합니다. 임베디드 콘텐츠(embedded content)나 inter-element whitespace가 아닌 노드로 구성된 각 연속 구간에는 원래 DOM에서 first 바로 앞부터 last 바로 뒤까지 문단이 존재합니다. (따라서 문단은 a, ins, del, map 요소를 가로지를 수 있습니다.)

준수 검사기는 문단이 서로 겹치는 경우 저자에게 경고할 수 있습니다 (이것은 object, video, audio, canvas 요소와 같은 요소를 사용할 때, 또는 HTML을 추가로 포함할 수 있도록 허용하는 다른 네임스페이스의 요소를 통해 간접적으로 발생할 수 있습니다. 예를 들어 SVG svg 또는 MathML math와 같은 요소입니다).

문단은 또한 p 요소에 의해 명시적으로 형성됩니다.

p 요소는 개별 문단을 감싸기 위해 사용할 수 있으며, 그렇지 않으면 각 문단을 서로 구분할 phrasing content 이외의 콘텐츠가 없을 경우에 사용됩니다.

다음 예제에서는 링크가 첫 번째 문단의 절반, 두 문단을 구분하는 제목 전체, 두 번째 문단의 절반을 가로지릅니다. 링크가 문단과 제목을 가로지릅니다.

<header>
 Welcome!
 <a href="about.html">
  This is home of...
  <h1>The Falcons!</h1>
  The Lockheed Martin multirole jet fighter aircraft!
 </a>
 This page discusses the F-16 Fighting Falcon's innermost secrets.
</header>

이 예제를 문단을 명시적으로 표시하고, 하나의 링크 요소를 세 개로 나누어 다시 마크업한 예제는 다음과 같습니다:

<header>
 <p>Welcome! <a href="about.html">This is home of...</a></p>
 <h1><a href="about.html">The Falcons!</a></h1>
 <p><a href="about.html">The Lockheed Martin multirole jet
 fighter aircraft!</a> This page discusses the F-16 Fighting
 Falcon's innermost secrets.</p>
</header>

일부 요소가 대체 콘텐츠를 정의할 때 문단이 중첩될 수 있습니다. 예를 들어 다음 섹션에서:

<section>
 <h2>My Cats</h2>
 You can play with my cat simulator.
 <object data="cats.sim">
  To see the cat simulator, use one of the following links:
  <ul>
   <li><a href="cats.sim">Download simulator file</a>
   <li><a href="https://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a>
  </ul>
  Alternatively, upgrade to the Mellblom Browser.
 </object>
 I'm quite proud of it.
</section>

여기에 다섯 개의 문단이 있습니다:

  1. "You can play with my cat simulator. object I'm quite proud of it."라고 말하는 문단에서, objectobject 요소입니다.
  2. "To see the cat simulator, use one of the following links:"라고 말하는 문단입니다.
  3. "Download simulator file"라고 말하는 문단입니다.
  4. "Use online simulator"라고 말하는 문단입니다.
  5. "Alternatively, upgrade to the Mellblom Browser."라고 말하는 문단입니다.

첫 번째 문단은 다른 네 문단과 중첩되어 있습니다. "cats.sim" 리소스를 지원하는 사용자 에이전트는 첫 번째 문단만 표시할 것입니다. 하지만 대체 콘텐츠를 보여주는 사용자 에이전트는 첫 번째 문단의 첫 번째 문장을 두 번째 문단과 같은 문단으로 표시하고, 마지막 문단은 첫 번째 문단의 두 번째 문장의 시작 부분처럼 혼란스럽게 표시할 것입니다.

이러한 혼동을 피하기 위해 명시적 p 요소를 사용할 수 있습니다. 예를 들어:

<section>
 <h2>My Cats</h2>
 <p>You can play with my cat simulator.</p>
 <object data="cats.sim">
  <p>To see the cat simulator, use one of the following links:</p>
  <ul>
   <li><a href="cats.sim">Download simulator file</a>
   <li><a href="https://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a>
  </ul>
  <p>Alternatively, upgrade to the Mellblom Browser.</p>
 </object>
 <p>I'm quite proud of it.</p>
</section>

3.2.6 글로벌 속성

Global_attributes

다음 속성들은 모든 HTML 요소에 공통적으로 지정될 수 있습니다(이 사양에서 정의되지 않은 요소들까지 포함하여):

이 속성들은 오직 이 사양에서 정의된 HTML 요소에 대한 속성으로만 정의됩니다. 이 사양에서 이러한 속성을 가진 것으로 언급된 요소들은, 이 속성들을 가진 것으로 정의되지 않은 네임스페이스의 요소들은 이 속성들을 가진 요소로 간주되어서는 안 됩니다.

예를 들어, 다음 XML 조각에서, "bogus" 요소는 이 사양에서 정의된 dir 속성을 가지고 있지 않습니다, 비록 "dir"이라는 이름을 가진 속성을 가지고 있음에도 불구하고. 따라서, 내부 가장 안쪽의 span 요소의 방향성은 'rtl'로, "bogus" 요소를 통해 간접적으로 div 요소에서 상속받은 것입니다.

<div xmlns="http://www.w3.org/1999/xhtml" dir="rtl">
 <bogus xmlns="https://example.net/ns" dir="ltr"> 
  <span xmlns="http://www.w3.org/1999/xhtml">
  </span>
 </bogus>
</div>

Global_attributes/slot

모든 최신 엔진에서 지원됩니다.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (레거시)아니요Internet Explorer?
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

DOM은 모든 네임스페이스에서 어떤 요소의 class, id, 그리고 slot 속성에 대한 사용자 에이전트 요구 사항을 정의합니다. [DOM]

class, id, 및 slot 속성은 모든 HTML elements에 지정될 수 있습니다.

HTML elements에 지정될 때, class 속성은 요소가 속하는 여러 클래스를 나타내는 공백으로 구분된 토큰 집합의 값을 가져야 합니다.

요소에 클래스를 지정하면 CSS에서 셀렉터의 클래스 매칭, DOM에서 getElementsByClassName() 메서드 및 기타 기능에 영향을 미칩니다.

저자들이 class 속성에 사용할 수 있는 토큰에는 추가적인 제한이 없지만, 저자들은 콘텐츠의 성격을 설명하는 값 대신, 콘텐츠의 원하는 프레젠테이션을 설명하는 값을 사용하도록 권장됩니다.

HTML elements에 지정될 때, id 속성 값은 요소의 IDs 중에서 고유해야 하며, 하나 이상의 문자를 포함해야 합니다. 값에는 ASCII 공백이 포함되지 않아야 합니다.

id 속성은 해당 요소의 고유 식별자(ID)를 지정합니다.

ID가 어떤 형식을 취할 수 있는지에 대한 다른 제한은 없습니다. 특히, ID는 숫자로만 구성될 수 있으며, 숫자로 시작하거나 밑줄로 시작하거나, 단순히 구두점으로 구성될 수도 있습니다.

요소의 고유 식별자는 특정 문서의 특정 부분에 링크하기 위한 방법, 스크립팅 시 요소를 타겟팅하기 위한 방법, CSS에서 특정 요소를 스타일링하는 방법 등 다양한 목적으로 사용할 수 있습니다.

식별자는 불투명한 문자열입니다. id 속성의 값에서 특정 의미를 유추해서는 안 됩니다.

HTML elements에 특정된 slot 속성에 대한 적합성 요구 사항은 없습니다.

slot 속성은 요소에 슬롯을 할당하는 데 사용됩니다. slot 속성이 있는 요소는 slot 요소에 의해 생성된 슬롯에 할당됩니다. 이때 슬롯 요소는 쉐도우 트리 내에서 찾을 수 있어야 하며, 해당 트리의 루트호스트를 가지고 있어야 합니다. 이 호스트는 해당하는 slot 속성 값을 가지고 있습니다.


접근성 기술 제품이 HTML 요소와 속성으로는 노출하기 어려운 세분화된 인터페이스를 제공할 수 있도록, 접근성 기술 제품을 위한 주석(annotations) 세트를 지정할 수 있습니다. 이 주석 세트에는 ARIA rolearia-* 속성이 포함됩니다. [ARIA]


다음 이벤트 핸들러 콘텐츠 속성은 모든 HTML 요소에 지정될 수 있습니다:

별표로 표시된 속성은 body 요소에 지정될 때 다른 의미를 가집니다. 이러한 요소들은 동일한 이름의 Window 객체의 이벤트 핸들러를 노출하기 때문입니다.

이 속성들은 모든 요소에 적용되지만, 모든 요소에서 유용하지는 않습니다. 예를 들어, 오직 미디어 요소만이 사용자 에이전트에 의해 발생된 volumechange 이벤트를 받을 수 있습니다.


사용자 정의 데이터 속성 (예: data-foldername 또는 data-msgid)은 모든 HTML 요소에 지정될 수 있으며, 페이지에 특정한 사용자 데이터, 상태, 주석 등을 저장하는 데 사용됩니다.


HTML 문서에서, HTML 네임스페이스 내의 요소는 "http://www.w3.org/1999/xhtml" 값을 정확히 가질 경우에만 xmlns 속성을 가질 수 있습니다. 이는 XML 문서에는 적용되지 않습니다.

HTML에서 xmlns 속성은 전혀 영향을 미치지 않습니다. 이 속성은 XML로의 이동을 약간 더 쉽게 하기 위해 허용되는 일종의 부적입니다. HTML 파서에 의해 구문 분석될 때 이 속성은 XML에서 네임스페이스 선언 속성들이 속하는 "http://www.w3.org/2000/xmlns/" 네임스페이스가 아닌, 네임스페이스에 속하지 않습니다.

XML에서 xmlns 속성은 네임스페이스 선언 메커니즘의 일부이며, 실제로 네임스페이스에 속하지 않는 xmlns 속성을 지정할 수 없습니다.


XML은 또한 XML 네임스페이스 내의 모든 요소에 대해 xml:space 속성의 사용을 허용합니다. 이 속성은 HTML 요소에는 영향을 미치지 않으며, HTML의 기본 동작은 공백을 유지하는 것입니다. [XML]

HTML 요소에서 xml:space 속성을 text/html 구문에서 직렬화할 수 있는 방법은 없습니다.

3.2.6.1 title 속성

Global_attributes/title

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

title 속성은 요소에 대한 권고 정보를 나타냅니다. 예를 들어, 링크에서는 대상 리소스의 제목이나 설명이 될 수 있으며, 이미지에서는 이미지 설명이나 크레딧이 될 수 있습니다. 문단에서는 주석이나 텍스트에 대한 설명이 될 수 있으며, 인용에서는 출처에 대한 추가 정보가 될 수 있습니다. 대화형 콘텐츠에서는 요소의 사용에 대한 라벨이나 지침이 될 수 있습니다. 이 속성의 값은 텍스트입니다.

title 속성에 의존하는 것은 현재 권장되지 않습니다. 많은 사용자 에이전트가 이 명세서에서 요구하는 대로 속성을 접근 가능한 방식으로 노출하지 않기 때문입니다 (예: 마우스와 같은 포인팅 장치를 필요로 하여 툴팁을 나타내는 경우, 이는 키보드 전용 사용자와 현대적인 휴대폰이나 태블릿을 사용하는 터치 전용 사용자에게 제외됩니다).

이 속성이 요소에 생략된 경우, 이는 HTML 요소의 가장 가까운 상위 요소에 설정된 title 속성의 권고 정보가 이 요소에도 관련이 있음을 암시합니다. 이 속성을 설정하면 이러한 암시가 무시되며, 상위 요소의 권고 정보가 이 요소와 관련이 없음을 명시적으로 나타냅니다. 속성을 빈 문자열로 설정하면 해당 요소에 권고 정보가 없음을 나타냅니다.

속성의 값에 U+000A 줄 바꿈(LF) 문자가 포함된 경우, 내용이 여러 줄로 나뉩니다. 각 U+000A 줄 바꿈(LF) 문자는 줄 바꿈을 나타냅니다.

title 속성에 줄 바꿈을 사용하는 것에 대해 주의가 필요합니다.

예를 들어, 다음 스니펫은 실제로 줄 바꿈이 포함된 약어의 확장을 정의합니다:

<p>My logs show that there was some interest in <abbr title="Hypertext
Transport Protocol">HTTP</abbr> today.</p>

일부 요소(예: link, abbr, input)는 위에 설명된 의미 외에 title 속성에 대한 추가적인 의미를 정의합니다.

요소의 권고 정보는 다음 알고리즘이 반환하는 값입니다. 알고리즘이 값을 반환하면 즉시 종료됩니다. 알고리즘이 빈 문자열을 반환하면 권고 정보가 없습니다.

  1. 요소에 title 속성이 있으면, 그 값에 대해 줄 바꿈 정규화를 수행한 결과를 반환합니다.

  2. 요소에 상위 요소가 있으면, 상위 요소의 권고 정보를 반환합니다.

  3. 빈 문자열을 반환합니다.

사용자 에이전트는 요소에 권고 정보가 있는 경우 사용자가 이를 인지할 수 있도록 해야 합니다. 그렇지 않으면 정보가 발견되지 않을 것입니다.


HTMLElement/title

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

title IDL 속성은 title 콘텐츠 속성을 반영해야 합니다.

3.2.6.2 langxml:lang 속성

Global_attributes/lang

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

lang 속성 (네임스페이스 없음)은 요소의 콘텐츠와 텍스트가 포함된 모든 속성에 대해 기본 언어를 지정합니다. 이 값은 유효한 BCP 47 언어 태그 또는 빈 문자열이어야 합니다. 속성을 빈 문자열로 설정하면 기본 언어가 알 수 없음을 나타냅니다. [BCP47]

lang 속성은 XML 네임스페이스에 정의되어 있습니다. [XML]

이 속성들이 요소에서 생략되면, 이 요소의 언어는 부모 요소의 언어와 동일합니다(부모 요소가 있는 경우). 다만 slot 요소는 쉐도우 트리에서 예외입니다.

네임스페이스 없는 lang 속성은 모든 HTML 요소에서 사용할 수 있습니다.

lang 속성HTML 요소에서 XML 문서뿐만 아니라 관련 사양에서 허용하는 경우 다른 네임스페이스의 요소에도 사용할 수 있습니다 (특히, MathML과 SVG는 lang 속성을 해당 요소에 지정하는 것을 허용합니다). 만약 동일한 요소에 네임스페이스가 없는 lang 속성과 lang 속성이 지정된 경우, 이들은 ASCII 대소문자 구분 없이 비교할 때 정확히 동일한 값을 가져야 합니다.

작성자는 lang 속성(예: XML 네임스페이스)을 HTML 요소에서 사용해서는 안 됩니다. XML로의 마이그레이션을 쉽게 하기 위해, 작성자는 xml:lang이라는 리터럴 로컬 이름을 가진 네임스페이스가 없는 속성을 HTML 요소에서 명시할 수 있지만, 이러한 속성은 lang 속성이 네임스페이스 없이 함께 지정된 경우에만 명시해야 하며, 두 속성은 ASCII 대소문자 구분 없이 동일한 값을 가져야 합니다.

네임스페이스가 없고 접두사가 없으며 리터럴 로컬 이름이 "xml:lang"인 속성은 언어 처리에 영향을 미치지 않습니다.


노드의 언어를 결정하기 위해, 사용자 에이전트는 다음 목록에서 적합한 첫 번째 단계를 사용해야 합니다:

노드가 lang 속성(예: XML 네임스페이스)이 설정된 요소일 경우

해당 속성의 값을 사용합니다.

노드가 HTML 요소이거나 SVG 네임스페이스에 있는 요소이며, 네임스페이스가 없는 lang 속성이 설정된 경우

해당 속성의 값을 사용합니다.

노드의 부모가 쉐도우 루트인 경우

해당 언어쉐도우 루트호스트의 언어로 사용합니다.

노드의 부모 요소가 null이 아닌 경우

해당 언어부모 요소의 언어로 사용합니다.

그 외의 경우

설정된 프래그마 설정 기본 언어가 있다면, 그것이 노드의 언어입니다. 설정된 프래그마 설정 기본 언어가 없다면, 더 높은 수준의 프로토콜(예: HTTP)에서 제공되는 언어 정보를 최종적인 대체 언어로 사용해야 합니다. 이러한 언어 정보가 없는 경우, 그리고 더 높은 수준의 프로토콜에서 여러 언어를 보고하는 경우, 노드의 언어는 알 수 없으며, 해당 언어 태그는 빈 문자열입니다.

결과 값이 인식되지 않는 언어 태그인 경우, 이는 주어진 언어 태그를 가진 알 수 없는 언어로 처리되어야 하며, 다른 모든 언어와 구분됩니다. 라운드트립이나 언어 태그를 기대하는 다른 서비스와의 통신을 위해, 사용자 에이전트는 알려지지 않은 언어 태그를 수정하지 않고 그대로 전달하고, BCP 47 언어 태그로 태그를 지정해야 하며, 이를 통해 이후 서비스가 데이터를 다른 유형의 언어 설명으로 해석하지 않도록 해야 합니다. [BCP47]

따라서, 예를 들어, lang="xyzzy"가 있는 요소는 선택자 :lang(xyzzy)(예: CSS)로 일치되지만, :lang(abcde)로는 일치하지 않습니다. 둘 다 똑같이 잘못되었더라도 말입니다. 마찬가지로, 웹 브라우저와 스크린 리더가 협력하여 요소의 언어를 전달하는 경우, 브라우저는 해당 언어가 잘못되었음을 알고 있더라도 스크린 리더에 "xyzzy" 언어로 알려주어야 합니다. 다른 구문으로 언어 이름을 인코딩할 수 있는 BCP 47 이외의 구문을 지원하는 스크린 리더가 있으며, 그 다른 구문에서 "xyzzy" 문자열이 벨라루스어를 나타내는 방법이라면, 벨라루스어로 텍스트를 처리하기 시작하는 것은 **잘못된** 일입니다. BCP 47 코드에서 벨라루스어는 "be" 코드로 설명되기 때문입니다.

결과 값이 빈 문자열인 경우, 이는 노드의 언어가 명시적으로 알 수 없음을 의미합니다.


사용자 에이전트는 요소의 언어를 사용하여 적절한 처리나 렌더링(예: 적절한 글꼴이나 발음 선택, 사전 선택 또는 날짜 선택기와 같은 폼 컨트롤의 사용자 인터페이스)을 결정할 수 있습니다.


HTMLElement/lang

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

lang IDL 속성은 네임스페이스가 없는 lang 콘텐츠 속성을 반영해야 합니다.

3.2.6.3 translate 속성

Global_attributes/translate

모든 현재 엔진에서 지원됩니다.

Firefox111+Safari6+Chrome19+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

translate 속성은 페이지가 로컬라이즈될 때 요소의 속성 값과 텍스트 노드 자식들의 값이 번역되어야 하는지 아니면 변경 없이 유지되어야 하는지를 지정하는 데 사용됩니다. 이 속성은 열거형 속성이며, 다음 키워드와 상태를 가집니다:

키워드 상태 간략한 설명
yes yes 번역 모드번역 가능 상태로 설정합니다.
(빈 문자열)
no no 번역 모드번역하지 않음 상태로 설정합니다.

이 속성의 누락된 값의 기본값유효하지 않은 값의 기본값은 모두 상속 상태입니다.

모든 요소(비HTML 요소 포함)는 번역 모드를 가지며, 이는 번역 가능 상태 또는 번역하지 않음 상태 중 하나입니다. 요소의 translate 속성이 yes 상태에 있으면, 해당 요소의 번역 모드번역 가능 상태에 있습니다. 그렇지 않으면 요소의 translate 속성이 no 상태에 있으면, 해당 요소의 번역 모드번역하지 않음 상태에 있습니다. 그렇지 않은 경우, 요소의 translate 속성이 상속 상태에 있거나 요소가 HTML 요소가 아니므로 translate 속성이 없습니다. 이 두 경우 모두, 요소의 번역 모드는 요소의 부모 요소의 상태와 동일하거나, 요소의 부모 요소가 null이면 번역 가능 상태에 있습니다.

요소가 번역 가능 상태에 있으면, 페이지가 로컬라이즈될 때 요소의 번역 가능한 속성텍스트 노드 자식들의 값이 번역됩니다.

요소가 번역하지 않음 상태에 있으면, 페이지가 로컬라이즈될 때 요소의 속성 값과 텍스트 노드 자식들의 값은 그대로 유지됩니다. 예를 들어, 요소에 사람의 이름이나 컴퓨터 프로그램의 이름이 포함된 경우입니다.

다음 속성들은 번역 가능한 속성입니다:

다른 명세서에서는 번역 가능한 속성으로 정의될 수 있는 다른 속성들을 정의할 수 있습니다. 예를 들어, ARIAaria-label 속성을 번역 가능으로 정의할 수 있습니다.


translate IDL 속성은 가져올 때, 요소의 번역 모드번역 가능 상태인 경우 true를 반환하고, 그렇지 않은 경우 false를 반환해야 합니다. 설정할 때, 콘텐츠 속성의 값을 새 값이 true인 경우 "yes"로, 그렇지 않은 경우 "no"로 설정해야 합니다.

이 예제에서는 페이지가 로컬라이즈될 때 문서의 모든 내용이 번역되어야 하지만, 샘플 키보드 입력과 샘플 프로그램 출력은 번역되지 않아야 합니다:

<!DOCTYPE HTML>
<html lang=en> <!-- default on the document element is translate=yes -->
 <head>
  <title>The Bee Game</title> <!-- implied translate=yes inherited from ancestors -->
 </head>
 <body>
  <p>The Bee Game is a text adventure game in English.</p>
  <p>When the game launches, the first thing you should do is type
  <kbd translate=no>eat honey</kbd>. The game will respond with:</p>
  <pre><samp translate=no>Yum yum! That was some good honey!</samp></pre>
 </body>
</html>
3.2.6.4 dir 속성

Global_attributes/dir

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

dir 속성은 열거형 속성이며 다음과 같은 키워드와 상태가 있습니다:

키워드 상태 간단한 설명
ltr ltr 요소의 내용이 명시적으로 좌에서 우로 방향이 고립된 텍스트입니다.
rtl rtl 요소의 내용이 명시적으로 우에서 좌로 방향이 고립된 텍스트입니다.
auto auto 요소의 내용이 명시적으로 방향이 고립된 텍스트이지만, 방향은 요소의 내용을 사용하여 프로그래밍 방식으로 결정됩니다 (아래에 설명되어 있습니다).

auto 상태에서 사용되는 휴리스틱은 매우 단순합니다 (양방향 알고리즘에서 단락 수준 결정과 유사하게 강한 방향성을 가진 첫 번째 문자를 참조합니다). 작성자는 텍스트의 방향이 정말로 알려지지 않았고 더 나은 서버 측 휴리스틱을 적용할 수 없을 때만 이 값을 최후의 수단으로 사용하는 것이 좋습니다. [BIDI]

textareapre 요소의 경우, 휴리스틱은 단락 수준에서 적용됩니다.

이 속성의 누락된 값 기본값잘못된 값 기본값은 모두 정의되지 않은 상태입니다.


요소(HTML 요소뿐만 아니라 HTML 요소)의 방향성은 'ltr' 또는 'rtl' 중 하나입니다. 요소 element에 대해 방향성을 계산하려면 elementdir 속성 상태를 기반으로 합니다:

ltr

'ltr'을 반환합니다.

rtl

'rtl'을 반환합니다.

auto
  1. result자동 방향성인지 확인합니다.

  2. result가 null이면 'ltr'을 반환합니다.

  3. result를 반환합니다.

정의되지 않음
elementbdi 요소인 경우
  1. result자동 방향성인지 확인합니다.

  2. result가 null이면 'ltr'을 반환합니다.

  3. result를 반환합니다.

elementinput 요소이며 type 속성이 전화 상태에 있는 경우

'ltr'을 반환합니다.

그 외의 경우

element부모 방향성을 반환합니다.

dir 속성은 HTML 요소에 대해서만 정의되므로 다른 네임스페이스의 요소에는 존재할 수 없습니다. 따라서 다른 네임스페이스의 요소는 항상 부모 방향성을 사용하게 됩니다.

자동 방향성 양식 연관 요소는 다음과 같습니다:

요소 element에 대한 자동 방향성을 계산하려면:

  1. element자동 방향성 양식 연관 요소인 경우:

    1. elementvalue에 양방향 문자 유형이 AL 또는 R인 문자가 포함되어 있으며, elementvalue의 앞 부분에 양방향 문자 유형이 L인 문자가 없는 경우 'rtl'을 반환합니다. [BIDI]

    2. elementvalue가 빈 문자열이 아닌 경우 'ltr'을 반환합니다.

    3. null을 반환합니다.

  2. elementslot 요소이며, elementrootshadow root이고 element할당된 노드가 비어 있지 않은 경우:

    1. 노드 childelement할당된 노드 중 하나인지 확인합니다:

      1. childDirection을 null로 설정합니다.

      2. childText 노드인 경우, child텍스트 노드 방향성childDirection으로 설정합니다.

      3. 그 외의 경우:

        1. 단언: childElement 노드입니다.

        2. child자동 방향성childDirection으로 설정합니다.

      4. childDirection이 null이 아닌 경우 childDirection을 반환합니다.

    2. null을 반환합니다.

  3. 노드 descendantelement자손 중 하나인지 확인합니다. 트리 순서에서:

    1. descendant 또는 element의 자손인 조상 요소 중 하나가 다음 중 하나인 경우:

      그렇다면 계속 진행합니다.

    2. descendantslot 요소이며, descendantrootshadow root인 경우, 해당 shadow rootshadow root호스트의 방향성을 반환합니다.

    3. descendantText 노드가 아닌 경우, 계속 진행합니다.

    4. descendant텍스트 노드 방향성result로 설정합니다.

    5. result가 null이 아닌 경우 result를 반환합니다.

  4. null을 반환합니다.

노드 Text text에 대한 텍스트 노드 방향성을 계산하려면:

  1. textdata에 양방향 문자 유형이 L, AL 또는 R인 코드 포인트가 포함되어 있지 않으면 null을 반환합니다. [BIDI]

  2. textdata에서 양방향 문자 유형이 L, AL 또는 R인 첫 번째 코드 포인트를 codePoint로 설정합니다.

  3. codePoint가 양방향 문자 유형 AL 또는 R인 경우 'rtl'을 반환합니다.

  4. codePoint가 양방향 문자 유형 L인 경우 'ltr'을 반환합니다.

요소 element에 대한 부모 방향성을 계산하려면:

  1. element의 부모 노드를 parentNode로 설정합니다.

  2. parentNodeshadow root인 경우, parentNode방향성을 반환합니다.

  3. parentNode가 요소인 경우, parentNode방향성을 반환합니다.

  4. 'ltr'을 반환합니다.

이 속성은 양방향 알고리즘과 관련된 렌더링 요구 사항을 포함합니다.


어떤 HTML 요소속성의 방향성은 텍스트가 렌더링에 포함될 때 사용되며, 다음 목록에서 첫 번째 적절한 단계를 기준으로 결정됩니다:

속성이 방향성 지원 속성이고, 요소의 dir 속성이 auto 상태에 있는 경우

속성 값의 논리 순서에서 양방향 문자 유형이 L, AL 또는 R인 첫 번째 문자를 찾습니다. [BIDI]

이러한 문자가 발견되었고 그것이 양방향 문자 유형 AL 또는 R인 경우, 속성의 방향성은 'rtl'입니다.

그 외의 경우, 속성의 방향성은 'ltr'입니다.

그 외의 경우

속성의 방향성요소의 방향성과 동일합니다.

다음 속성들은 방향성 지원 속성입니다:


document.dir [ = value ]

html 요소의 dir 속성 값이 반환됩니다.

ltr, rtl, 또는 auto를 설정하여 html 요소의 dir 속성 값을 변경할 수 있습니다.

해당 요소가 없으면 빈 문자열을 반환하고 새 값을 무시합니다.

HTMLElement/dir

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

dir IDL 속성은 해당 요소의 dir 내용 속성을 반영해야 하며, 알려진 값만으로 제한됩니다.

Document/dir

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari10.1+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

dir IDL 속성은 Document 객체의 dir 내용 속성을 반영해야 하며, 알려진 값만으로 제한됩니다. 해당 요소가 없으면 속성은 빈 문자열을 반환하고 설정 시 아무것도 하지 않아야 합니다.

작성자는 CSS를 사용하는 대신 dir 속성을 사용하여 텍스트 방향을 표시하는 것이 권장됩니다. 이렇게 하면 CSS가 없는 경우에도 (예: 검색 엔진에 의해 해석될 때) 문서가 올바르게 렌더링됩니다.

이 마크업 조각은 IM 대화의 일부입니다.

<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> How do you write "What's your name?" in Arabic?</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> ما اسمك؟</p>
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> Thanks.</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> That's written "شكرًا".</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> Do you know how to write "Please"?</p>
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> "من فضلك", right?</p>

적절한 스타일 시트와 p 요소에 대한 기본 정렬 스타일, 즉 단락의 시작 가장자리에 텍스트를 정렬하는 스타일을 사용하면, 렌더링 결과는 다음과 같이 될 수 있습니다:

각 단락은 별도의 블록으로 렌더링되며, 첫 번째 단락과 마지막 단락을 제외하고는 단락이 왼쪽에 정렬되고, 마지막 단락은 오른쪽에 정렬됩니다. 사용자 이름('Student'와 'Teacher'가 이 예시에서 사용됨)은 오른쪽에 배치되며, 콜론이 왼쪽에 위치하고, 텍스트는 그 왼쪽에서 시작됩니다.

앞서 언급한 것처럼, auto 값이 만능은 아닙니다. 이 예시에서 마지막 단락은 아랍어 문자로 시작하기 때문에 오른쪽에서 왼쪽으로 쓰여진 텍스트로 오해되어 "right?"가 아랍어 텍스트의 왼쪽에 위치하게 됩니다.

3.2.6.5 style 속성

Global_attributes/style

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

모든 HTML 요소에는 style 내용 속성이 설정될 수 있습니다. 이는 스타일 속성으로, CSS Style Attributes에 정의되어 있습니다. [CSSATTR]

CSS를 지원하는 사용자 에이전트에서는, 속성이 추가되거나 값이 변경될 때, 스타일 속성에 대한 규칙에 따라 속성의 값을 파싱해야 합니다. [CSSATTR]

그러나, 속성의 콘텐츠 보안 정책에 의해 요소의 인라인 동작이 차단되어야 하는지 여부 알고리즘이 속성의 요소에 대해 "Blocked"를 반환하는 경우, 속성의 값에 정의된 스타일 규칙은 해당 요소에 적용되지 않아야 합니다. [CSP]

어떠한 요소에 style 속성을 사용하는 문서라도, 해당 속성이 제거된 경우에도 문서는 이해 가능하고 사용할 수 있어야 합니다.

특히, 콘텐츠를 숨기거나 표시하기 위해 또는 문서에 포함되지 않은 의미를 전달하기 위해 style 속성을 사용하는 것은 비표준입니다. (콘텐츠를 숨기거나 표시하려면 hidden 속성을 사용하십시오.)


element.style

해당 요소의 CSSStyleDeclaration 객체를 반환합니다.

style IDL 속성은 CSS Object Model에 정의되어 있습니다. [CSSOM]

다음 예제에서 색상을 나타내는 단어들은 span 요소와 style 속성을 사용하여 시각적 매체에서 관련 색상으로 표시되도록 마크업되었습니다.

<p>My sweat suit is <span style="color: green; background:
transparent">green</span> and my eyes are <span style="color: blue;
background: transparent">blue</span>.</p>
3.2.6.6 data-* 속성을 사용하여비가시적 데이터를 포함하기

Global_attributes/data-*

모든 현재 엔진에서 지원됩니다.

Firefox6+Safari5.1+Chrome7+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

사용자 정의 데이터 속성은 네임스페이스에 속하지 않는 속성으로, 이름이 "data-"로 시작하고 하이픈 뒤에 적어도 한 글자가 있으며, XML 호환되고, ASCII 대문자가 포함되지 않은 속성입니다.

HTML 요소의 모든 속성 이름은 HTML 문서에서 자동으로 ASCII 소문자로 변환되므로, 이 규칙은 그러한 문서에 영향을 미치지 않습니다.

사용자 정의 데이터 속성은 페이지나 애플리케이션에 적절한 속성이나 요소가 없는 경우에만 사용자 정의 데이터, 상태, 주석 등을 저장하기 위해 의도되었습니다.

이러한 속성은 속성을 사용하는 사이트의 관리자가 알지 못하는 소프트웨어가 사용하는 것을 의도하지 않았습니다. 여러 독립적인 도구가 사용하는 일반적인 확장 기능의 경우, 이 사양이 기능을 명시적으로 제공하도록 확장되거나 마이크로데이터와 같은 기술(표준화된 어휘와 함께)을 사용해야 합니다.

예를 들어, 음악에 대한 사이트는 앨범의 트랙을 나타내는 목록 항목을 사용자 정의 데이터 속성으로 주석을 달아 각 트랙의 길이를 포함할 수 있습니다. 이 정보는 사이트 자체에서 트랙 길이로 목록을 정렬하거나 특정 길이의 트랙을 필터링하는 데 사용할 수 있습니다.

<ol>
     <li data-length="2m11s">Beyond The Sea</li>
     ...
    </ol>

그러나, 사용자가 해당 음악 사이트와 관련이 없는 일반 소프트웨어를 사용하여 이 데이터를 통해 특정 길이의 트랙을 검색하는 것은 부적절합니다.

이 속성들은 사이트 자체의 스크립트에서 사용하기 위한 것이며, 공용 메타데이터를 위한 일반 확장 메커니즘이 아닙니다.

유사하게, 페이지 작성자는 자신이 사용하려는 번역 도구에 대한 정보를 제공하는 마크업을 작성할 수 있습니다:

<p>The third <span data-mytrans-de="Anspruch">claim</span> covers the case of <span
    translate="no">HTML</span> markup.</p>

이 예에서 "data-mytrans-de" 속성은 MyTrans 제품이 "claim"이라는 문구를 독일어로 번역할 때 사용할 특정 텍스트를 제공합니다. 그러나, 모든 언어에서 "HTML"은 변경되지 않도록 translate 표준 속성이 사용됩니다. 표준 속성이 제공될 때는 사용자 정의 데이터 속성을 사용할 필요가 없습니다.

이 예에서, 사용자 정의 데이터 속성은 PaymentRequest에 대한 기능 검출 결과를 저장하는 데 사용됩니다. 이는 체크아웃 페이지를 다르게 스타일링하기 위해 CSS에서 사용될 수 있습니다.

<script>
     if ('PaymentRequest' in window) {
       document.documentElement.dataset.hasPaymentRequest = '';
     }
    </script>

여기서 "data-has-payment-request" 속성은 효과적으로 불리언 속성으로 사용됩니다. 속성의 존재를 확인하는 것만으로도 충분합니다. 그러나 작성자가 원한다면 나중에 일부 값을 포함시켜 기능의 제한된 기능을 나타낼 수 있습니다.

모든 HTML 요소는 임의의 값으로 사용자 정의 데이터 속성을 지정할 수 있습니다.

작성자는 이러한 확장을 설계할 때 속성이 무시되고 관련 CSS가 제거되더라도 페이지가 여전히 사용 가능하도록 신중하게 설계해야 합니다.

사용자 에이전트는 이러한 속성이나 값에서 구현 동작을 파생해서는 안 됩니다. 사용자 에이전트를 위한 사양에서는 이러한 속성이 의미 있는 값을 갖도록 정의해서는 안 됩니다.

JavaScript 라이브러리는 페이지의 일부로 간주되므로 사용자 정의 데이터 속성을 사용할 수 있습니다. 많은 작성자가 재사용하는 라이브러리 작성자는 충돌 위험을 줄이기 위해 속성 이름에 자신의 이름을 포함하는 것이 좋습니다. 적절한 경우, 라이브러리 작성자는 또한 속성 이름에 사용되는 정확한 이름을 사용자 정의할 수 있는 API를 제공하는 것이 좋습니다. 이렇게 하면 라이브러리 작성자가 모르게 동일한 이름을 선택한 경우 동일한 페이지에서 라이브러리를 사용할 수 있으며, 상호 호환되지 않는 경우에도 특정 라이브러리의 여러 버전을 동일한 페이지에서 사용할 수 있습니다.

예를 들어, "DoQuery"라는 라이브러리는 data-doquery-range와 같은 속성 이름을 사용할 수 있으며, "jJo"라는 라이브러리는 data-jjo-range와 같은 속성 이름을 사용할 수 있습니다. jJo 라이브러리는 또한 J.setDataPrefix('j2')와 같이 속성 이름에 사용할 접두사를 설정하는 API를 제공하여 data-j2-range와 같은 이름을 갖게 할 수 있습니다.


element.dataset

HTMLElement/dataset

모든 현재 엔진에서 지원됨.

Firefox6+Safari5.1+Chrome7+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android11+

SVGElement/dataset

모든 현재 엔진에서 지원됨.

Firefox51+Safari5.1+Chrome55+
Opera41+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android41+

요소의 DOMStringMap 객체를 반환합니다.

하이픈으로 연결된 이름은 camel-case로 변환됩니다. 예를 들어, data-foo-bar=""element.dataset.fooBar로 변환됩니다.

dataset IDL 속성은 요소의 모든 data-* 속성에 대해 편리한 접근자를 제공합니다. 가져올 때, dataset IDL 속성은 이 요소와 연결된 DOMStringMap을 반환해야 합니다.

DOMStringMap 인터페이스는 dataset 속성에 사용됩니다. 각 DOMStringMap에는 연결된 요소가 있습니다.

[Exposed=Window,
     LegacyOverrideBuiltIns]
    interface DOMStringMap {
      getter DOMString (DOMString name);
      [CEReactions] setter undefined (DOMString name, DOMString value);
      [CEReactions] deleter undefined (DOMString name);
    };

DOMStringMap의 이름-값 쌍을 가져오기 위해 다음 알고리즘을 실행합니다:

  1. list를 빈 이름-값 쌍 목록으로 설정합니다.

  2. 연결된 요소의 첫 다섯 문자가 "data-"이고, 나머지 문자가 ASCII 대문자를 포함하지 않는 각 내용 속성에 대해, list에 이름-값 쌍을 추가합니다. 이 때 이름은 속성의 이름에서 첫 다섯 문자를 제거한 것이며, 값은 속성의 값입니다.

  3. list에 있는 각 이름에 대해, 이름의 U+002D 하이픈-마이너스 문자(-) 뒤에 ASCII 소문자가 따라오는 경우, U+002D 하이픈-마이너스 문자(-)를 제거하고 뒤따르는 문자를 동일한 문자로 ASCII 대문자로 변환합니다.

  4. list를 반환합니다.

DOMStringMap 객체의 지원되는 속성 이름은 언제나 이 시점에서 DOMStringMap의 이름-값 쌍을 가져올 때 반환된 이름 목록입니다.

이름이 지정된 속성의 값을 결정하려면 nameDOMStringMap에서 반환된 DOMStringMap의 이름-값 쌍을 가져와 이름 구성 요소가 name인 쌍의 값 구성 요소를 반환합니다.

새 이름이 지정된 속성의 값을 설정하려면 또는 기존 이름이 지정된 속성의 값을 설정하려면 name과 새로운 값 value를 가지고 다음 단계를 실행합니다:

  1. name에 U+002D 하이픈-마이너스 문자(-) 뒤에 ASCII 소문자가 포함되어 있으면, "SyntaxError" DOMException을 발생시킵니다.

  2. name의 각 ASCII 대문자 앞에 U+002D 하이픈-마이너스 문자(-)를 삽입하고, 문자를 동일한 문자로 ASCII 소문자로 변환합니다.

  3. name의 앞에 "data-" 문자열을 삽입합니다.

  4. name이 XML Name 생산 규칙과 일치하지 않으면 "InvalidCharacterError" DOMException을 발생시킵니다.

  5. 속성 값을 설정합니다 DOMStringMap연결된 요소namevalue를 사용합니다.

기존 이름이 지정된 속성을 삭제하려면 name을 사용하여 DOMStringMap연결된 요소에서 속성을 삭제합니다.

이 알고리즘은 DOMStringMap의 이름-값 쌍을 가져오는 이전 알고리즘에서 제공한 이름에 대해서만 Web IDL에 의해 호출됩니다. [WEBIDL]

웹 페이지에서 예를 들어 게임의 일부로서 요소가 우주선을 나타내려면 class 속성과 함께 data-* 속성을 사용해야 합니다:

<div class="spaceship" data-ship-id="92432"
    data-weapons="laser 2" data-shields="50%" data-x="30" data-y="10" data-z="90">
    <button class="fire"
        onclick="spaceships[this.parentNode.dataset.shipId].fire()">
Fire
</button>

하이픈이 있는 속성 이름이 API에서 카멜 케이스로 변환되는 방식을 주목하세요.

다음 조각과 유사한 구조의 요소가 있는 경우:

<img class="tower" id="tower5" data-x="12" data-y="5"
     data-ai="robotarget" data-hp="46" data-ability="flames"
     src="towers/rocket.png" alt="Rocket Tower">

...누군가는 첫 번째 인수로 처리할 요소를 받아들이는 splashDamage() 함수를 상상할 수 있습니다:

function splashDamage(node, x, y, damage) {
  if (node.classList.contains('tower') && // checking the 'class' attribute
      node.dataset.x == x && // reading the 'data-x' attribute
      node.dataset.y == y) { // reading the 'data-y' attribute
    var hp = parseInt(node.dataset.hp); // reading the 'data-hp' attribute
    hp = hp - damage;
    if (hp < 0) {
      hp = 0;
      node.dataset.ai = 'dead'; // setting the 'data-ai' attribute
      delete node.dataset.ability; // removing the 'data-ability' attribute
    }
    node.dataset.hp = hp; // setting the 'data-hp' attribute
  }
}

3.2.7 innerTextouterText 속성

HTMLElement/innerText

모든 최신 엔진에서 지원됨.

Firefox45+Safari1+Chrome1+
Opera9.6+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android1+Samsung Internet?Opera Android10.1+
element.innerText [ = value ]

요소의 "렌더링된" 텍스트 콘텐츠를 반환합니다.

지정된 값으로 요소의 자식을 대체할 수 있지만, 줄 바꿈은 br 요소로 변환됩니다.

element.outerText [ = value ]

요소의 "렌더링된" 텍스트 콘텐츠를 반환합니다.

지정된 값으로 요소를 대체할 수 있지만, 줄 바꿈은 br 요소로 변환됩니다.

HTMLElement element를 주어진 텍스트 가져오기 단계는 다음과 같습니다:

  1. element렌더링되지 않는 경우 또는 사용자 에이전트가 비CSS 사용자 에이전트인 경우, element하위 텍스트 콘텐츠를 반환합니다.

    이 단계는 예상치 못한 결과를 초래할 수 있습니다. 예를 들어, innerText getter가 렌더링되지 않은 요소에서 호출되면 텍스트 콘텐츠가 반환되지만, 렌더링된 요소에서 호출되면 렌더링되지 않은 모든 자식 요소의 텍스트 콘텐츠는 무시됩니다.

  2. results를 새로 비어있는 목록으로 만듭니다.

  3. element의 각 자식 노드 node에 대해:

    1. current목록으로 설정하고, node에 대해 렌더링된 텍스트 수집 단계를 실행한 결과로 설정합니다. results의 각 항목은 문자열이거나 양의 정수(필수 줄 바꿈 수)입니다.

      직관적으로, 필수 줄 바꿈 수 항목은 해당 지점에 특정 수의 줄 바꿈이 나타남을 의미하지만, 인접한 필수 줄 바꿈 수 항목에 의해 유도된 줄 바꿈과 함께 축소될 수 있습니다. 이는 CSS의 여백 축소와 유사합니다.

    2. current의 각 항목 itemresults에 추가합니다.

  4. 비어있는 문자열 항목을 results에서 제거합니다.

  5. 연속된 필수 줄 바꿈 수 항목을 results의 시작이나 끝에서 제거합니다.

  6. 남아있는 연속된 필수 줄 바꿈 수 항목을 해당 항목의 값의 최대값만큼의 U+000A LF 코드 포인트로 이루어진 문자열로 대체합니다.

  7. results의 문자열 항목을 연결하여 반환합니다.

HTMLElement/outerText

모든 최신 엔진에서 지원됩니다.

Firefox98+Safari1.3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android1+Samsung Internet?Opera Android12.1+

innerTextouterText getter 단계는 텍스트 가져오기 단계this로 실행한 결과를 반환하는 것입니다.

주어진 렌더링된 텍스트 수집 단계에서 노드 node는 다음과 같습니다:

  1. node의 각 자식 노드에 대해 렌더링된 텍스트 수집 단계를 실행하여 items를 설정하고, node의 각 자식 노드에서 트리 순서로 실행된 결과를 연결하여 단일 목록으로 설정합니다.

  2. node계산된 값'visibility'가 'visible'이 아닌 경우 items를 반환합니다.

  3. node렌더링되지 않는 경우 items를 반환합니다. 이 단계의 목적은 계산된 값'display' 속성이 'none'이 아닌 경우, 다음과 같은 요소들이 설명된 대로 동작해야 합니다:

    items는 'display:contents'로 인해 비어있지 않을 수 있습니다.

  4. node텍스트 노드인 경우, 콘텐츠 순서에 따라 node가 생성한 각 CSS 텍스트 박스에 대해 CSS 'white-space' 처리 규칙과 'text-transform' 규칙이 적용된 후의 텍스트를 계산하고, items를 해당 문자열 목록으로 설정한 후 items를 반환합니다. CSS 'white-space' 처리 규칙은 약간 수정되었습니다: 줄 끝의 축소 가능한 공백은 항상 축소되지만, 줄이 블록의 마지막 줄이거나 br 요소로 끝날 때만 제거됩니다. 소프트 하이픈은 유지되어야 합니다. [CSSTEXT]

  5. nodebr 요소인 경우, 단일 U+000A LF 코드 포인트가 포함된 문자열을 items에 추가합니다.

  6. node계산된 값'display' 속성이 'table-cell'이고, nodeCSS 박스가 포함하는 'table-row' 박스의 마지막 'table-cell' 박스가 아닌 경우, 단일 U+0009 TAB 코드 포인트가 포함된 문자열을 items에 추가합니다.

  7. node계산된 값'display' 속성이 'table-row'이고, nodeCSS 박스가 포함하는 가장 가까운 조상 'table' 박스의 마지막 'table-row' 박스가 아닌 경우, 단일 U+000A LF 코드 포인트가 포함된 문자열을 items에 추가합니다.

  8. nodep 요소인 경우, items의 시작과 끝에 2(필수 줄 바꿈 수)를 추가합니다.

  9. node사용된 값'display' 속성이 블록 수준 또는 'table-caption'인 경우, items의 시작과 끝에 1(필수 줄 바꿈 수)을 추가합니다. [CSSDISPLAY]

    부동 요소와 절대 위치 요소는 이 범주에 속합니다.

  10. items를 반환합니다.

대부분의 대체 요소(예: textarea, input, videobutton은 제외)의 하위 노드는 엄밀히 말하면 CSS에 의해 렌더링되지 않으며, 따라서 이 알고리즘의 목적을 위해 CSS 상자가 없습니다.

이 알고리즘은 범위에서 작동하도록 일반화될 수 있습니다. 그런 다음 이를 Selection의 문자열화기 및 범위에 직접 노출시키는 기반으로 사용할 수 있습니다. Bugzilla 버그 10583를 참조하십시오.


HTMLElement element와 문자열 value가 주어진 경우, inner text 설정 단계는 다음과 같습니다:

  1. fragmentvalue에 대한 렌더링된 텍스트 조각으로 설정하고, element노드 문서를 사용합니다.

  2. element 내에서 fragment모두 교체합니다.

innerText setter 단계는 inner text 설정 단계를 실행하는 것입니다.

outerText setter 단계는 다음과 같습니다:

  1. this의 부모가 null인 경우, "NoModificationAllowedError" DOMException을 던집니다.

  2. nextthis다음 형제로 설정합니다.

  3. previousthis이전 형제로 설정합니다.

  4. fragment를 주어진 값에 대한 렌더링된 텍스트 조각으로, this노드 문서를 기준으로 설정합니다.

  5. fragment자식이 없는 경우, fragment에 빈 문자열을 가진 새 Text 노드를 추가합니다. 노드 문서는 this노드 문서입니다.

  6. 모두 교체 this의 부모 내에서 fragmentthis로 설정합니다.

  7. next가 null이 아니고 next이전 형제Text 노드인 경우, 다음 텍스트 노드와 병합합니다.

  8. previousText 노드인 경우, 다음 텍스트 노드와 병합합니다.

렌더링된 텍스트 조각document 문서에 대해 주어진 문자열 input을 사용하여 다음 단계들을 실행한 결과입니다:

  1. fragmentdocument 문서를 가진 새로운 DocumentFragment로 설정합니다.

  2. positioninput에 대한 위치 변수로 설정하고, 초기에는 input의 시작을 가리키도록 합니다.

  3. text를 빈 문자열로 설정합니다.

  4. positioninput의 끝을 지나지 않을 때까지 다음을 반복합니다:

    1. U+000A LF 또는 U+000D CR이 아닌 코드 포인트의 시퀀스를 수집하고, 그 결과를 text로 설정합니다.

    2. text가 빈 문자열이 아닌 경우, document 문서의 새로운 Text 노드를 text를 가진 상태로 fragment추가합니다.

    3. positioninput의 끝을 지나지 않았고, position에서의 코드 포인트가 U+000A LF 또는 U+000D CR인 동안:

      1. position에서의 코드 포인트가 U+000D CR이고 다음 코드 포인트가 U+000A LF인 경우, positioninput의 다음 코드 포인트로 이동합니다.

      2. positioninput의 다음 코드 포인트로 이동합니다.

      3. document, br 요소, 그리고 HTML 네임스페이스를 사용하여 요소를 생성한 결과를 fragment추가합니다.

  5. fragment를 반환합니다.

주어진 Text 노드 node를 사용하여 다음 텍스트 노드와 병합하는 방법:

  1. nextnode다음 형제로 설정합니다.

  2. nextText 노드가 아닌 경우, 작업을 중지합니다.

  3. 데이터를 대체하여, nodedata길이 0을 nextdata로 대체합니다.

  4. next의 부모가 null이 아닌 경우, next제거합니다.

    이전 단계는 변이 이벤트를 트리거할 수 있으므로 부모 확인이 필요합니다.

3.2.8 양방향 알고리즘과 관련된 요구사항

3.2.8.1 양방향 알고리즘 형식화 문자에 대한 작성 적합성 기준

텍스트 콘텐츠HTML 요소 내의 텍스트 노드에 포함될 수 있으며, 컨텐츠에 존재하며 자유 형식 텍스트를 허용하는 HTML 요소의 속성에서 U+202A에서 U+202E와 U+2066에서 U+2069 사이의 문자(양방향 알고리즘 형식화 문자)를 포함할 수 있습니다. [BIDI]

작성자는 dir 속성, bdo 요소, bdi 요소를 사용하는 것이 권장되며, 양방향 알고리즘 형식화 문자를 수동으로 관리하지 않는 것이 좋습니다. 양방향 알고리즘 형식화 문자는 CSS와 잘 어울리지 않습니다.

3.2.8.2 사용자 에이전트 적합성 기준

사용자 에이전트는 문서 및 문서의 일부를 렌더링할 때 올바른 문자 순서를 결정하기 위해 유니코드 양방향 알고리즘을 구현해야 합니다. [BIDI]

HTML을 유니코드 양방향 알고리즘에 매핑하는 작업은 세 가지 방법 중 하나로 수행되어야 합니다. 사용자 에이전트는 CSS를 구현해야 하며, 특히 CSS 'unicode-bidi', 'direction', 'content' 속성을 포함해야 하며, 사용자 에이전트 스타일 시트에 이 명세서의 렌더링 섹션에서 제공된 속성을 사용한 규칙이 포함되어 있어야 합니다. 또는, 사용자 에이전트는 문서에서 지정된 스타일 시트가 이를 재정의하지 않도록 하면서, 상기 언급된 속성들만 구현하고 상기 언급된 모든 규칙이 포함된 사용자 에이전트 스타일 시트가 있는 것처럼 작동해야 하며, 또는 사용자가 동일한 의미를 가진 다른 스타일 언어를 구현해야 합니다. [CSSGC]

다음 요소 및 속성에는 렌더링 섹션에서 정의된 요구사항이 있으며, 이 섹션의 요구사항에 따라 모든 사용자 에이전트에 적용됩니다(제안된 기본 렌더링을 지원하는 사용자 에이전트에만 적용되는 것이 아닙니다):

3.2.9 ARIA 및 플랫폼 접근성 API와 관련된 요구사항

HTML 요소에서 접근성 API 의미를 구현하기 위한 사용자 에이전트 요구사항은 HTML Accessibility API Mappings에 정의되어 있습니다. 여기서 제시된 규칙 외에도, 커스텀 요소 element의 기본 ARIA 역할 의미는 다음과 같이 결정됩니다: [HTMLAAM]

  1. mapelement내부 콘텐츠 속성 맵으로 설정합니다.

  2. 만약 map["role"]이 존재한다면 이를 반환합니다.

  3. 역할이 없음을 반환합니다.

유사하게, 커스텀 요소 element에 대해, stateOrProperty라는 상태 또는 속성의 기본 ARIA 상태 및 속성 의미는 다음과 같이 결정됩니다:

  1. 만약 element부착된 내부 요소가 null이 아니라면:

    1. 만약 element부착된 내부 요소stateOrProperty와 연관된 요소 가져오기가 존재한다면, 이를 실행한 결과를 반환합니다.

    2. 만약 element부착된 내부 요소stateOrProperty와 연관된 요소들 가져오기가 존재한다면, 이를 실행한 결과를 반환합니다.

  2. 만약 element내부 콘텐츠 속성 맵[stateOrProperty]이 존재한다면 이를 반환합니다.

  3. stateOrProperty의 기본값을 반환합니다.

여기서 언급된 "기본 의미"는 ARIA에서 가끔 "네이티브", "암시적", 또는 "호스트 언어" 의미라고도 불립니다. [ARIA]

이 정의의 한 가지 의미는 기본 의미가 시간이 지남에 따라 변경될 수 있다는 것입니다. 이는 커스텀 요소가 내장된 요소와 동일한 표현력을 가질 수 있도록 합니다. 예를 들어, a 요소의 기본 ARIA 역할 의미가 href 속성이 추가되거나 제거됨에 따라 변경되는 방식과 비교해 보십시오.

이 기능의 예를 보려면 커스텀 요소 섹션을 참조하십시오.


HTML 요소에서 ARIA rolearia-* 속성 사용을 확인하기 위한 적합성 검사 요구사항은 ARIA in HTML에 정의되어 있습니다. [ARIAHTML]

4 HTML 요소

4.1 문서 요소

4.1.1 html 요소

Element/html

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLHtmlElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 컨텍스트:
문서의 문서 요소로서.
복합 문서에서 서브문서 조각이 허용되는 곳.
콘텐츠 모델:
head 요소 뒤에 body 요소가 옵니다.
text/html에서 태그 생략:
html 요소의 시작 태그html 요소 안에 있는 첫 번째 내용이 주석이 아닌 경우 생략할 수 있습니다.
html 요소의 종료 태그html 요소 바로 뒤에 주석이 오지 않는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLHtmlElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 또한 사용되지 않는 멤버도 포함되어 있습니다
};

html 요소는 HTML 문서의 루트를 나타냅니다.

작성자는 루트 html 요소에 문서의 언어를 제공하는 lang 속성을 지정하는 것이 권장됩니다. 이는 음성 합성 도구가 사용할 발음을 결정하는 데 도움이 되며, 번역 도구가 사용할 규칙을 결정하는 데에도 도움이 됩니다.

다음 예제의 html 요소는 문서의 언어가 영어임을 선언합니다.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Swapping Songs</title>
</head>
<body>
<h1>Swapping Songs</h1>
<p>Tonight I swapped some of the songs I wrote with some friends, who
gave me some of the songs they wrote. I love sharing my music.</p>
</body>
</html>

4.2 문서 메타데이터

4.2.1 head 요소

Element/head

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLHeadElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 컨텍스트:
html 요소의 첫 번째 요소로서.
콘텐츠 모델:
문서가 iframe srcdoc 문서이거나 상위 프로토콜에서 제목 정보가 제공되는 경우: 최대 하나의 title 요소와 최대 하나의 base 요소를 포함하는 하나 이상의 메타데이터 콘텐츠 요소.
그렇지 않은 경우: 하나 이상의 메타데이터 콘텐츠 요소가 있어야 하며, 이 중 하나는 title 요소이고, 최대 하나는 base 요소여야 합니다.
text/html에서 태그 생략:
head 요소의 시작 태그는 요소가 비어 있거나 head 요소 안의 첫 번째 내용이 요소인 경우 생략할 수 있습니다.
head 요소의 종료 태그head 요소 바로 뒤에 ASCII 공백 또는 주석이 오지 않는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLHeadElement : HTMLElement {
  [HTMLConstructor] constructor();
};

head 요소는 document에 대한 메타데이터 모음을 나타냅니다.

head 요소의 메타데이터 모음은 클 수도 있고 작을 수도 있습니다. 다음은 매우 짧은 예제입니다:

<!doctype html>
<html lang=en>
 <head>
  <title>A document with a short head</title>
 </head>
 <body>
 ...

다음은 더 긴 예제입니다:

<!DOCTYPE HTML>
<HTML LANG="EN">
 <HEAD>
  <META CHARSET="UTF-8">
  <BASE HREF="https://www.example.com/">
  <TITLE>An application with a long head</TITLE>
  <LINK REL="STYLESHEET" HREF="default.css">
  <LINK REL="STYLESHEET ALTERNATE" HREF="big.css" TITLE="Big Text">
  <SCRIPT SRC="support.js"></SCRIPT>
  <META NAME="APPLICATION-NAME" CONTENT="Long headed application">
 </HEAD>
 <BODY>
 ...

title 요소는 대부분의 상황에서 필수 자식 요소이지만, 상위 프로토콜이 제목 정보를 제공하는 경우, 예를 들어 HTML이 이메일 작성 형식으로 사용될 때 이메일의 제목 줄에서 title 요소를 생략할 수 있습니다.

4.2.2 title 요소

Element/title

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer1+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLTitleElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
메타데이터 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
다른 title 요소가 포함되지 않은 head 요소 안에서.
콘텐츠 모델:
텍스트, 단 요소 간 공백은 제외합니다.
text/html에서 태그 생략:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTitleElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] 속성 DOMString text;
};

title 요소는 문서의 제목 또는 이름을 나타냅니다. 작성자는 사용자의 기록, 북마크 또는 검색 결과와 같이 문서가 문맥에서 벗어났을 때에도 문서를 식별할 수 있는 제목을 사용해야 합니다. 문서의 제목은 종종 첫 번째 제목과 다릅니다. 첫 번째 제목은 문맥에서 벗어났을 때도 단독으로 존재할 필요가 없기 때문입니다.

문서당 하나 이상의 title 요소가 있어서는 안 됩니다.

문서에 제목이 없을 가능성이 있는 경우, Document에 대해 title 요소가 필요하지 않을 수 있습니다. 요소가 필요한 경우에 대한 설명은 head 요소의 콘텐츠 모델을 참조하십시오.

title.text [ = value ]

요소의 자식 텍스트 콘텐츠를 반환합니다.

값을 설정하여 요소의 자식을 주어진 값으로 교체할 수 있습니다.

text 속성의 getter는 이 title 요소의 자식 텍스트 콘텐츠를 반환해야 합니다.

text 속성의 setter는 이 title 요소 내에서 주어진 값으로 모두 대체해야 합니다.

적절한 제목의 예와 같은 페이지에 사용될 수 있는 최상위 제목과의 대조를 아래에 설명합니다.

  <title>Introduction to The Mating Rituals of Bees</title>
...
  <h1>Introduction</h1>
  <p>This companion guide to the highly successful
  <cite>Introduction to Medieval Bee-Keeping</cite> book is...

다음 페이지는 동일한 사이트의 일부일 수 있습니다. 제목이 주제를 명확하게 설명하는 반면 첫 번째 제목은 독자가 상황을 알고 있다고 가정하고 있으며, 따라서 춤이 살사인지 왈츠인지 궁금해하지 않을 것이라는 점을 주목하십시오:

  <title>Dances used during bee mating rituals</title>
...
  <h1>The Dances</h1>

문서 제목으로 사용할 문자열은 document.title IDL 속성에서 제공합니다.

사용자 에이전트는 사용자 인터페이스에서 문서를 참조할 때 문서의 제목을 사용해야 합니다. title 요소의 내용이 이와 같이 사용될 때, 그 title 요소의 방향성을 사용하여 사용자 인터페이스에서 문서 제목의 방향성을 설정해야 합니다.

4.2.3 base 요소

요소/base

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLBaseElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
범주:
메타데이터 콘텐츠.
이 요소가 사용될 수 있는 문맥:
다른 base 요소가 없는 head 요소 내.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐츠 속성:
전역 속성
href문서 기본 URL
target탐색 가능한 기본 대상 하이퍼링크 탐색폼 제출에 대해.
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLBaseElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString href;
  [CEReactions] attribute DOMString target;
};

base 요소는 작성자가 문서 기본 URL을 지정하고, URL을 파싱하는 목적으로 사용하며, 기본적으로 탐색 가능한 대상으로 하이퍼링크를 따르는 것과 같은 작업을 수행할 때 사용합니다. 이 요소는 이 정보 외의 콘텐츠를 나타내지 않습니다.

문서당 하나의 base 요소만 존재해야 합니다.

base 요소는 href 속성, target 속성 또는 둘 다를 가져야 합니다.

href 콘텐츠 속성은, 지정된 경우, 공백으로 둘러싸일 수 있는 유효한 URL을 포함해야 합니다.

base 요소가 href 속성을 가지고 있는 경우, 이 요소는 html 요소(해당 manifest 속성은 base 요소에 의해 영향을 받지 않습니다.)를 제외한 URL을 사용하는 다른 요소들보다 앞에 와야 합니다.

href 속성을 가진 여러 base 요소가 있는 경우, 첫 번째를 제외한 모든 요소는 무시됩니다.

target 속성은, 지정된 경우, 유효한 탐색 대상 이름 또는 키워드를 포함해야 하며, 이는 document 내에서 하이퍼링크탐색을 유발할 때 기본으로 사용할 탐색 가능 대상을 지정합니다.

base 요소는 target 속성을 가지고 있는 경우, 하이퍼링크를 나타내는 요소보다 앞에 와야 합니다.

target 속성을 가진 여러 base 요소가 있는 경우, 첫 번째를 제외한 모든 요소는 무시됩니다.

a, area 또는 요소 element 및 선택적 문자열 또는 null target(기본값 null)이 주어졌을 때, 요소의 target을 가져옵니다:

  1. 만약 target이 null이라면:

    1. elementtarget 속성을 가지고 있다면, target을 그 속성의 값으로 설정합니다.

    2. 그렇지 않으면, element노드 문서base 요소를 가지고 있고 target 속성을 가지고 있다면, target을 첫 번째 해당 base 요소의 target 속성 값으로 설정합니다.

  2. 만약 target이 null이 아니고 ASCII 탭 또는 개행 문자와 U+003C (<)을 포함하고 있다면, target을 "_blank"로 설정합니다.

  3. target을 반환합니다.


첫 번째 base 요소가 href 콘텐츠 속성을 가지고 있는 경우, 문서 트리 내에 동결된 기본 URL이 있습니다. 동결된 기본 URL은 다음 상황이 발생할 때마다 설정되어야 합니다:

동결된 기본 URL을 설정합니다 element에 대해:

  1. documentelement노드 문서로 설정합니다.

  2. urlRecorddocument파싱을 통해 elementhref 콘텐츠 속성 값을 document대체 기본 URLdocument문서 문자 인코딩과 함께

    (따라서 base 요소는 자체적으로 영향을 받지 않습니다.)

  3. 다음 중 하나가 참이면:

    element동결된 기본 URLdocument대체 기본 URL로 설정하고 반환합니다.

  4. element동결된 기본 URLurlRecord로 설정합니다.

IDL 속성 href는, 가져올 때 다음 알고리즘을 실행하여 반환되어야 합니다:

  1. documentelement노드 문서로 설정합니다.

  2. url을, 이 요소가 href 속성을 가지고 있는 경우 해당 속성의 값으로, 그렇지 않은 경우에는 빈 문자열로 설정합니다.

  3. urlRecorddocument파싱을 통해 url대체 기본 URLdocument문서 문자 인코딩과 함께 파싱한 결과로 설정합니다.

    (따라서 base 요소는 다른 base 요소나 자체에 의해 영향을 받지 않습니다.)

  4. urlRecord이 실패인 경우, url을 반환합니다.

  5. urlRecord직렬화를 반환합니다.

IDL 속성 href는, 설정 시, 주어진 새 값으로 href 콘텐츠 속성을 설정해야 합니다.

IDL 속성 target는 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

이 예제에서 base 요소는 문서 기본 URL을 설정하는 데 사용됩니다:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>This is an example for the &lt;base&gt; element</title>
        <base href="https://www.example.com/news/index.html">
    </head>
    <body>
        <p>Visit the <a href="archives.html">archives</a>.</p>
    </body>
</html>

위 예제의 링크는 "https://www.example.com/news/archives.html"로 연결되는 링크가 될 것입니다.

Element/link

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLLinkElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
카테고리:
메타데이터 콘텐츠.
요소가 본문에서 허용되는 경우: 흐름 콘텐츠.
요소가 본문에서 허용되는 경우: 구문 콘텐츠.
이 요소를 사용할 수 있는 맥락:
메타데이터 콘텐츠가 예상되는 곳.
noscript 요소가 head 요소의 자식 요소인 경우.
요소가 본문에서 허용되는 경우: 구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐츠 속성:
전역 속성
href하이퍼링크의 주소
crossorigin — 이 요소가 crossorigin 요청을 처리하는 방법
rel — 문서와 하이퍼링크 목적지 리소스 간의 관계
media — 적용 가능한 미디어
integrity서브리소스 무결성 검사에서 사용되는 무결성 메타데이터 [SRI]
hreflang — 링크된 리소스의 언어
type — 참조된 리소스의 유형에 대한 힌트
referrerpolicy — 이 요소가 시작한 참조 정책 페치에 대해
sizes — 아이콘의 크기 (rel="icon"일 때)
imagesrcset — 다양한 상황에서 사용할 이미지, 예를 들어 고해상도 디스플레이, 작은 모니터 등 (rel="preload"일 때)
imagesizes — 다양한 페이지 레이아웃에 대한 이미지 크기 (rel="preload"일 때)
as — 프리로드 요청에 대한 잠재적 목적지 (rel="preload" 및 rel="modulepreload"일 때)
blocking — 이 요소가 잠재적 렌더링 차단인지 여부
color — 사이트 아이콘을 사용자 정의할 때 사용할 색상 (rel="mask-icon"일 때)
disabled — 링크가 비활성화되었는지 여부
fetchpriority — 이 요소가 시작한 우선 순위 설정 페치에 대해
또한, 이 요소에서 title 속성 특수한 의미를 가집니다: 링크의 제목; CSS 스타일 시트 세트 이름
접근성 고려 사항:
작성자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLLinkElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString href;
  [CEReactions] attribute DOMString? crossOrigin;
  [CEReactions] attribute DOMString rel;
  [CEReactions] attribute DOMString as;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
  [CEReactions] attribute DOMString media;
  [CEReactions] attribute DOMString integrity;
  [CEReactions] attribute DOMString hreflang;
  [CEReactions] attribute DOMString type;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList sizes;
  [CEReactions] attribute USVString imageSrcset;
  [CEReactions] attribute DOMString imageSizes;
  [CEReactions] attribute DOMString referrerPolicy;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList blocking;
  [CEReactions] attribute boolean disabled;
  [CEReactions] attribute DOMString fetchPriority;

  // also has obsolete members
};
HTMLLinkElement includes LinkStyle;

link 요소는 작성자가 문서를 다른 리소스와 연결할 수 있게 해줍니다.

링크의 주소는 href 속성에 의해 제공됩니다. href 속성이 존재하는 경우, 그 값은 유효한 비어 있지 않은 URL(공백으로 둘러싸일 수 있음)이어야 합니다. href 속성이나 imagesrcset 속성 중 하나 또는 둘 다 존재해야 합니다.

href 속성과 imagesrcset 속성이 모두 없으면, 이 요소는 링크를 정의하지 않습니다.

지정된 링크 유형(관계)은 rel 속성의 값으로 제공되며, 이 속성이 존재하는 경우 그 값은 순서가 없는 고유한 공백으로 구분된 토큰 집합이어야 합니다. 허용된 키워드와 그 의미는 후속 섹션에서 정의됩니다. rel 속성이 없거나, 키워드가 없거나, 또는 사용된 키워드가 이 사양에 정의된 대로 허용되지 않는 경우, 이 요소는 링크를 생성하지 않습니다.

rel지원되는 토큰HTML 링크 유형에 정의된 키워드로, link 요소에서 허용되며, 처리 모델에 영향을 미치고 사용자 에이전트에서 지원됩니다. 가능한 지원되는 토큰alternate, dns-prefetch, expect, icon, manifest, modulepreload, next, pingback, preconnect, prefetch, preload, search, 그리고 stylesheet입니다. rel지원되는 토큰은 사용자 에이전트가 처리 모델을 구현하는 이 목록의 토큰만 포함해야 합니다.

이론적으로는 사용자 에이전트가 canonical 키워드에 대한 처리 모델을 지원할 수 있습니다. 만약 그 에이전트가 자바스크립트를 실행하는 검색 엔진이라면요. 하지만 실제로는 매우 드뭅니다. 따라서 대부분의 경우, canonicalrel지원되는 토큰에 포함되지 않아야 합니다.

link 요소는 rel 속성 또는 itemprop 속성을 가져야 하며, 둘 다 가져서는 안 됩니다.

link 요소에 itemprop 속성이 있거나, rel 속성에 body-ok 키워드만 포함되어 있는 경우, 이 요소는 본문에서 허용됨이라고 합니다. 이는 요소가 구문 콘텐츠가 예상되는 곳에 사용될 수 있음을 의미합니다.

rel 속성이 사용되는 경우, 이 요소는 페이지의 body에서 가끔만 사용할 수 있습니다. itemprop 속성이 사용되는 경우, 이 요소는 head 요소와 body 요소에서 모두 사용할 수 있으며, 이는 마이크로데이터 모델의 제약을 받습니다.


link 요소를 사용하여 두 가지 종류의 링크를 생성할 수 있습니다: 외부 리소스 링크하이퍼링크. 링크 유형 섹션에서는 특정 링크 유형 이 외부 리소스인지 하이퍼링크인지 정의합니다. 하나의 link 요소가 여러 개의 링크를 생성할 수 있으며(일부는 외부 리소스 링크일 수 있고, 일부는 하이퍼링크일 수 있음), 생성되는 링크의 정확한 종류와 수는 rel 속성에 제공된 키워드에 따라 다릅니다. 사용자 에이전트는 요소별로가 아니라 링크별로 링크를 처리해야 합니다.

link 요소에 대해 생성된 각 링크는 별도로 처리됩니다. 예를 들어, rel="stylesheet"가 있는 두 개의 link 요소가 있다면, 각각은 별개의 외부 리소스로 간주되며, 각 링크는 독립적으로 속성에 의해 영향을 받습니다. 마찬가지로, rel 속성이 next stylesheet 값을 가진 단일 link 요소는 next 키워드에 대한 하이퍼링크stylesheet 키워드에 대한 외부 리소스 링크를 생성하며, 이들은 다른 속성(media 또는 title와 같은)에 의해 다르게 영향을 받습니다.

예를 들어, 다음 link 요소는 두 개의 하이퍼링크(동일한 페이지로)를 생성합니다:

<link rel="author license" href="/about">

이 요소에 의해 생성된 두 개의 링크는 하나는 현재 페이지의 작성자에 대한 정보를 가지고 있다는 의미를 가지며, 다른 하나는 현재 페이지가 제공되는 라이선스에 대한 정보를 가지고 있다는 의미를 가집니다.

하이퍼링크link 요소와 그 rel 속성으로 생성된 경우 문서 전체에 적용됩니다. 이는 rel 속성이 aarea 요소에 사용되어 문서 내에서 링크의 위치에 따라 링크의 컨텍스트를 나타내는 것과 대조됩니다.

a 요소와 area 요소로 생성된 하이퍼링크와 달리, link 요소로 생성된 하이퍼링크는 기본적으로 사용자 에이전트가 제안된 기본 렌더링을 지원하는 경우 문서의 일부로 표시되지 않습니다. 그리고 CSS를 사용하여 강제로 표시하더라도 활성화 동작이 없습니다. 대신, 이들은 주로 페이지 또는 페이지의 콘텐츠를 소비하는 다른 소프트웨어에 의해 사용될 수 있는 의미론적 정보를 제공합니다. 추가적으로, 사용자 에이전트는 이러한 하이퍼링크를 따를 수 있는 UI를 제공할 수 있습니다.

외부 리소스 링크의 정확한 동작은 관련 링크 유형에 정의된 정확한 관계에 따라 달라집니다.


crossorigin 속성은 CORS 설정 속성입니다. 이는 외부 리소스 링크에서 사용하도록 설계되었습니다.

media 속성은 리소스가 적용되는 미디어를 지정합니다. 값은 유효한 미디어 쿼리 리스트이어야 합니다.

Subresource_Integrity

모든 현재 엔진에서 지원됩니다.

Firefox43+Safari11.1+Chrome45+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

integrity 속성은 이 요소가 담당하는 요청에 대한 무결성 메타데이터를 나타냅니다. 값은 텍스트입니다. 이 속성은 rel 속성에 stylesheet, preload, 또는 modulepreload 키워드가 포함된 link 요소에서만 지정되어야 합니다. [SRI]

hreflang 속성은 link 요소에서 hreflang 속성이 a 요소에서 동일한 의미를 가집니다.

type 속성은 링크된 리소스의 MIME 유형을 제공합니다. 이는 순전히 권고사항입니다. 값은 유효한 MIME 유형 문자열이어야 합니다.

외부 리소스 링크의 경우, type 속성은 사용자 에이전트가 지원하지 않는 리소스를 가져오지 않도록 힌트를 제공하는 데 사용됩니다.

referrerpolicy 속성은 참조 정책 속성입니다. 이는 외부 리소스 링크에서 사용하도록 설계되었으며, 참조 정책을 설정하는 데 도움이 됩니다. [REFERRERPOLICY]

title 속성은 링크의 제목을 제공합니다. 하나의 예외를 제외하고는 순전히 권고사항입니다. 값은 텍스트입니다. 예외는 문서 트리에 포함된 스타일 시트 링크에 해당하며, 이 경우 title 속성은 CSS 스타일 시트 세트를 정의합니다.

title 속성은 대부분의 다른 요소에 대한 전역 title 속성과 달리 link 요소에서 링크에 제목이 없으면 상위 요소의 제목을 상속받지 않습니다. 단순히 제목이 없는 것입니다.


imagesrcset 속성은 존재할 수 있으며, srcset 속성입니다.

imagesrcsethref 속성(너비 설명자가 사용되지 않는 경우)은 함께 이미지 소스소스 세트에 기여합니다.

imagesrcset 속성이 존재하고 이미지 후보 문자열너비 설명자를 사용하는 것이 있는 경우, imagesizes 속성도 존재해야 하며, 이는 sizes 속성입니다. imagesizes 속성은 소스 크기소스 세트에 기여합니다.

imagesrcsetimagesizes 속성은 link 요소에서만 지정되어야 하며, rel 속성에 preload 키워드가 지정되어 있으며, "image" 상태에서 as 속성을 가지고 있어야 합니다.

이 속성들은 나중에 img 요소가 해당하는 srcsetsizes 속성 값을 가진 리소스를 미리 로드할 수 있도록 허용합니다:

<link rel="preload" as="image"
      imagesrcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"
      imagesizes="50vw">

<!-- ... later, or perhaps inserted dynamically ... -->
<img src="wolf.jpg" alt="A rad wolf"
     srcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"
     sizes="50vw">

href 속성을 생략하는 방법에 주목하세요. 이 속성은 imagesrcset을 지원하지 않는 브라우저에만 관련이 있으며, 이러한 경우 잘못된 이미지가 미리 로드될 가능성이 높기 때문입니다.

imagesrcset 속성은 media 속성과 결합하여 아트 디렉션을 위한 picture 요소의 소스에서 선택된 적절한 리소스를 미리 로드할 수 있습니다:

<link rel="preload" as="image"
      imagesrcset="dog-cropped-1x.jpg, dog-cropped-2x.jpg 2x"
      media="(max-width: 800px)">
<link rel="preload" as="image"
      imagesrcset="dog-wide-1x.jpg, dog-wide-2x.jpg 2x"
      media="(min-width: 801px)">

<!-- ... later, or perhaps inserted dynamically ... -->
<picture>
  <source srcset="dog-cropped-1x.jpg, dog-cropped-2x.jpg 2x"
          media="(max-width: 800px)">
  <img src="dog-wide-1x.jpg" srcset="dog-wide-2x.jpg 2x"
       alt="An awesome dog">
</picture>

sizes 속성은 시각 매체용 아이콘의 크기를 제공합니다. 이 속성이 존재하는 경우, 그 값은 단순히 권고 사항일 뿐입니다. 사용자 에이전트는 여러 아이콘이 사용 가능한 경우 어떤 아이콘을 사용할지 결정하기 위해 이 값을 사용할 수 있습니다. 지정된 경우, 이 속성의 값은 순서 없는 고유한 공백으로 구분된 토큰 집합이어야 하며, 이는 ASCII 대소문자 구분 없이 매치되어야 합니다. 각 값은 문자열 "any"와 ASCII 대소문자 구분 없이 일치하거나, U+0030 숫자 0(0) 문자가 앞에 오지 않고, U+0078 라틴 소문자 X 또는 U+0058 라틴 대문자 X 문자로 구분된 두 개의 유효한 음수가 아닌 정수로 구성되어야 합니다. 이 속성은 link 요소에만 지정되어야 하며, rel 속성에 icon 키워드나 apple-touch-icon 키워드가 지정된 경우에만 사용해야 합니다.

apple-touch-icon 키워드는 미리 정의된 링크 유형 세트에 대한 확장으로 등록된 키워드이지만, 사용자 에이전트가 이를 지원해야 할 의무는 없습니다.


as 속성은 href 속성에 의해 제공된 리소스를 미리 로드할 때의 잠재적 목적지를 지정합니다. 이는 열거형 속성입니다. 각 잠재적 목적지는 이 속성에 대한 키워드로, 동일한 이름의 상태에 매핑됩니다. 이 속성은 link 요소에 지정되어야 하며, rel 속성에 preload 키워드가 포함되어 있어야 합니다. 이 속성은 link 요소에 지정될 수 있으며, rel 속성에 modulepreload 키워드가 포함된 경우, 이 속성은 스크립트와 유사한 목적지를 나타내는 값을 가져야 합니다. 다른 link 요소에 대해서는 이 속성을 지정해서는 안 됩니다.

as 속성이 사용되는 방법에 대한 처리 모델은 각 링크 유형의 리소스 가져오기 및 처리 알고리즘에 제공됩니다.

이 속성은 누락된 값 기본값이나 유효하지 않은 값 기본값을 가지지 않으며, 이는 유효하지 않거나 누락된 속성 값이 상태에 매핑되지 않음을 의미합니다. 이는 처리 모델에서 고려됩니다. preload 링크의 경우, 두 조건 모두 오류로 간주되며, modulepreload 링크의 경우, 누락된 값은 "스크립트"로 처리됩니다.


blocking 속성은 차단 속성입니다. 이 속성은 stylesheetexpect 링크 유형에서 사용되며, 이러한 키워드를 포함하는 rel 속성을 가진 링크 요소에서만 지정되어야 합니다.


color 속성은 mask-icon 링크 유형에서 사용됩니다. 이 속성은 rel 속성에 mask-icon 키워드가 포함된 link 요소에서만 지정되어야 합니다. 이 값은 사용자가 사이트를 고정할 때 사용자 에이전트가 아이콘의 표시를 사용자 정의하는 데 사용할 수 있는 권장 색상을 정의하는 CSS <color> 프로덕션과 일치하는 문자열이어야 합니다.

이 사양에서는 color 속성에 대한 사용자 에이전트 요구 사항이 없습니다.

mask-icon 키워드는 미리 정의된 링크 유형 세트에 대한 확장으로 등록된 키워드이지만, 사용자 에이전트가 이를 지원해야 할 의무는 없습니다.


link 요소에는 관련된 명시적으로 활성화됨 부울이 있습니다. 초기 값은 false입니다.

disabled 속성은 부울 속성이며, stylesheet 링크 유형에서 사용됩니다. 이 속성은 rel 속성에 stylesheet 키워드가 포함된 link 요소에서만 지정되어야 합니다.

disabled 속성이 제거될 때마다 link 요소의 명시적으로 활성화됨 속성을 true로 설정합니다.

예를 들어, disabled 속성을 동적으로 제거하면, 예를 들어 document.querySelector("link").removeAttribute("disabled")을 사용하여 스타일 시트를 가져오고 적용합니다:

<link disabled rel="alternate stylesheet" href="css/pooh">

HTMLLinkElement/fetchPriority

Firefox아니오Safari🔰 프리뷰+Chrome102+
Opera?Edge102+
Edge (Legacy)?Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

fetchpriority 속성은 가져오기 우선 순위 속성으로, 외부 리소스 링크에서 사용되며, 가져오기 및 리소스 처리 시 사용됩니다.


HTMLLinkElement/rel

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

IDL 속성 href, hreflang, integrity, media, rel, sizes, type, blocking, 그리고 disabled은 각 속성과 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

color 속성에 대한 반영 IDL 속성은 없지만, 나중에 추가될 수 있습니다.

HTMLLinkElement/as

모든 현재 엔진에서 지원됩니다.

Firefox56+Safari10+Chrome50+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

as IDL 속성은 as 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

crossOrigin IDL 속성은 crossorigin 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

HTMLLinkElement/referrerPolicy

모든 현재 엔진에서 지원됩니다.

Firefox50+Safari14.1+Chrome58+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

referrerPolicy IDL 속성은 referrerpolicy 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

fetchPriority IDL 속성은 fetchpriority 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

imageSrcset IDL 속성은 imagesrcset 콘텐츠 속성을 반영해야 합니다.

imageSizes IDL 속성은 imagesizes 콘텐츠 속성을 반영해야 합니다.

HTMLLinkElement/relList

모든 현재 엔진에서 지원됩니다.

Firefox30+Safari9+Chrome50+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

IDL 속성 relListrel 콘텐츠 속성을 반영해야 합니다.

relList 속성은 그 supports() 메서드를 호출하여 지원되는 링크 유형을 확인함으로써 기능 감지에 사용할 수 있습니다.

4.2.4.1 media 속성 처리

링크가 하이퍼링크인 경우, media 속성은 순전히 권고 사항이며, 해당 문서가 어떤 미디어를 위해 설계되었는지를 설명합니다.

그러나 링크가 외부 리소스 링크인 경우, media 속성은 규정적입니다. 사용자 에이전트는 media 속성의 값이 환경과 일치하고 기타 관련 조건이 적용될 때 외부 리소스를 적용해야 하며, 그렇지 않은 경우에는 적용하지 않아야 합니다.

media 속성이 생략된 경우 기본값은 "all"이며, 이는 기본적으로 모든 미디어에 링크가 적용됨을 의미합니다.

외부 리소스는 적용 가능성을 제한하는 추가 제한 사항이 정의되어 있을 수 있습니다. 예를 들어, CSS 스타일 시트는 일부 @media 블록을 포함할 수 있습니다. 이 사양은 이러한 추가 제한 사항이나 요구 사항을 무시하지 않습니다.

4.2.4.2 type 속성 처리

type 속성이 존재하는 경우, 사용자 에이전트는 해당 리소스가 지정된 유형(예: 빈 문자열과 같이 유효한 MIME 타입 문자열이 아닐 수도 있음)이라고 가정해야 합니다. 속성이 생략되었지만 외부 리소스 링크 유형에 기본 유형이 정의된 경우, 사용자 에이전트는 해당 리소스가 해당 유형이라고 가정해야 합니다. UA가 지정된 링크 관계에 대해 주어진 MIME 타입을 지원하지 않는 경우, UA는 링크된 리소스를 가져오고 처리해서는 안 됩니다. UA가 지정된 링크 관계에 대해 주어진 MIME 타입을 지원하는 경우, UA는 링크된 리소스를 가져와서 처리해야 하며, 적절한 시점에 외부 리소스 링크의 특정 유형에 대해 지정된 대로 처리해야 합니다. 속성이 생략되고 외부 리소스 링크 유형에 기본 유형이 정의되어 있지 않지만, 유형이 알려져 있고 지원된다고 가정할 경우 사용자 에이전트가 링크된 리소스를 가져와서 처리할 것이라면, 사용자 에이전트는 이를 지원된다고 가정하고 링크된 리소스를 가져와서 처리해야 합니다.

사용자 에이전트는 type 속성을 권위적으로 간주해서는 안 됩니다. 리소스를 가져온 후, 사용자 에이전트는 리소스의 실제 유형을 결정하기 위해 type 속성을 사용해서는 안 됩니다. 실제 유형만이 리소스를 적용할지 여부를 결정하는 데 사용되며, 이는 이전에 가정한 유형과는 다릅니다.

스타일시트 링크 유형은 리소스의 Content-Type 메타데이터를 처리하기 위한 규칙을 정의합니다.

사용자 에이전트가 리소스의 유형을 확인한 후, 해당 리소스가 지원되는 유형이고 기타 관련 조건이 적용되는 경우 리소스를 적용해야 하며, 그렇지 않은 경우 리소스를 무시해야 합니다.

문서에 다음과 같이 레이블이 지정된 스타일시트 링크가 포함된 경우:

<link rel="stylesheet" href="A" type="text/plain">
<link rel="stylesheet" href="B" type="text/css">
<link rel="stylesheet" href="C">

...그러면 CSS 스타일시트만 지원하는 준수하는 UA는 B 및 C 파일을 가져오고, A 파일은 건너뜁니다(이유: text/plain은 CSS 스타일시트의 MIME 타입이 아니기 때문입니다).

B 및 C 파일에 대해서는 서버에서 반환된 실제 유형을 확인합니다. text/css로 전송된 경우 스타일을 적용하지만, text/plain 또는 기타 다른 유형으로 라벨이 지정된 경우 스타일을 적용하지 않습니다.

두 파일 중 하나가 Content-Type 메타데이터 없이 반환되거나 Content-Type: "null"과 같은 구문적으로 잘못된 유형으로 반환된 경우, 스타일시트 링크에 대한 기본 유형이 적용됩니다. 기본 유형이 text/css이므로 스타일시트는 여전히 적용됩니다.

기본 링크된 리소스를 가져와서 처리하는 알고리즘은 link 요소 el을 받았을 때 다음과 같습니다:

  1. optionsel에서 링크 옵션을 생성한 결과로 설정합니다.

  2. requestoptions에서 링크 요청을 생성한 결과로 설정합니다.

  3. request가 null이면, 반환합니다.

  4. request동기 플래그를 설정합니다.

  5. elrequest를 사용하여 링크된 리소스 가져오기 설정 단계를 실행합니다. 결과가 false이면, 반환합니다.

  6. elrel 속성에 stylesheet 키워드가 포함된 경우, request요청 개시자 유형을 "css"로 설정합니다. 그렇지 않으면 "link"로 설정합니다.

  7. 요청 requestprocessResponseConsumeBody를 사용하여 응답 response와 null, 실패 또는 바이트 시퀀스 bodyBytes에 설정합니다:

    1. success를 true로 설정합니다.

    2. 다음 중 하나라도 참인 경우:

      • bodyBytes가 null이거나 실패일 경우

      • response상태ok 상태가 아닌 경우

      그렇다면 success를 false로 설정합니다.

      콘텐츠별 오류, 예: CSS 구문 오류 또는 PNG 디코딩 오류는 success에 영향을 미치지 않습니다.

    3. 그렇지 않으면 링크 리소스중요한 하위 리소스가 로드될 때까지 기다립니다.

      링크 유형의 중요한 하위 리소스를 정의하는 사양(예: CSS)은 이러한 하위 리소스를 가져오고 처리하는 방법을 설명할 것으로 예상됩니다. 그러나 현재 이 부분이 명확하지 않기 때문에 이 사양에서는 링크 리소스중요한 하위 리소스를 가져오고 처리하는 방법을 설명하고 있으며, 올바르게 수행될 것이라고 기대합니다.

    4. el, success, responsebodyBytes을 사용하여 링크된 리소스를 처리합니다.

링크 처리 옵션 options을 받아서 링크 요청을 생성합니다:

  1. 단언: optionshref가 빈 문자열이 아닙니다.

  2. options목적지가 null이면, null을 반환합니다.

  3. urloptionshref와 상대적으로 URL 인코딩-파싱의 결과로 설정합니다.

    문서나 환경 대신 기본 URL을 전달하는 것은 이슈 #9715에서 추적됩니다.

  4. url이 실패이면, null을 반환합니다.

  5. requesturl, options목적지options교차 출처를 사용하여 잠재적 CORS 요청을 생성한 결과로 설정합니다.

  6. request정책 컨테이너options정책 컨테이너로 설정합니다.

  7. request무결성 메타데이터options무결성으로 설정합니다.

  8. request암호화 논스 메타데이터options암호화 논스 메타데이터로 설정합니다.

  9. request리퍼러 정책options리퍼러 정책으로 설정합니다.

  10. request클라이언트options환경으로 설정합니다.

  11. request우선순위options가져오기 우선순위로 설정합니다.

  12. request을 반환합니다.

사용자 에이전트는 필요할 때 이러한 리소스를 가져와서 처리하도록 선택할 수 있으며, 모든 적용되지 않은 외부 리소스를 미리 가져오는 대신에 이 방법을 사용할 수 있습니다.

링크된 리소스를 가져와서 처리하는 알고리즘과 유사하게, 모든 외부 리소스 링크에는 링크된 리소스를 처리하는 알고리즘이 있으며, 이는 link 요소 el, boolean success, 응답 response, 그리고 바이트 시퀀스 bodyBytes를 가져옵니다. 개별 링크 유형은 자체 링크된 리소스를 처리하는 알고리즘을 제공할 수 있지만, 명시적으로 언급되지 않은 경우 해당 알고리즘은 아무 작업도 하지 않습니다.

주어진 rel 키워드에 대해 달리 명시되지 않은 경우, 요소는 요소의 노드 문서로드 이벤트를 지연시켜야 하며, 모든 시도가 완료될 때까지 기다립니다. 사용자 에이전트가 리소스를 가져와서 처리하려고 시도하지 않은 경우(예: 리소스가 필요할 때까지 기다리는 경우) 로드 이벤트를 지연시키지 않습니다.

외부 리소스 링크가 될 수 있는 모든 링크 유형은 `Link` 응답 헤더에 나타나는 경우에 반응 여부 및 방법을 정의하는 링크 헤더 처리 알고리즘을 정의합니다.

대부분의 링크 유형에서는 이 알고리즘이 아무 작업도 수행하지 않습니다. 링크 유형이 링크 헤더 처리 단계를 정의했는지 빠르게 알 수 있는 좋은 참조는 요약 표입니다.

링크 처리 옵션구조체입니다. 다음과 같은 항목을 포함합니다:

href (기본값 빈 문자열)
목적지 (기본값 빈 문자열)
initiator (기본값 "link")
무결성 (기본값 빈 문자열)
type (기본값 빈 문자열)
암호화 논스 메타데이터 (기본값 빈 문자열)
문자열
crossorigin (기본값 No CORS)
CORS 설정 속성 상태
리퍼러 정책 (기본값 빈 문자열)
리퍼러 정책
소스 세트 (기본값 null)
Null 또는 소스 세트
기본 URL
URL
origin
원점
환경
환경
정책 컨테이너
정책 컨테이너
문서 (기본값 null)
Null 또는 document
문서 준비 시 (기본값 null)
Null 또는 document를 수락하는 알고리즘
가져오기 우선순위 (기본값 auto)
가져오기 우선순위 속성 상태

링크 처리 옵션에는 파싱된 URL 대신 기본 URLhref가 있습니다. 왜냐하면 URL이 옵션의 소스 세트 결과일 수 있기 때문입니다.

link 요소 el을 받아서 링크 옵션을 생성합니다:

  1. documentel노드 문서로 설정합니다.

  2. options을 다음을 사용하여 새 링크 처리 옵션으로 설정합니다:

    목적지
    elas 속성 상태를 변환한 결과.
    crossorigin
    elcrossorigin 콘텐츠 속성 상태.
    리퍼러 정책
    elreferrerpolicy 콘텐츠 속성 상태.
    소스 세트
    el소스 세트.
    기본 URL
    document문서 기본 URL.
    origin
    document원점.
    환경
    document관련 설정 객체.
    정책 컨테이너
    document정책 컨테이너.
    문서
    document.
    암호화 논스 메타데이터
    el[[CryptographicNonce]] 내부 슬롯의 현재 값.
    가져오기 우선순위
    elfetchpriority 콘텐츠 속성 상태.
  3. elhref 속성을 가지고 있다면, optionshrefelhref 속성 값으로 설정합니다.

  4. elintegrity 속성을 가지고 있다면, options무결성elintegrity 콘텐츠 속성 값으로 설정합니다.

  5. eltype 속성을 가지고 있다면, optionstypeeltype 속성 값으로 설정합니다.

  6. 단언: optionshref가 빈 문자열이 아니거나 options소스 세트가 null이 아닙니다.

    link 요소에 href 또는 imagesrcset이 없으면 링크를 나타내지 않습니다.

  7. options을 반환합니다.

헤더 목록headers이 주어졌을 때 헤더에서 링크를 추출합니다:

  1. 리스트links를 설정합니다.

  2. 얻고, 디코딩하고, 분할하는 작업의 결과로 rawLinkHeaders를 설정합니다. response헤더 목록에서 `Link`을 얻습니다.

  3. rawLinkHeaderslinkHeader에 대해 다음을 수행합니다:

    1. 파싱 작업의 결과로 linkObject를 설정합니다. [WEBLINK]

    2. 만약 linkObject["target_uri"]가 존재하지 않는다면, 계속 진행합니다.

    3. linkObjectlinks에 추가합니다.

  4. links를 반환합니다.

doc 문서Document, response 응답, 그리고 "pre-media" 또는 "media" phase가 주어졌을 때 링크 헤더를 처리합니다:

  1. response헤더 목록에서 링크를 추출한 결과로 links를 설정합니다.

  2. linkslinkObject에 대해 다음을 수행합니다:

    1. rellinkObject["relation_type"]로 설정합니다.

    2. attribslinkObject["target_attributes"]로 설정합니다.

    3. 만약 "srcset", "imagesrcset", 또는 "media"가 attribs존재한다면 expectedPhase를 "media"로 설정합니다. 그렇지 않으면 "pre-media"로 설정합니다.

    4. 만약 expectedPhasephase와 일치하지 않으면, 계속 진행합니다.

    5. 만약 attribs["media"]가 존재하고, attribs["media"]가 환경과 일치하지 않으면, 계속 진행합니다.

    6. 다음으로 링크 처리 옵션으로 options을 새로 생성합니다:

      href
      linkObject["target_uri"]
      기본 URL
      doc문서 기본 URL
      origin
      doc원점
      환경
      doc관련 설정 객체
      정책 컨테이너
      doc정책 컨테이너
      문서
      doc
    7. 파싱된 헤더 속성에서 링크 옵션 적용options에 대해 수행하고 attribs를 사용합니다.

    8. 만약 attribs["imagesrcset"]이 존재하고 attribs["imagesizes"]이 존재한다면, options소스 세트를 다음에 따라 설정합니다: linkObject["target_uri"], attribs["imagesrcset"], attribs["imagesizes"], 그리고 null로 소스 세트 생성을 수행합니다.

    9. 링크 헤더 처리 단계를 rel에 대해 options를 사용하여 실행합니다.

파싱된 헤더 속성에서 링크 처리 옵션link processing options options을 적용하려면, 다음 단계를 수행합니다:

  1. 만약 attribs["as"]가 존재한다면, optionsdestinationattribs["as"]를 번역한 결과로 설정합니다.

  2. 만약 attribs["crossorigin"]이 존재하고 이 값이 ASCII 대소문자 구분 없음과 일치하는 경우, CORS 설정 속성 키워드 중 하나와 일치하는 경우, optionscrossorigin을 해당 키워드에 해당하는 CORS 설정 속성 상태로 설정합니다.

  3. 만약 attribs["integrity"]이 존재한다면, options무결성attribs["integrity"]로 설정합니다.

  4. 만약 attribs["referrerpolicy"]가 존재하고 ASCII 대소문자 구분 없음과 일치하는 경우, 리퍼러 정책에 해당하는 경우, options리퍼러 정책을 해당 리퍼러 정책으로 설정합니다.

  5. 만약 attribs["nonce"]이 존재한다면, optionsnonceattribs["nonce"]로 설정합니다.

  6. 만약 attribs["type"]이 존재한다면, optionstypeattribs["type"]으로 설정합니다.

  7. 만약 attribs["fetchpriority"]가 존재하고 이 값이 ASCII 대소문자 구분 없음과 일치하는 경우, 가져오기 우선순위 속성 키워드 중 하나와 일치하는 경우, optionsfetch priority를 해당 fetch priority 키워드로 설정합니다.

4.2.4.5 사전 힌트

상태/103

Firefox미리보기+Safari아니오Chrome103+
Opera아니오Edge103+
Edge (레거시)?Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

사전 힌트는 사용자 에이전트가 탐색 요청이 서버에 의해 완전히 처리되고 응답 코드가 제공되기 전에 문서에서 사용할 가능성이 높은 리소스를 사전 로드하는 등의 작업을 수행할 수 있게 합니다. 서버는 최종 응답을 제공하기 전에 103 상태 코드가 포함된 응답을 제공함으로써 사전 힌트를 나타낼 수 있습니다.[RFC8297]

호환성 문제로 인해 사전 힌트는 일반적으로 HTTP/2 이상에서 제공됩니다, 하지만 가독성을 위해 아래에서 HTTP/1.1 스타일 표기법을 사용합니다.

예를 들어, 다음과 같은 응답 순서가 주어졌을 때:

103 Early Hint
Link: </image.png>; rel=preload; as=image
200 OK
Content-Type: text/html

<!DOCTYPE html>
...
<img src="/image.png">

이미지는 HTML 콘텐츠가 도착하기 전에 로드되기 시작할 것입니다.

탐색 중 제공된 첫 번째 사전 힌트 응답만 처리되며, 교차 출처 리디렉션이 뒤따를 경우 폐기됩니다.

103 응답에는 Link 헤더 외에도 콘텐츠 보안 정책 헤더가 포함될 수 있으며, 이는 사전 힌트를 처리할 때 강제됩니다.

예를 들어, 다음과 같은 응답 순서가 주어졌을 때:

103 Early Hint
Content-Security-Policy: style-src: self;
Link: </style.css>; rel=preload; as=style
103 Early Hint
Link: </image.png>; rel=preload; as=image
302 Redirect
Location: /alternate.html
200 OK
Content-Security-Policy: style-src: none;
Link: </font.ttf>; rel=preload; as=font

글꼴과 스타일이 로드되지만, 이미지는 무시됩니다. 최종 리디렉션 체인에서 첫 번째 사전 힌트 응답만 존중되기 때문입니다. 늦게 도착한 콘텐츠 보안 정책 헤더는 스타일을 가져오는 요청이 이미 수행된 후에 도착하지만, 스타일은 문서에서 접근할 수 없습니다.

사전 힌트 헤더를 처리하기 위해, 응답 response환경 reservedEnvironment이 주어졌을 때:

사전 힌트 Link 헤더는 항상 최종 Link 헤더보다 먼저 처리되며, 그 다음으로 link 요소가 처리됩니다. 이는 사전 및 최종 Link 헤더의 내용을 각각 documenthead 요소에 미리 추가하는 것과 동일합니다.

  1. earlyPolicyContainer를 생성하기 위한 결과를 responsereservedEnvironment에 대해 패치 응답에서 정책 컨테이너 생성으로 설정합니다.

    이 작업은 사전 힌트 응답콘텐츠 보안 정책이 포함되어, 사전 힌트 요청을 가져올 때 적용될 수 있게 합니다.

  2. linksresponse헤더 목록에서 헤더에서 링크 추출의 결과로 설정합니다.

  3. earlyHints를 빈 목록으로 설정합니다.

  4. 각각의 linkObject에 대해 links에서:

    사전 힌트 링크 헤더를 수신하는 순간 earlyRequest를 가져오기를 시작합니다. document가 생성되기 전에 응답이 반환되면, 이를 earlyResponse로 설정합니다. document가 생성되면 이를 커밋하고, 사전 로드된 리소스의 맵에 추가합니다. 문서가 먼저 생성되면, 응답이 사용 가능해지자마자 커밋됩니다.

    1. rellinkObject["relation_type"]로 설정합니다.

    2. options를 새로운 링크 처리 옵션으로 설정합니다. 해당 옵션에:

      href
      linkObject["target_uri"]
      initiator
      "early-hint"
      기본 URL
      responseURL
      origin
      responseURLorigin
      환경
      reservedEnvironment
      정책 컨테이너
      earlyPolicyContainer
    3. attribslinkObject["target_attributes"]로 설정합니다.

      사전 힌트 처리에서는 as, crossorigin, integrity, type 속성만 처리됩니다. 나머지, 특히 blocking, imagesrcset, imagesizes, media 속성은 document가 생성된 후에만 적용됩니다.

    4. 파싱된 헤더 속성에서 링크 옵션 적용attribs를 준 options에 수행합니다.

    5. 링크 헤더 처리 단계를 rel에 대해 options을 주어 실행합니다.

    6. 추가 optionsearlyHints에 추가합니다.

  5. document doc이 주어졌을 때, 다음 하위 단계를 반환합니다: 각각의 earlyHints에서 options에 대해:

    1. 만약 options문서 준비 시가 null이면 options문서doc으로 설정합니다.

    2. 그렇지 않으면 options문서 준비 시doc을 주어 호출합니다.

인터랙티브 사용자 에이전트는 사용자에게 link 요소를 사용하여 생성된 하이퍼링크를 따라갈 수 있는 방법을 사용자 인터페이스 내에서 제공할 수 있습니다. 이러한 하이퍼링크를 따르는 알고리즘을 호출할 때는 userInvolvement 인자를 "브라우저 UI"로 설정해야 합니다. 이 명세서는 정확한 인터페이스를 정의하지 않지만, 문서 내의 각 link 요소로 생성된 각 하이퍼링크에 대해 다음과 같은 정보를 (아래 정의된 요소의 속성에서 얻은) 어떤 형태로든 포함할 수 있습니다.

사용자 에이전트는 리소스의 유형(type 속성으로 제공됨)과 같은 다른 정보도 포함할 수 있습니다.

4.2.5 meta 요소

Element/meta

모든 현재 엔진에서 지원.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLMetaElement

모든 현재 엔진에서 지원.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
메타데이터 콘텐츠.
itemprop 속성이 있는 경우: 흐름 콘텐츠.
itemprop 속성이 있는 경우: 구문 콘텐츠.
이 요소를 사용할 수 있는 맥락:
charset 속성이 있거나, 요소의 http-equiv 속성이 인코딩 선언 상태에 있는 경우: head 요소 내.
http-equiv 속성이 있지만 인코딩 선언 상태에 있지 않은 경우: head 요소 내.
http-equiv 속성이 있지만 인코딩 선언 상태에 있지 않은 경우: noscript 요소의 자식 요소인 head 요소 내.
name 속성이 있는 경우: 메타데이터 콘텐츠가 예상되는 곳.
itemprop 속성이 있는 경우: 메타데이터 콘텐츠가 예상되는 곳.
itemprop 속성이 있는 경우: 구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
없음.
text/html에서의 태그 생략:
종료 태그 없음.
콘텐츠 속성:
전역 속성
name — 메타데이터 이름
http-equiv — 프래그마 지시어
content — 요소의 값
charset문자 인코딩 선언
media — 적용 가능한 미디어
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLMetaElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString httpEquiv;
  [CEReactions] attribute DOMString content;
  [CEReactions] attribute DOMString media;

  // 구식 멤버도 포함
};

meta 요소는 title, base, link, style, 그리고 script 요소로 표현할 수 없는 다양한 종류의 메타데이터를 나타냅니다.

meta 요소는 name 속성을 사용하여 문서 수준의 메타데이터를 나타낼 수 있고, http-equiv 속성을 사용하여 프래그마 지시어를 나타낼 수 있으며, HTML 문서를 문자열 형태로 직렬화할 때(예: 네트워크를 통해 전송하거나 디스크에 저장할 때) charset 속성을 사용하여 파일의 문자 인코딩 선언을 나타낼 수 있습니다.

name, http-equiv, charsetitemprop 속성 중 정확히 하나가 지정되어야 합니다.

name, http-equiv, 또는 itemprop 중 하나가 지정된 경우 content 속성도 지정되어야 합니다. 그렇지 않으면 생략해야 합니다.

charset 속성은 문서에 사용된 문자 인코딩을 지정합니다. 이것은 문자 인코딩 선언입니다. 속성이 존재하는 경우 그 값은 문자열 "utf-8"과 ASCII 대소문자 구분 없이 일치해야 합니다.

charset 속성은 XML 문서에서 아무런 효과가 없지만, XML 문서 간의 마이그레이션을 용이하게 하기 위해 XML 문서에서도 허용됩니다.

charset 속성이 있는 meta 요소는 문서당 하나만 있어야 합니다.

content 속성은 문서 메타데이터나 프래그마 지시어로 사용될 때 요소의 값을 제공합니다. 허용되는 값은 이 명세서의 후속 섹션에서 설명된 대로 정확한 맥락에 따라 다릅니다.

meta 요소에 name 속성이 있는 경우, 문서 메타데이터를 설정합니다. 문서 메타데이터는 이름-값 쌍으로 표현되며, name 속성은 이름을, 동일한 요소의 content 속성은 값을 나타냅니다. 이름은 메타데이터의 어느 측면이 설정되고 있는지를 지정합니다. 유효한 이름과 값의 의미는 다음 섹션에서 설명됩니다. meta 요소에 content 속성이 없는 경우 메타데이터 이름-값 쌍의 값 부분은 빈 문자열입니다.

media 속성은 메타데이터가 적용되는 미디어를 나타냅니다. 값은 유효한 미디어 쿼리 목록이어야 합니다. nametheme-color가 아닌 한, media 속성은 처리 모델에 영향을 미치지 않으며, 저자에 의해 사용되지 않아야 합니다.

name, content, 및 media IDL 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다. IDL 속성 httpEquiv해당 콘텐츠 속성http-equiv에 반영해야 합니다.

4.2.5.1 표준 메타데이터 이름

요소/meta/name

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이 명세는 name 속성에 대한 몇 가지 이름을 정의합니다.

이름은 대소문자를 구분하지 않으며, ASCII 대소문자 구분 없이 비교되어야 합니다.

application-name

값은 페이지가 나타내는 웹 애플리케이션의 이름을 나타내는 짧은 자유 형식의 문자열이어야 합니다. 페이지가 웹 애플리케이션이 아닌 경우, application-name 메타데이터 이름을 사용해서는 안 됩니다. 웹 애플리케이션의 이름 번역은 lang 속성을 사용하여 각 이름의 언어를 지정할 수 있습니다.

문서 내에서 동일한 언어name 속성 값이 ASCII 대소문자 구분 없이 일치하는 application-name 메타 요소는 하나 이상 존재할 수 없습니다.

사용자 에이전트는 페이지의 title 대신 UI에서 애플리케이션 이름을 사용할 수 있습니다. 제목은 특정 순간에 페이지 상태와 관련된 상태 메시지 등을 포함할 수 있기 때문입니다.

언어 목록이 주어졌을 때 애플리케이션 이름을 찾기 위해 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. languages 목록을 만듭니다.

  2. 기본 언어document문서 요소의 언어로 설정합니다(언어가 알려져 있는 경우).

  3. 기본 언어가 존재하고, languages의 다른 언어와 동일하지 않은 경우, languages에 추가합니다.

  4. languages에서 meta 요소가 있는 첫 번째 언어를 선택된 언어로 설정합니다. 여기서 name 속성 값이 ASCII 대소문자 구분 없이 일치하고, 언어가 일치하는 문서에서 application-name 인지 확인합니다.

    이 언어에 해당하는 meta 요소가 없으면, 반환합니다. 애플리케이션 이름이 제공되지 않은 것입니다.

  5. 선택된 언어에 대해, content 속성의 값을 반환합니다.

이 알고리즘은 브라우저가 예를 들어 북마크에 레이블을 붙일 때 페이지 이름이 필요할 때 사용됩니다. 브라우저는 사용자의 선호 언어를 이 알고리즘에 제공합니다.

author

값은 페이지의 저자 중 한 명의 이름을 나타내는 자유 형식의 문자열이어야 합니다.

description

값은 페이지를 설명하는 자유 형식의 문자열이어야 합니다. 값은 예를 들어 검색 엔진과 같은 페이지 디렉토리에 사용하기에 적합해야 합니다. meta 요소는 name 속성 값이 ASCII 대소문자 구분 없이 일치하는 description 요소는 문서에 하나만 존재해야 합니다.

generator

값은 문서를 생성하는 데 사용된 소프트웨어 패키지 중 하나를 식별하는 자유 형식의 문자열이어야 합니다. 이 값은 소프트웨어에 의해 생성되지 않은 페이지에 사용되어서는 안 됩니다. 예를 들어 텍스트 편집기에서 사용자가 직접 작성한 마크업이 있는 페이지에는 사용하지 않습니다.

"Frontweaver"라는 도구가 페이지의 head 요소에 다음과 같이 포함될 수 있습니다. 이를 통해 페이지를 생성하는 데 사용된 도구를 식별할 수 있습니다:

<meta name=generator content="Frontweaver 8.2">
keywords

값은 페이지와 관련된 쉼표로 구분된 토큰 세트여야 합니다.

이 페이지는 영국 고속도로의 서체에 대해 설명하며, 검색을 위한 몇 가지 키워드를 meta 요소에 지정합니다:

<!DOCTYPE HTML>
<html lang="en-GB">
 <head>
  <title>Typefaces on UK motorways</title>
  <meta name="keywords" content="british,type face,font,fonts,highway,highways">

많은 검색 엔진이 이와 같은 키워드를 고려하지 않습니다. 이는 역사적으로 검색 엔진 결과를 스팸으로 채우는 데 사용되었으며 사용자에게 도움이 되지 않는 방식으로 사용되었기 때문입니다.

페이지에 적용 가능한 키워드 목록을 얻으려면, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. keywords 목록을 비웁니다.

  2. 속성 이름이 name이고, content 속성이 있으며, 속성 값이 keywordsASCII 대소문자 구분 없이 일치하는 모든 meta 요소에 대해:

    1. 요소의 content 속성 값을 쉼표로 분리합니다.

    2. 결과 토큰을 keywords에 추가합니다.

  3. 중복된 키워드를 제거합니다.

  4. keywords를 반환합니다. 이것이 저자가 페이지에 적용했다고 지정한 키워드 목록입니다.

사용자 에이전트는 값의 신뢰성이 불충분하다고 판단되면 이 정보를 사용해서는 안 됩니다.

예를 들어, 콘텐츠 관리 시스템은 시스템 내 페이지의 키워드 정보를 사용하여 사이트 내 검색 엔진의 인덱스를 채울 수 있지만, 대규모 콘텐츠 집계자는 부적절한 키워드를 사용하여 순위를 조작하려는 사용자가 있을 수 있습니다.

referrer

값은 referrer 정책이어야 하며, 이는 document의 기본 referrer 정책을 정의합니다. [REFERRERPOLICY]

어떠한 meta 요소가 문서에 삽입되거나, name 또는 content 속성이 변경된 경우, 사용자 에이전트는 다음 알고리즘을 실행해야 합니다:

  1. 해당 요소가 문서 트리 내에 있지 않으면 반환합니다.

  2. 해당 요소에 name 속성이 없고, 그 값이 "referrer"와 ASCII 대소문자 구분 없이 일치하지 않으면 반환합니다.

  3. 해당 요소에 content 속성이 없거나, 그 속성 값이 비어 있으면 반환합니다.

  4. valueelementcontent 속성 값으로 설정하고, 이를 ASCII 소문자로 변환합니다.

  5. value가 다음 표의 첫 번째 열에 있는 값 중 하나인 경우, value를 두 번째 열에 주어진 값으로 설정합니다:

    레거시 값 referrer 정책
    never no-referrer
    default 기본 referrer 정책
    always unsafe-url
    origin-when-crossorigin origin-when-cross-origin
  6. valuereferrer 정책인 경우, element노드 문서정책 컨테이너referrer 정책policy로 설정합니다.

역사적인 이유로, 다른 표준 메타데이터 이름과 달리, referrer의 처리 모델은 요소 제거에 응답하지 않으며, 트리 순서를 사용하지 않습니다. 이 상태에서 가장 최근에 삽입되었거나 가장 최근에 수정된 meta 요소만 효과를 미칩니다.

theme-color

요소/meta/name/theme-color

Firefox아니요Safari15+Chrome🔰 73+
Opera아니요Edge🔰 79+
Edge (레거시)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android80+WebView Android아니요Samsung Internet6.2+Opera Android아니요

값은 CSS <color> 프로덕션과 일치하는 문자열이어야 하며, 페이지나 주변 사용자 인터페이스의 표시를 사용자 지정하는 데 사용자 에이전트가 사용해야 하는 제안된 색상을 정의합니다. 예를 들어, 브라우저는 페이지의 제목 표시줄을 지정된 값으로 색칠하거나 탭 표시줄 또는 작업 전환기에 색상 하이라이트로 사용할 수 있습니다.

HTML 문서 내에서, media 속성 값은 meta 요소의 name 속성 값이 ASCII 대소문자 구분 없이 theme-color와 일치하는 경우, 고유해야 합니다.

이 표준 자체는 "WHATWG 그린"을 테마 색상으로 사용합니다:

<!DOCTYPE HTML>
<title>HTML Standard</title>
<meta name="theme-color" content="#3c790a">

media 속성은 제공된 색상이 사용되어야 하는 컨텍스트를 설명하는 데 사용될 수 있습니다.

이 표준의 테마 색상으로 "WHATWG 그린"을 다크 모드에서만 사용하고자 할 경우, prefers-color-scheme 미디어 기능을 사용할 수 있습니다:

<!DOCTYPE HTML>
<title>HTML Standard</title>
<meta name="theme-color" content="#3c790a" media="(prefers-color-scheme: dark)">

페이지의 테마 색상을 얻으려면, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. 후보 요소를 다음 기준을 충족하는 모든 meta 요소 목록으로 설정합니다. 이 목록은 트리 순서로 작성됩니다:

  2. 후보 요소 목록의 각 요소에 대해:

    1. 요소media 속성이 있고, 요소media 속성 값이 환경과 일치하지 않는다면, 계속 진행합니다.

    2. 요소content 속성 값에서 앞뒤의 ASCII 공백을 제거한 결과를 으로 설정합니다.

    3. CSS 색상 값으로 파싱한 결과를 색상으로 설정합니다.

    4. 색상이 실패하지 않았다면, 색상을 반환합니다.

  3. 아무 것도 반환하지 않습니다 (페이지에 테마 색상이 없음).

어떠한 meta 요소가 문서에 삽입되거나 문서에서 제거되거나, 기존 meta 요소의 name, content 또는 media 속성이 변경되거나, 환경이 변경되어 meta 요소의 media 속성 값이 환경과 일치할 수도 있고 일치하지 않을 수도 있는 경우, 사용자 에이전트는 위의 알고리즘을 다시 실행하고 결과를 관련 UI에 적용해야 합니다.

UI에서 테마 색상을 사용할 때, 사용자 에이전트는 이를 구현에 특정한 방식으로 조정하여 해당 UI에 더 적합하게 만들 수 있습니다. 예를 들어, 사용자 에이전트가 테마 색상을 배경으로 사용하고 그 위에 흰색 텍스트를 표시하려는 경우, 충분한 대비를 보장하기 위해 해당 UI 부분에서 테마 색상의 어두운 변형을 사용할 수 있습니다.

color-scheme

사용자 에이전트가 페이지의 모든 CSS를 로드하기 전에 원하는 색상 체계를 즉시 렌더링할 수 있도록 돕기 위해, 'color-scheme' 값을 meta 요소에 제공할 수 있습니다.

값은 CSS 'color-scheme' 속성 값 구문과 일치하는 문자열이어야 합니다. 이는 페이지가 지원하는 색상 체계를 결정합니다.

문서당 meta 요소에 대해 name 속성 값이 color-schemeASCII 대소문자 구분 없이 일치하는 속성이 하나 이상 존재할 수 없습니다.

다음 선언은 페이지가 어두운 배경 색상과 밝은 전경 색상을 가진 색상 체계를 처리할 수 있음을 나타냅니다:

<meta name="color-scheme" content="dark">

페이지가 지원하는 색상 체계를 얻으려면, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. 후보 요소를 다음 기준을 충족하는 모든 meta 요소 목록으로 설정합니다. 이 목록은 트리 순서로 작성됩니다:

  2. 후보 요소 목록의 각 요소에 대해:

    1. elementcontent 속성 값을 주어진 구성 요소 목록을 파싱하여 파싱된 값으로 설정합니다.
    2. 파싱된 값이 유효한 CSS 'color-scheme' 속성 값인 경우, 파싱된 값을 반환합니다.
  3. 아무 것도 반환하지 않습니다 (페이지에 지원되는 색상 체계가 없음).

어떠한 meta 요소가 문서에 삽입되거나 문서에서 제거되거나, 기존 meta 요소의 name 또는 content 속성이 변경된 경우, 사용자 에이전트는 위의 알고리즘을 다시 실행해야 합니다.

이 규칙은 연속적인 요소를 검사하여 일치하는 것을 찾을 때까지 적용되므로, 저자는 레거시 사용자 에이전트를 처리하기 위해 여러 값을 제공할 수 있습니다. CSS 속성의 폴백이 작동하는 방식과 반대로, 레거시 값은 새로운 값 이후에 배치해야 합니다.

4.2.5.2 다른 메타데이터 이름

누구나 미리 정의된 메타데이터 이름 집합에 대한 확장을 생성하고 사용할 수 있습니다. 이러한 확장을 등록할 필요는 없습니다.

그러나 다음의 경우에는 새로운 메타데이터 이름을 생성하지 않아야 합니다:

또한, 새로운 메타데이터 이름을 생성하고 사용하기 전에 WHATWG Wiki MetaExtensions 페이지를 참고하여 이미 사용 중인 이름을 선택하지 않도록 하고, 이미 사용 중인 메타데이터 이름의 목적을 복제하지 않도록 하며, 새로운 표준화된 이름과 충돌하지 않도록 하는 것이 좋습니다. [WHATWGWIKI]

누구나 언제든지 WHATWG Wiki MetaExtensions 페이지를 편집하여 메타데이터 이름을 추가할 수 있습니다. 새로운 메타데이터 이름은 다음 정보를 사용하여 지정할 수 있습니다:

키워드

정의된 실제 이름입니다. 이름은 다른 정의된 이름과 혼동되지 않도록 해야 합니다 (예: 대소문자만 다른 경우 등).

간단한 설명

메타데이터 이름의 의미에 대한 간단한 비표준 설명으로, 값이 필요한 형식도 포함합니다.

명세서
메타데이터 이름의 의미와 요구 사항에 대한 자세한 설명으로 연결되는 링크입니다. 이는 위키의 다른 페이지이거나 외부 페이지로의 링크일 수 있습니다.
동의어

처리 요구 사항이 정확히 동일한 다른 이름 목록입니다. 저자는 동의어로 정의된 이름을 사용해서는 안 됩니다 (이는 구식 콘텐츠와의 호환성을 위해 사용자 에이전트가 지원해야 하는 이름을 의미합니다). 실제로 사용되지 않는 동의어는 누구든지 제거할 수 있습니다. 호환성을 위해 동의어로 처리해야 하는 이름만 이 방식으로 등록해야 합니다.

상태

다음 중 하나입니다:

제안됨
이 이름은 광범위한 동료 검토와 승인을 받지 않았습니다. 누군가가 이를 제안했으며, 곧 사용할 예정이거나 사용 중입니다.
비준됨
이 이름은 광범위한 동료 검토와 승인을 받았습니다. 잘못된 방식으로 사용되었을 때 이를 처리하는 방법을 명확하게 정의하는 명세서가 있습니다.
중단됨
이 메타데이터 이름은 광범위한 동료 검토를 받았으며, 부족한 것으로 판명되었습니다. 기존 페이지에서는 이 메타데이터 이름을 사용하고 있지만, 새로운 페이지에서는 이를 피해야 합니다. "간단한 설명"과 "명세서" 항목에서 저자가 대신 사용해야 하는 것을 설명합니다.

메타데이터 이름이 기존 값과 중복된 것으로 판명되면 제거하고 기존 값의 동의어로 나열해야 합니다.

메타데이터 이름이 "제안됨" 상태로 한 달 이상 추가되었으나 사용되거나 명세화되지 않은 경우, WHATWG Wiki MetaExtensions 페이지에서 제거될 수 있습니다.

메타데이터 이름이 "제안됨" 상태로 추가되었으나 기존 값과 중복된 것으로 판명된 경우, 제거하고 기존 값의 동의어로 나열해야 합니다. 메타데이터 이름이 "제안됨" 상태로 추가되었으나 유해한 것으로 판명된 경우, "중단됨" 상태로 변경해야 합니다.

누구나 언제든지 상태를 변경할 수 있지만, 위의 정의에 따라 변경해야 합니다.

4.2.5.3 프래그마 지시문

meta 요소에 http-equiv 속성이 지정된 경우, 해당 요소는 프래그마 지시문이 됩니다.

http-equiv 속성은 다음과 같은 키워드 및 상태를 갖는 열거된 속성입니다:

키워드 적합 여부 상태 간단한 설명
content-language 아니오 콘텐츠 언어 프래그마 설정 기본 언어를 설정합니다.
content-type 인코딩 선언 charset을 설정하는 대체 형태입니다.
default-style 기본 스타일 기본 CSS 스타일 시트 집합이름을 설정합니다.
refresh 새로고침 타이머가 설정된 리디렉트 역할을 합니다.
set-cookie 아니오 Set-Cookie 효과가 없습니다.
x-ua-compatible X-UA-Compatible 실제로는 Internet Explorer가 표준에 더 가깝게 따르도록 권장합니다.
content-security-policy 콘텐츠 보안 정책 콘텐츠 보안 정책document에 적용합니다.

meta 요소가 문서에 삽입될 때, 만약 그 요소에 http-equiv 속성이 존재하고 위의 상태 중 하나를 나타내는 경우, 사용자 에이전트는 해당 상태에 맞는 알고리즘을 실행해야 합니다. 이 알고리즘은 아래 목록에 설명되어 있습니다:

콘텐츠 언어 상태 (http-equiv="content-language")

이 기능은 비표준입니다. 저자들은 대신 lang 속성을 사용하는 것이 권장됩니다.

이 프래그마는 프래그마 설정 기본 언어를 설정합니다. 이 프래그마가 성공적으로 처리될 때까지는 프래그마 설정 기본 언어가 없습니다.

  1. 만약 meta 요소에 content 속성이 없다면, 반환합니다.

  2. 만약 요소의 content 속성이 U+002C 콤마(,) 문자를 포함하고 있다면, 반환합니다.

  3. input을 요소의 content 속성 값으로 설정합니다.

  4. positioninput의 첫 번째 문자로 설정합니다.

  5. ASCII 공백input에서 position으로 건너뜁니다.

  6. 코드 포인트 시퀀스 수집input에서 position으로 수행하여 ASCII 공백이 아닌 시퀀스를 수집합니다.

  7. candidate를 이전 단계에서 생성된 문자열로 설정합니다.

  8. 만약 candidate가 빈 문자열이라면, 반환합니다.

  9. 프래그마 설정 기본 언어candidate로 설정합니다.

    값이 여러 공백으로 구분된 토큰으로 구성된 경우, 첫 번째 토큰 이후의 토큰은 무시됩니다.

이 프래그마는 HTTP `Content-Language` 헤더와 거의 비슷하지만, 완전히 같지는 않습니다. [HTTP]

인코딩 선언 상태 (http-equiv="content-type")

인코딩 선언 상태charset 속성을 설정하는 대체 형태로, 문자 인코딩 선언입니다. 이 상태의 사용자 에이전트 요구 사항은 모두 명세서의 파싱 섹션에서 처리됩니다.

meta 요소에 인코딩 선언 상태http-equiv 속성이 지정된 경우, content 속성은 다음과 같은 ASCII 대소문자 구분 없이 일치하는 문자열 값을 가져야 합니다: "text/html;", 선택적으로 뒤따르는 모든 수의 ASCII 공백, 뒤따라 "charset=utf-8"이 포함됩니다.

문서에는 meta 요소에 인코딩 선언 상태http-equiv 속성이 지정된 요소와 meta 요소에 charset 속성이 함께 존재해서는 안 됩니다.

인코딩 선언 상태HTML 문서에서 사용할 수 있지만, 해당 상태로 http-equiv 속성이 있는 요소는 XML 문서에서 사용해서는 안 됩니다.

기본 스타일 상태 (http-equiv="default-style")

Alternative_style_sheets

하나의 엔진에서만 지원됩니다.

Firefox3+Safari?Chrome1–48
OperaYesEdgeNo
Edge (Legacy)?Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

이 프래그마는 기본 CSS 스타일 시트 집합의 이름을 설정합니다.

  1. meta 요소에 content 속성이 없거나, 해당 속성의 값이 빈 문자열인 경우 반환합니다.

  2. 선호하는 CSS 스타일 시트 집합 이름 변경을 요소의 content 속성 값으로 설정합니다. [CSSOM]

새로고침 상태 (http-equiv="refresh")

이 프래그마는 타이머가 설정된 리디렉트 역할을 합니다.

document 객체는 선언적으로 새로고침을 수행합니다 (부울 값)과 연관됩니다. 초기 값은 false입니다.

  1. meta 요소에 content 속성이 없거나, 해당 속성의 값이 빈 문자열인 경우 반환합니다.

  2. input을 요소의 content 속성 값으로 설정합니다.

  3. 공유 선언적 새로고침 단계meta 요소의 노드 문서, input, 및 meta 요소와 함께 실행합니다.

공유 선언적 새로고침 단계document 객체 document, 문자열 input 및 선택적으로 meta 요소 meta를 인수로 하여 다음과 같이 진행됩니다:

  1. 만약 document선언적으로 새로고침을 수행이 true인 경우, 반환합니다.

  2. positioninput의 첫 번째 코드 포인트로 설정합니다.

  3. ASCII 공백input에서 position으로 건너뜁니다.

  4. time을 0으로 설정합니다.

  5. 코드 포인트 시퀀스 수집input에서 position으로 수행하여 ASCII 숫자 시퀀스를 수집하고, 결과를 timeString으로 설정합니다.

  6. 만약 timeString이 빈 문자열인 경우:

    1. 만약 input에서 position이 가리키는 코드 포인트가 U+002E (.)가 아닌 경우, 반환합니다.

  7. 그렇지 않으면, timetimeString을 사용하여 음수가 아닌 정수를 구문 분석하는 규칙에 따라 구문 분석한 결과로 설정합니다.

  8. 코드 포인트 시퀀스 수집input에서 position으로 수행하여 ASCII 숫자 및 U+002E FULL STOP 문자를 수집합니다. 수집된 문자는 무시합니다.

  9. urlRecorddocumentURL로 설정합니다.

  10. 만약 positioninput의 끝을 지나지 않은 경우:

    1. 만약 input에서 position이 가리키는 코드 포인트가 U+003B (;), U+002C (,), 또는 ASCII 공백이 아닌 경우, 반환합니다.

    2. ASCII 공백input에서 position으로 건너뜁니다.

    3. 만약 input에서 position이 가리키는 코드 포인트가 U+003B (;) 또는 U+002C (,)인 경우, position을 다음 코드 포인트로 이동합니다.

    4. ASCII 공백input에서 position으로 건너뜁니다.

  11. 만약 positioninput의 끝을 지나지 않은 경우:

    1. urlStringposition에서 input의 끝까지의 하위 문자열로 설정합니다.

    2. 만약 position에서 input코드 포인트가 U+0055 (U) 또는 U+0075 (u)인 경우, position을 다음 코드 포인트로 이동합니다. 그렇지 않으면, 따옴표 건너뛰기로 이동합니다.

    3. 만약 position에서 input코드 포인트가 U+0052 (R) 또는 U+0072 (r)인 경우, position을 다음 코드 포인트로 이동합니다. 그렇지 않으면, 구문 분석 단계로 이동합니다.

    4. 만약 position에서 input코드 포인트가 U+004C (L) 또는 U+006C (l)인 경우, position을 다음 코드 포인트로 이동합니다. 그렇지 않으면, 구문 분석 단계로 이동합니다.

    5. ASCII 공백input에서 position으로 건너뜁니다.

    6. 만약 position에서 input코드 포인트가 U+003D (=)인 경우, position을 다음 코드 포인트로 이동합니다. 그렇지 않으면, 구문 분석 단계로 이동합니다.

    7. ASCII 공백input에서 position으로 건너뜁니다.

    8. 따옴표 건너뛰기: 만약 position에서 input코드 포인트가 U+0027 (') 또는 U+0022 (")인 경우, quote를 해당 코드 포인트로 설정하고, position을 다음 코드 포인트로 이동합니다. 그렇지 않으면, quote를 빈 문자열로 설정합니다.

    9. urlStringposition에서 input의 끝까지의 하위 문자열로 설정합니다.

    10. 만약 quote가 빈 문자열이 아니고, urlStringquote와 동일한 코드 포인트가 있는 경우, urlString을 해당 코드 포인트 이후의 모든 코드 포인트가 제거되도록 잘라냅니다.

    11. 구문 분석: urlRecordurlString을 사용하여 URL을 인코딩하여 구문 분석한 결과로 설정합니다. document를 기준으로 합니다.

    12. 만약 urlRecord가 실패인 경우, 반환합니다.

  12. document선언적으로 새로고침을 수행을 true로 설정합니다.

  13. 다음 단계 중 하나 이상을 수행합니다:

    • 새로고침이 완료된 후(아래에서 정의됨), 사용자가 리디렉트를 취소하지 않았고, meta가 지정된 경우 document활성 샌드박싱 플래그 세트샌드박스된 자동 기능 브라우징 컨텍스트 플래그를 설정하지 않은 경우, document노드 네비게이블을 사용하여 urlRecord탐색합니다. 이때, historyHandling은 "replace"로 설정됩니다.

      이전 단락의 목적을 위해, 새로고침은 다음 두 조건 중 더 나중에 발생한 시점에서 완료된 것으로 간주됩니다:

      • document완전히 로드된 시간 이후 최소 time 초가 경과하고, 사용자 또는 사용자 에이전트의 선호도를 고려한 경우.
      • meta가 지정된 경우, documentmeta문서에 삽입된 시간 이후 최소 time 초가 경과하고, 사용자 또는 사용자 에이전트의 선호도를 고려한 경우.

      여기서 meta노드 문서가 새로고침이 완료되기 전 단계와는 다를 수 있으므로, document를 사용해야 하며, meta는 항상 지정되는 것은 아닙니다(HTTP `새로고침` 헤더의 경우).

    • 사용자가 선택할 수 있는 인터페이스를 제공하여, document노드 네비게이블urlRecorddocument를 사용하여 탐색합니다.

    • 아무것도 하지 않습니다.

    또한, 사용자 에이전트는 타이머 상태, 타이머가 설정된 리디렉트의 목적지 등을 포함한 작동의 모든 측면을 사용자에게 알릴 수 있습니다.

meta 요소에 http-equiv 속성이 새로고침 상태로 지정된 경우, content 속성의 값은 다음 중 하나로 구성되어야 합니다:

첫 번째 경우, 정수는 페이지가 다시 로드되기 전의 시간을 초 단위로 나타냅니다. 두 번째 경우, 정수는 페이지가 지정된 URL로 교체되기 전의 시간을 초 단위로 나타냅니다.

뉴스 조직의 첫 페이지는 페이지의 head 요소에 다음과 같은 마크업을 포함시켜, 페이지가 5분마다 자동으로 서버에서 다시 로드되도록 할 수 있습니다:

<meta http-equiv="Refresh" content="300">

일련의 페이지를 사용하여 각 페이지가 일정 시간 후에 다음 페이지로 새로고침되는 자동 슬라이드 쇼를 만들 수 있습니다. 이를 위해 다음과 같은 마크업을 사용할 수 있습니다:

<meta http-equiv="Refresh" content="20; URL=page4.html">
Set-Cookie 상태 (http-equiv="set-cookie")

이 프래그마는 비표준이며, 효과가 없습니다.

사용자 에이전트는 이 프래그마를 무시해야 합니다.

X-UA-Compatible 상태 (http-equiv="x-ua-compatible")

실제로, 이 프래그마는 Internet Explorer가 표준을 더 잘 따르도록 권장합니다.

meta 요소에 X-UA-Compatible 상태http-equiv 속성이 지정된 경우, content 속성의 값은 "IE=edge"와 ASCII 대소문자 구분 없이 일치해야 합니다.

사용자 에이전트는 이 프래그마를 무시해야 합니다.

콘텐츠 보안 정책 상태 (http-equiv="content-security-policy")

이 프래그마는 정책을 강제하고, 콘텐츠 보안 정책document에 적용합니다. [CSP]

  1. meta 요소가 head 요소의 자식이 아닌 경우, 반환합니다.

  2. meta 요소에 content 속성이 없거나, 해당 속성의 값이 빈 문자열인 경우 반환합니다.

  3. 정책을 meta 요소의 content 속성 값을 사용하여 콘텐츠 보안 정책의 직렬화된 콘텐츠 보안 정책 구문 분석 알고리즘을 실행한 결과로 설정합니다. 소스는 "meta"로, 배치(disposition)는 "enforce"로 설정합니다.

  4. 정책에서 report-uri, frame-ancestors, sandbox 지시문을 모두 제거합니다.

  5. 정책을 강제합니다.

meta 요소에 콘텐츠 보안 정책 상태http-equiv 속성이 지정된 경우, content 속성의 값은 유효한 콘텐츠 보안 정책으로 구성되어야 하지만, report-uri, frame-ancestors, sandbox 지시문을 포함해서는 안 됩니다. content 속성에 지정된 콘텐츠 보안 정책이 현재 문서에 적용됩니다. [CSP]

meta 요소를 문서에 삽입할 때, 일부 리소스는 이미 가져왔을 수 있습니다. 예를 들어, 이미지가 meta 요소가 강제될 수 있는 상태가 되기 전에 사용 가능한 이미지 목록에 저장될 수 있습니다. 이미 가져온 리소스는 나중에 강제된 콘텐츠 보안 정책에 의해 차단되지 않을 수 있습니다.

페이지는 다음과 같은 정책을 사용하여 교차 사이트 스크립팅 공격의 위험을 줄이고, 모든 플러그인 콘텐츠를 차단할 수 있습니다:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'; object-src 'none'">

문서에 동시에 특정 상태와 일치하는 meta 요소는 하나만 있어야 합니다.

4.2.5.4 문서의 문자 인코딩 지정

문자 인코딩 선언은 문서를 저장하거나 전송할 때 사용되는 문자 인코딩을 지정하는 메커니즘입니다.

Encoding 표준에서는 UTF-8 문자 인코딩의 사용을 요구하며, "utf-8" 인코딩 레이블을 사용하여 이를 식별하도록 요구합니다. 이러한 요구 사항은 문서의 문자 인코딩 선언이 존재하는 경우, ASCII 대소문자 구분 없이 "utf-8"와 일치하는 인코딩 레이블을 지정해야 함을 의미합니다. 문자 인코딩 선언이 존재하든지 않든지 간에, 문서 인코딩에 사용되는 실제 문자 인코딩UTF-8이어야 합니다. [ENCODING]

위의 규칙을 적용하기 위해 저작 도구는 새로 생성된 문서에 대해 기본적으로 UTF-8을 사용해야 합니다.

다음 제한 사항도 적용됩니다:

또한, meta 요소에 대한 여러 제한 사항 때문에, 문서당 하나의 meta 기반 문자 인코딩 선언만 허용됩니다.

만약 HTML 문서가 BOM으로 시작하지 않고, 인코딩이 Content-Type 메타데이터에 명시되지 않으며, 문서가 iframe srcdoc 문서가 아닌 경우, meta 요소와 charset 속성을 사용하여 인코딩을 지정해야 하며, 또는 meta 요소와 http-equiv 속성을 사용하여 인코딩 선언 상태에서 인코딩을 지정해야 합니다.

모든 문자가 ASCII 범위 내에 있더라도 Content-Type 메타데이터 또는 파일에 명시적으로 문서 인코딩 선언이 필요합니다. 왜냐하면, 사용자 입력 양식에서 비-ASCII 문자를 처리하거나, 스크립트에 의해 생성된 URL을 처리하는 데 문자 인코딩이 필요하기 때문입니다.

비-UTF-8 인코딩을 사용하는 경우, 양식 제출 및 URL 인코딩에서 예상치 못한 결과를 초래할 수 있습니다. 이러한 경우 기본적으로 문서의 문자 인코딩이 사용되기 때문입니다.

문서가 iframe srcdoc 문서인 경우, 해당 문서에는 문자 인코딩 선언이 없어야 합니다. (이 경우, 소스는 이미 디코딩되어 있으며, iframe을 포함하는 문서의 일부로서 제공됩니다.)

XML에서는 필요한 경우, 인라인 문자 인코딩 정보를 위해 XML 선언을 사용해야 합니다.

HTML에서 UTF-8 문자 인코딩을 선언하기 위해, 작성자는 문서의 상단 근처에 다음과 같은 마크업을 포함시킬 수 있습니다. (즉, head 요소 안에):

<meta charset="utf-8">

XML에서는, XML 선언을 대신 사용하여 다음과 같이 마크업의 가장 상단에 선언합니다:

<?xml version="1.0" encoding="utf-8"?>

4.2.6 style 요소

Element/style

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera3.5+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

HTMLStyleElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
메타데이터 콘텐츠.
이 요소가 사용될 수 있는 문맥:
메타데이터 콘텐츠가 예상되는 곳.
noscript 요소 내에서, head 요소의 자식인 경우.
내용 모델:
텍스트, 해당 텍스트는 준수하는 스타일 시트이어야 합니다.
텍스트/HTML에서의 태그 생략:
태그를 생략할 수 없습니다.
내용 속성:
전역 속성
media — 적용 가능한 미디어
blocking — 요소가 렌더링을 차단할 가능성이 있는지 여부
또한, title 속성은 이 요소에서 특별한 의미를 가집니다: CSS 스타일 시트 세트 이름
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLStyleElement : HTMLElement {
  [HTMLConstructor] constructor();

  attribute boolean disabled;
  [CEReactions] attribute DOMString media;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList blocking;

  // 구식 멤버도 포함합니다
};
HTMLStyleElement includes LinkStyle;

style 요소를 사용하면 저자가 문서에 CSS 스타일 시트를 포함할 수 있습니다. style 요소는 스타일 처리 모델에 대한 여러 입력 중 하나입니다. 이 요소는 사용자에게 콘텐츠를 표시하지 않습니다.

HTMLStyleElement/disabled

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)13+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

disabled 게터 단계는 다음과 같습니다:

  1. this연결된 CSS 스타일 시트가 없으면 false를 반환합니다.

  2. this연결된 CSS 스타일 시트비활성화 플래그가 설정된 경우 true를 반환합니다.

  3. false를 반환합니다.

disabled 세터 단계는 다음과 같습니다:

  1. this연결된 CSS 스타일 시트가 없는 경우, return.

  2. 주어진 값이 true이면 this연결된 CSS 스타일 시트비활성화 플래그를 설정합니다. 그렇지 않으면 this연결된 CSS 스타일 시트비활성화 플래그를 해제합니다.

중요하게도, disabled 속성 할당은 style 요소가 연결된 CSS 스타일 시트를 가지고 있을 때만 적용됩니다:

const style = document.createElement('style');
style.disabled = true;
style.textContent = 'body { background-color: red; }';
document.body.append(style);
console.log(style.disabled); // false

media 속성은 스타일이 적용될 미디어를 지정합니다. 이 값은 유효한 미디어 쿼리 목록이어야 합니다. 사용자 에이전트는 media 속성의 값이 환경에 맞는 경우 및 기타 관련 조건이 적용될 때 스타일을 적용해야 하며, 그렇지 않은 경우 스타일을 적용하지 않아야 합니다.

스타일은 예를 들어 CSS의 @media 블록을 사용하여 범위가 더 제한될 수 있습니다. 이 사양은 이러한 추가 제한이나 요구사항을 무효화하지 않습니다.

기본값은 media 속성이 생략된 경우 "all"이며, 이는 기본적으로 모든 미디어에 스타일이 적용된다는 의미입니다.

blocking 속성은 차단 속성입니다.

Alternative_style_sheets

하나의 엔진에서만 지원됨.

Firefox3+Safari?Chrome1–48
OperaYesEdgeNo
Edge (Legacy)?Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

title 속성이 style 요소에 있으면 CSS 스타일 시트 세트가 정의됩니다. style 요소에 title 속성이 없으면 제목이 없습니다. 조상 요소의 title 속성은 style 요소에 적용되지 않습니다. style 요소가 문서 트리에 없으면 title 속성은 무시됩니다. [CSSOM]

title 속성은 style 요소에 있으며, title 속성은 link 요소에 있으며, 전역 title 속성과 다릅니다. 제목이 없는 style 블록은 부모 요소의 제목을 상속하지 않고, 제목이 없습니다.

style 요소의 자식 텍스트 내용준수하는 스타일 시트이어야 합니다.

style 요소는 암묵적으로 렌더링을 차단할 가능성이 있는 요소입니다. 이 요소는 노드 문서의 파서에 의해 생성된 경우 암묵적으로 렌더링을 차단할 가능성이 있습니다.


사용자 에이전트는 다음 조건 중 하나가 발생할 때마다 style 블록 업데이트 알고리즘을 실행해야 합니다:

style 블록 업데이트 알고리즘은 다음과 같습니다:

  1. elementstyle 요소로 지정합니다.

  2. element연결된 CSS 스타일 시트가 있으면 해당 CSS 스타일 시트를 제거합니다.

  3. element연결되지 않은 경우, 반환합니다.

  4. elementtype 속성이 존재하며 값이 빈 문자열이 아니거나 ASCII 대소문자 구분을 하지 않는 "text/css"와 일치하지 않는 경우, 반환합니다.

    특히 "text/css; charset=utf-8"과 같은 매개변수가 있는 type 값은 이 알고리즘을 일찍 반환하게 만듭니다.

  5. 요소의 인라인 동작이 콘텐츠 보안 정책에 의해 차단되어야 하는지 여부 알고리즘이 style 요소, "style", 및 style 요소의 자식 텍스트 내용을 대상으로 실행할 때 "차단됨"을 반환하는 경우, 반환합니다. [CSP]

  6. 다음 속성으로 CSS 스타일 시트를 만듭니다:

    type

    text/css

    소유 노드

    element

    미디어

    elementmedia 속성.

    이는 속성의 현재 값을 복사한 것이 아닌, (이 시점에서 부재할 수 있는) 속성에 대한 참조입니다. CSSOM은 속성이 동적으로 설정, 변경 또는 제거될 때 어떻게 되는지를 정의합니다.

    제목

    element문서 트리에 있으면 elementtitle 속성, 그렇지 않으면 빈 문자열.

    다시 말하지만, 이것은 속성에 대한 참조입니다.

    대체 플래그

    설정하지 않음.

    원점 정리 플래그

    설정됨.

    위치
    부모 CSS 스타일 시트
    소유 CSS 규칙

    null

    비활성화 플래그

    기본값으로 유지.

    CSS 규칙

    초기화되지 않음.

    이것은 맞지 않습니다. 아마도 요소의 자식 텍스트 내용을 사용해야 할 것입니다? 문제 #2997로 추적되었습니다.

  7. element스크립트 차단 스타일 시트를 기여하는 경우, element추가하고, element노드 문서스크립트 차단 스타일 시트 세트에 추가합니다.

  8. elementmedia 속성 값이 환경에 맞는 경우이며 element렌더링을 차단할 가능성이 있는 경우, element에서 렌더링을 차단합니다.

스타일 시트의 중요한 하위 리소스(있는 경우)를 얻으려는 시도가 완료되거나, 스타일 시트에 중요한 하위 리소스가 없으면 스타일 시트가 구문 분석되고 처리된 후에 사용자 에이전트는 다음 단계를 실행해야 합니다:

중요한 하위 리소스를 가져오는 것은 명확하지 않으며, 아마도 문제 #968가 가장 좋은 해결책일 것입니다. 그동안, 중요한 하위 리소스 요청style 요소가 현재 렌더링을 차단하는지 여부에 따라 설정되어야 합니다.

  1. element를 스타일 시트와 연결된 style 요소로 지정합니다.

  2. success를 true로 설정합니다.

  3. 스타일 시트의 중요한 하위 리소스를 얻으려는 시도가 어떤 이유로든 실패한 경우(DNS 오류, HTTP 404 응답, 연결이 조기에 닫힌 경우, 지원되지 않는 콘텐츠 유형 등), success를 false로 설정합니다.

    CSS 구문 분석 오류나 PNG 디코딩 오류와 같은 콘텐츠 관련 오류는 success에 영향을 미치지 않습니다.

  4. element와 다음 단계를 주어진 요소 작업을 큐에 추가합니다:

    1. success가 true이면, element에서 load라는 이름의 이벤트를 발생시킵니다.

    2. 그렇지 않으면, element에서 error라는 이름의 이벤트를 발생시킵니다.

    3. element스크립트 차단 스타일 시트를 기여하는 경우:

      1. element노드 문서스크립트 차단 스타일 시트 세트element포함하고 있는지 확인합니다.

      2. element제거하고, element노드 문서스크립트 차단 스타일 시트 세트에서 제거합니다.

    4. element에서 렌더링 차단 해제를 수행합니다.

이 요소는 해당 요소의 로드 이벤트를 지연 시켜야 하며, 스타일 시트의 노드 문서중요 하위 리소스를 모두 가져올 때까지 기다려야 합니다.

이 사양은 스타일 시스템을 명시하지 않지만 대부분의 웹 브라우저에서 CSS가 지원될 것으로 예상됩니다. [CSS]

HTMLStyleElement/media

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

mediablocking IDL 속성은 각각 동일한 이름의 해당 내용 속성을 반영해야 합니다.

LinkStyle 인터페이스도 이 요소에 의해 구현됩니다. [CSSOM]

다음 문서는 스트레스 강조 표시가 기울임체 텍스트 대신 밝은 빨간색 텍스트로 스타일링되며, 제목과 라틴어 단어는 기본 기울임체로 유지됩니다. 이는 적절한 요소를 사용하여 문서를 쉽게 다시 스타일링하는 방법을 보여줍니다.

<!DOCTYPE html>
<html lang="en-US">
 <head>
  <title>My favorite book</title>
  <style>
   body { color: black; background: white; }
   em { font-style: normal; color: red; }
  </style>
 </head>
 <body>
  <p>My <em>favorite</em> book of all time has <em>got</em> to be
  <cite>A Cat's Life</cite>. It is a book by P. Rahmel that talks
  about the <i lang="la">Felis catus</i> in modern human society.</p>
 </body>
</html>

4.2.7 스타일링과 스크립팅의 상호작용

스타일 시트가 다른 리소스를 참조하지 않은 경우(예: style 요소에 의해 제공된 내부 스타일 시트로 @import 규칙이 없는 경우), 스타일 규칙은 스크립트에서 즉시 사용할 수 있어야 합니다. 그렇지 않은 경우, 스타일 규칙은 이벤트 루프렌더링 업데이트 단계에 도달한 후에만 스크립트에서 사용할 수 있어야 합니다.

HTML 파서 또는 XML 파서의 문맥에서 document에 있는 요소 el이 다음 조건이 모두 참일 때 스크립트를 차단하는 스타일 시트에 기여합니다:

위의 규칙에 상응하는 규칙이 <?xml-stylesheet?> PI에도 적용될 것으로 예상됩니다. 그러나 이것은 아직 철저히 조사되지 않았습니다.

document는 초기에는 비어 있는 순서가 지정된 세트스크립트 차단 스타일 시트 세트를 가지고 있습니다.

document document가 다음 단계가 참이면 스크립트를 차단하는 스타일 시트가 있는 것으로 간주됩니다:

  1. 만약 document스크립트 차단 스타일 시트 세트비어 있지 않다면 true를 반환합니다.

  2. 만약 document탐색 가능한 노드가 null이라면 false를 반환합니다.

  3. containerDocumentdocument탐색 가능한 노드컨테이너 문서로 설정합니다.

  4. 만약 containerDocument가 null이 아니고 containerDocument스크립트 차단 스타일 시트 세트비어 있지 않다면 true를 반환합니다.

  5. false를 반환합니다.

document스크립트를 차단하는 스타일 시트가 없는 경우에 스크립트를 차단하는 스타일 시트가 없는 것으로 간주됩니다.

4.3 섹션

Introduction_to_HTML/Document_and_website_structure#HTML_for_structuring_content

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+

4.3.1 body 요소

Element/body

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLBodyElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
html 요소의 두 번째 요소로.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서 태그 생략:
요소가 비어 있거나 body 요소 안의 첫 번째 내용이 ASCII 공백 또는 주석이 아닌 경우, body 요소의 시작 태그를 생략할 수 있습니다. 단, meta, noscript, link, script, style, 또는 template 요소가 첫 번째 내용인 경우는 제외됩니다.
body 요소의 종료 태그body 요소 바로 뒤에 주석이 없는 경우 생략할 수 있습니다.
콘텐츠 속성:
글로벌 속성
onafterprint
onbeforeprint
onbeforeunload
onhashchange
onlanguagechange
onmessage
onmessageerror
onoffline
ononline
onpageswap
onpagehide
onpagereveal
onpageshow
onpopstate
onrejectionhandled
onstorage
onunhandledrejection
onunload
접근성 고려 사항:
저자를 위한 지침.
구현자를 위한 지침.
DOM 인터페이스:
[Exposed=Window]
interface HTMLBodyElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 더 이상 사용되지 않는 멤버도 포함합니다.
};

HTMLBodyElement 포함합니다 WindowEventHandlers;

body 요소는 문서의 내용을 나타냅니다.

준수 문서에는 하나의 body 요소만 존재합니다. document.body IDL 속성은 스크립트에 문서의 body 요소에 쉽게 접근할 수 있게 해줍니다.

일부 DOM 작업(예: 드래그 앤 드롭 모델의 일부)은 "body 요소"로 정의됩니다. 이는 용어의 정의에 따라 DOM의 특정 요소를 참조하며, 임의의 body 요소를 의미하지 않습니다.

body 요소는 이벤트 핸들러 콘텐츠 속성으로 Window 객체의 여러 이벤트 핸들러를 노출합니다. 또한 이러한 이벤트 핸들러는 이벤트 핸들러 IDL 속성을 반영합니다.

이벤트 핸들러Window 객체에서 Window-반영 body 요소 이벤트 핸들러 세트로 명명된 이벤트 핸들러를 body 요소에 노출하며, 일반적인 이벤트 핸들러를 대체합니다.

따라서, 예를 들어, 오류 이벤트가 documentbody 요소의 자식에서 버블링되면, 먼저 해당 요소의 onerror 이벤트 핸들러 콘텐츠 속성이 트리거되고, 그 다음으로 루트 html 요소의 해당 속성이 트리거됩니다. 이 이벤트는 타겟에서 body로, html로, document로, Window로 버블링되며, 이벤트 핸들러Window가 아닌 body에서 이를 감지합니다. 그러나 bodyaddEventListener()를 사용하여 추가된 일반 이벤트 리스너는 이벤트가 body를 통해 버블링할 때 실행되며, Window 객체에 도달할 때는 실행되지 않습니다.

이 페이지는 사용자가 온라인 상태인지 여부를 표시하는 표시기를 업데이트합니다:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Online or offline?</title>
  <script>
   function update(online) {
     document.getElementById('status').textContent =
       online ? 'Online' : 'Offline';
   }
  </script>
 </head>
 <body ononline="update(true)"
       onoffline="update(false)"
       onload="update(navigator.onLine)">
  <p>You are: <span id="status">(Unknown)</span></p>
 </body>
</html>

4.3.2 article 요소

Element/article

모든 최신 엔진에서 지원됨.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+
카테고리:
플로우 콘텐츠.
섹션 콘텐츠.
확실한 콘텐츠.
이 요소를 사용할 수 있는 문맥:
섹션 콘텐츠가 예상되는 곳.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서 태그 생략:
어느 태그도 생략할 수 없음.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
저자를 위한 지침.
구현자를 위한 지침.
DOM 인터페이스:
HTMLElement 사용.

article 요소는 문서, 페이지, 애플리케이션 또는 사이트 내에서 완결된 또는 자립적인 구성을 나타내며, 원칙적으로 독립적으로 배포되거나 재사용될 수 있습니다. 예시로는 포럼 게시물, 잡지나 신문 기사, 블로그 글, 사용자 제출 댓글, 대화형 위젯 또는 장치, 또는 기타 독립적인 콘텐츠 항목이 있습니다.

article 요소가 중첩될 때, 내부 article 요소는 원칙적으로 외부 기사와 관련된 기사를 나타냅니다. 예를 들어, 사용자 제출 댓글을 허용하는 사이트의 블로그 글은 댓글을 블로그 글에 대한 article 요소 내에 중첩된 article 요소로 나타낼 수 있습니다.

article 요소와 관련된 저자 정보(예를 들어 address 요소)는 중첩된 article 요소에는 적용되지 않습니다.

특히 콘텐츠를 배포하려는 경우 article 요소는 Atom의 entry 요소와 목적이 유사합니다. [ATOM]

schema.org 마이크로데이터 어휘를 사용하여 article 요소에 대한 출판 날짜를 제공할 수 있습니다. CreativeWork 서브타입 중 하나를 사용하여 제공합니다.

페이지의 주요 콘텐츠(푸터, 헤더, 탐색 블록 및 사이드바 제외)가 하나의 자립적인 구성인 경우, 해당 콘텐츠는 article로 표시될 수 있지만, 이 경우 기술적으로 중복됩니다(단일 문서이므로 페이지가 단일 구성임이 자명하기 때문입니다).

이 예제는 article 요소를 사용하는 블로그 게시물과 몇 가지 schema.org 주석을 보여줍니다:

<article itemscope itemtype="http://schema.org/BlogPosting">
 <header>
  <h2 itemprop="headline">The Very First Rule of Life</h2>
  <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p>
  <link itemprop="url" href="?comments=0">
 </header>
 <p>If there's a microphone anywhere near you, assume it's hot and
 sending whatever you're saying to the world. Seriously.</p>
 <p>...</p>
 <footer>
  <a itemprop="discussionUrl" href="?comments=1">Show comments...</a>
 </footer>
</article>

다음은 동일한 블로그 게시물이지만 일부 댓글을 표시한 것입니다:

<article itemscope itemtype="http://schema.org/BlogPosting">
 <header>
  <h2 itemprop="headline">The Very First Rule of Life</h2>
  <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p>
  <link itemprop="url" href="?comments=0">
 </header>
 <p>If there's a microphone anywhere near you, assume it's hot and
 sending whatever you're saying to the world. Seriously.</p>
 <p>...</p>
 <section>
  <h1>Comments</h1>
  <article itemprop="comment" itemscope itemtype="http://schema.org/Comment" id="c1">
   <link itemprop="url" href="#c1">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">George Washington</span>
    </span></p>
    <p><time itemprop="dateCreated" datetime="2009-10-10">15 minutes ago</time></p>
   </footer>
   <p>Yeah! Especially when talking about your lobbyist friends!</p>
  </article>
  <article itemprop="comment" itemscope itemtype="http://schema.org/Comment" id="c2">
   <link itemprop="url" href="#c2">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">George Hammond</span>
    </span></p>
    <p><time itemprop="dateCreated" datetime="2009-10-10">5 minutes ago</time></p>
   </footer>
   <p>Hey, you have the same first name as me.</p>
  </article>
 </section>
</article>

각 댓글에 대한 정보(작성자와 작성 시간 등)를 제공하기 위해 footer 요소를 사용하는 것을 주목하세요. footer 요소는 적절한 경우, 이 예시에서처럼 해당 섹션의 시작 부분에 나타날 수도 있습니다. (이 경우에 header를 사용하는 것도 잘못된 것은 아닙니다. 이는 주로 작성자의 선호에 따라 다릅니다.)

이 예시에서는 article 요소들이 포털 페이지에 위젯을 호스팅하기 위해 사용됩니다. 위젯은 특정 스타일링과 스크립팅된 동작을 얻기 위해 커스텀 내장 요소로 구현되었습니다.

<!DOCTYPE HTML>
<html lang=en>
<title>eHome Portal</title>
<script src="/scripts/widgets.js"></script>
<link rel=stylesheet href="/styles/main.css">
<article is="stock-widget">
 <h2>Stocks</h2>
 <table>
  <thead> <tr> <th> Stock <th> Value <th> Delta
  <tbody> <template> <tr> <td> <td> <td> </template>
 </table>
 <p> <input type=button value="Refresh" onclick="this.parentElement.refresh()">
</article>
<article is="news-widget">
 <h2>News</h2>
 <ul>
  <template>
   <li>
    <p><img> <strong></strong>
    <p>
  </template>
 </ul>
 <p> <input type=button value="Refresh" onclick="this.parentElement.refresh()">
</article>

4.3.3 section 요소

Element/section

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (레거시)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+
카테고리:
플로우 콘텐츠.
섹션 콘텐츠.
눈에 보이는 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
섹션 콘텐츠가 예상되는 곳에서 사용 가능.
콘텐츠 모델:
플로우 콘텐츠.
텍스트/HTML에서 태그 생략:
태그를 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
작성자를 위한 가이드라인.
구현자를 위한 가이드라인.
DOM 인터페이스:
HTMLElement을 사용.

section 요소는 문서나 애플리케이션의 일반적인 섹션을 나타냅니다. 이 컨텍스트에서 섹션은 일반적으로 제목이 있는 콘텐츠의 주제별 그룹화입니다.

섹션의 예로는 챕터, 탭이 있는 대화 상자의 여러 탭 페이지 또는 논문의 번호가 매겨진 섹션이 있습니다. 웹사이트의 홈페이지는 소개, 뉴스 항목, 연락처 정보 등으로 나눌 수 있습니다.

작성자는 article 요소의 콘텐츠를 배포하는 것이 합리적일 때 section 요소 대신 사용할 것을 권장합니다.

section 요소는 일반적인 컨테이너 요소가 아닙니다. 요소가 스타일링 목적이나 스크립팅 편의를 위해서만 필요한 경우, 작성자는 div 요소를 사용하는 것이 좋습니다. 일반적인 규칙은 section 요소가 적합한 경우는 해당 요소의 콘텐츠가 문서의 개요에 명시적으로 나열되는 경우에만 해당된다는 것입니다.

다음 예시는 사과에 관한 기사(더 큰 웹 페이지의 일부)로, 두 개의 짧은 섹션을 포함하고 있습니다.

<article>
 <hgroup>
  <h2>Apples</h2>
  <p>Tasty, delicious fruit!</p>
 </hgroup>
 <p>The apple is the pomaceous fruit of the apple tree.</p>
 <section>
  <h3>Red Delicious</h3>
  <p>These bright red apples are the most common found in many
  supermarkets.</p>
 </section>
 <section>
  <h3>Granny Smith</h3>
  <p>These juicy, green apples make a great filling for
  apple pies.</p>
 </section>
</article>

다음은 졸업 프로그램의 예로, 졸업자 명단과 행사 설명 두 개의 섹션으로 구성되어 있습니다. (이 예시의 마크업은 요소 간 공백을 최소화하기 위해 가끔 사용되는 비정형 스타일을 포함하고 있습니다.)

<!DOCTYPE Html>
<Html Lang=En
 ><Head
   ><Title
     >Graduation Ceremony Summer 2022</Title
   ></Head
 ><Body
   ><H1
     >Graduation</H1
   ><Section
     ><H2
       >Ceremony</H2
     ><P
       >Opening Procession</P
     ><P
       >Speech by Valedictorian</P
     ><P
       >Speech by Class President</P
     ><P
       >Presentation of Diplomas</P
     ><P
       >Closing Speech by Headmaster</P
   ></Section
   ><Section
     ><H2
       >Graduates</H2
     ><Ul
       ><Li
         >Molly Carpenter</Li
       ><Li
         >Anastasia Luccio</Li
       ><Li
         >Ebenezar McCoy</Li
       ><Li
         >Karrin Murphy</Li
       ><Li
         >Thomas Raith</Li
       ><Li
         >Susan Rodriguez</Li
     ></Ul
   ></Section
 ></Body
></Html>

이 예시에서는 책 저자가 몇몇 섹션을 장(chapters)으로, 몇몇을 부록(appendices)으로 표시하였으며, CSS를 사용하여 이 두 종류의 섹션에 속하는 헤더를 다르게 스타일링하고 있습니다.

<style>
 section { border: double medium; margin: 2em; }
 section.chapter h2 { font: 2em Roboto, Helvetica Neue, sans-serif; }
 section.appendix h2 { font: small-caps 2em Roboto, Helvetica Neue, sans-serif; }
</style>
<header>
 <hgroup>
  <h1>My Book</h1>
  <p>A sample with not much content</p>
 </hgroup>
 <p><small>Published by Dummy Publicorp Ltd.</small></p>
</header>
<section class="chapter">
 <h2>My First Chapter</h2>
 <p>This is the first of my chapters. It doesn't say much.</p>
 <p>But it has two paragraphs!</p>
</section>
<section class="chapter">
 <h2>It Continues: The Second Chapter</h2>
 <p>Bla dee bla, dee bla dee bla. Boom.</p>
</section>
<section class="chapter">
 <h2>Chapter Three: A Further Example</h2>
 <p>It's not like a battle between brightness and earthtones would go
 unnoticed.</p>
 <p>But it might ruin my story.</p>
</section>
<section class="appendix">
 <h2>Appendix A: Overview of Examples</h2>
 <p>These are demonstrations.</p>
</section>
<section class="appendix">
 <h2>Appendix B: Some Closing Remarks</h2>
 <p>Hopefully this long example shows that you <em>can</em> style
 sections, so long as they are used to indicate actual sections.</p>
</section>

4.3.4 nav 요소

Element/nav

현재 모든 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+
카테고리:
플로우 콘텐츠.
섹셔닝 콘텐츠.
유의미한 콘텐츠.
이 요소를 사용할 수 있는 맥락:
섹셔닝 콘텐츠가 예상되는 곳.
콘텐츠 모델:
플로우 콘텐츠.
텍스트/HTML에서 태그 생략:
어느 태그도 생략할 수 없음.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
저자를 위한 가이드.
구현자를 위한 가이드.
DOM 인터페이스:
HTMLElement을 사용함.

nav 요소는 페이지 내에서 다른 페이지로 또는 페이지 내 다른 부분으로 연결하는 링크가 포함된 섹션을 나타냅니다.

모든 링크 그룹이 nav 요소 내에 있을 필요는 없습니다. 이 요소는 주로 주요 탐색 블록을 포함하는 섹션을 대상으로 합니다. 특히, 사이트의 푸터에 서비스 약관, 홈페이지, 저작권 페이지 등의 짧은 링크 목록이 있는 경우가 일반적입니다. 이러한 경우에는 footer 요소만으로도 충분하며, nav 요소를 사용할 수는 있지만, 보통은 불필요합니다.

화면 읽기 장치와 같은 사용자 에이전트는 내비게이션 정보를 초기 렌더링에서 생략하거나 요청 시 제공할 수 있습니다. 이러한 요소는 페이지에서 건너뛸 콘텐츠를 식별하거나 필요에 따라 정보를 즉시 제공하는 데 도움이 될 수 있습니다.

다음 예에서 두 개의 nav 요소가 있습니다. 하나는 사이트의 주요 탐색을 위한 것이고, 다른 하나는 페이지 자체의 부차적인 탐색을 위한 것입니다.

<body>
 <h1>The Wiki Center Of Exampland</h1>
 <nav>
  <ul>
   <li><a href="/">Home</a></li>
   <li><a href="/events">Current Events</a></li>
   ...more...
  </ul>
 </nav>
 <article>
  <header>
   <h2>Demos in Exampland</h2>
   <p>Written by A. N. Other.</p>
  </header>
  <nav>
   <ul>
    <li><a href="#public">Public demonstrations</a></li>
    <li><a href="#destroy">Demolitions</a></li>
    ...more...
   </ul>
  </nav>
  <div>
   <section id="public">
    <h2>Public demonstrations</h2>
    <p>...more...</p>
   </section>
   <section id="destroy">
    <h2>Demolitions</h2>
    <p>...more...</p>
   </section>
   ...more...
  </div>
  <footer>
   <p><a href="?edit">Edit</a> | <a href="?delete">Delete</a> | <a href="?Rename">Rename</a></p>
  </footer>
 </article>
 <footer>
  <p><small>© copyright 1998 Exampland Emperor</small></p>
 </footer>
</body>

다음 예에서는 페이지에 여러 링크가 있지만, 그중 하나만 내비게이션 섹션으로 간주됩니다.

<body itemscope itemtype="http://schema.org/Blog">
 <header>
  <h1>Wake up sheeple!</h1>
  <p><a href="news.html">News</a> -
     <a href="blog.html">Blog</a> -
     <a href="forums.html">Forums</a></p>
  <p>Last Modified: <span itemprop="dateModified">2009-04-01</span></p>
  <nav>
   <h2>Navigation</h2>
   <ul>
    <li><a href="articles.html">Index of all articles</a></li>
    <li><a href="today.html">Things sheeple need to wake up for today</a></li>
    <li><a href="successes.html">Sheeple we have managed to wake</a></li>
   </ul>
  </nav>
 </header>
 <main>
  <article itemprop="blogPosts" itemscope itemtype="http://schema.org/BlogPosting">
   <header>
    <h2 itemprop="headline">My Day at the Beach</h2>
   </header>
   <div itemprop="articleBody">
    <p>Today I went to the beach and had a lot of fun.</p>
    ...more content...
   </div>
   <footer>
    <p>Posted <time itemprop="datePublished" datetime="2009-10-10">Thursday</time>.</p>
   </footer>
  </article>
  ...more blog posts...
 </main>
 <footer>
  <p>Copyright ©
   <span itemprop="copyrightYear">2010</span>
   <span itemprop="copyrightHolder">The Example Company</span>
  </p>
  <p><a href="about.html">About</a> -
     <a href="policy.html">Privacy Policy</a> -
     <a href="contact.html">Contact Us</a></p>
 </footer>
</body>

위 예에서 블로그 게시물의 발행 날짜와 기타 메타데이터를 제공하기 위해 schema.org 어휘를 사용하는 마이크로데이터 주석도 볼 수 있습니다.

nav 요소는 반드시 목록을 포함해야 하는 것은 아니며, 다른 종류의 콘텐츠도 포함할 수 있습니다. 이 내비게이션 블록에서는 링크가 산문 형태로 제공됩니다:

<nav>
 <h1>Navigation</h1>
 <p>You are on my home page. To the north lies <a href="/blog">my
 blog</a>, from whence the sounds of battle can be heard. To the east
 you can see a large mountain, upon which many <a
 href="/school">school papers</a> are littered. Far up thus mountain
 you can spy a little figure who appears to be me, desperately
 scribbling a <a href="/school/thesis">thesis</a>.</p>
 <p>To the west are several exits. One fun-looking exit is labeled <a
 href="https://games.example.com/">"games"</a>. Another more
 boring-looking exit is labeled <a
 href="https://isp.example.net/">ISP™</a>.</p>
 <p>To the south lies a dark and dank <a href="/about">contacts
 page</a>. Cobwebs cover its disused entrance, and at one point you
 see a rat run quickly out of the page.</p>
</nav>

이 예시에서는 nav가 이메일 애플리케이션에서 사용되어 사용자가 폴더를 전환할 수 있도록 합니다:

<p><input type=button value="Compose" onclick="compose()"></p>
<nav>
 <h1>Folders</h1>
 <ul>
  <li> <a href="/inbox" onclick="return openFolder(this.href)">Inbox</a> <span class=count></span>
  <li> <a href="/sent" onclick="return openFolder(this.href)">Sent</a>
  <li> <a href="/drafts" onclick="return openFolder(this.href)">Drafts</a>
  <li> <a href="/trash" onclick="return openFolder(this.href)">Trash</a>
  <li> <a href="/customers" onclick="return openFolder(this.href)">Customers</a>
 </ul>
</nav>

4.3.5 aside 요소

Element/aside

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+
카테고리:
흐름 콘텐츠.
구획 콘텐츠.
명확한 콘텐츠.
이 요소를 사용할 수 있는 맥락:
구획 콘텐츠가 예상되는 곳.
콘텐츠 모델:
흐름 콘텐츠.
태그 생략:
두 태그 모두 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement 사용.

aside 요소는 페이지의 일부분을 나타내며, 해당 요소 주위의 콘텐츠와 간접적으로 관련된 콘텐츠로 구성되며, 해당 콘텐츠와는 분리된 것으로 간주될 수 있습니다. 이러한 구획은 인쇄된 타이포그래피에서 종종 사이드바로 표현됩니다.

이 요소는 인용구나 사이드바와 같은 타이포그래피 효과, 광고, nav 요소 그룹, 페이지의 주요 콘텐츠와 별개로 간주되는 기타 콘텐츠에 사용할 수 있습니다.

단순히 괄호 안의 내용을 나타내기 위해 aside 요소를 사용하는 것은 적절하지 않습니다. 이들은 문서의 주요 흐름의 일부로 간주되기 때문입니다.

다음 예시는 유럽에 대한 훨씬 긴 뉴스 기사에서 스위스에 대한 배경 정보를 표시하기 위해 aside가 사용되는 방식을 보여줍니다.

<aside>
 <h2>Switzerland</h2>
 <p>Switzerland, a land-locked country in the middle of geographic
 Europe, has not joined the geopolitical European Union, though it is
 a signatory to a number of European treaties.</p>
</aside>

다음 예시는 더 긴 기사에서 인용문을 마크업하기 위해 aside가 사용되는 방식을 보여줍니다.

...

<p>He later joined a large company, continuing on the same work.
<q>I love my job. People ask me what I do for fun when I'm not at
work. But I'm paid to do my hobby, so I never know what to
answer. Some people wonder what they would do if they didn't have to
work... but I know what I would do, because I was unemployed for a
year, and I filled that time doing exactly what I do now.</q></p>

<aside>
 <q>People ask me what I do for fun when I'm not at work. But I'm
 paid to do my hobby, so I never know what to answer.</q>
</aside>

<p>Of course his work — or should that be hobby? —
isn't his only passion. He also enjoys other pleasures.</p>

...

다음 발췌문은 블로그롤과 블로그의 기타 사이드 콘텐츠에 대해 aside를 사용하는 방법을 보여줍니다:

<body>
 <header>
  <h1>My wonderful blog</h1>
  <p>My tagline</p>
 </header>
 <aside>
  <!-- this aside contains two sections that are tangentially related
  to the page, namely, links to other blogs, and links to blog posts
  from this blog -->
  <nav>
   <h2>My blogroll</h2>
   <ul>
    <li><a href="https://blog.example.com/">Example Blog</a>
   </ul>
  </nav>
  <nav>
   <h2>Archives</h2>
   <ol reversed>
    <li><a href="/last-post">My last post</a>
    <li><a href="/first-post">My first post</a>
   </ol>
  </nav>
 </aside>
 <aside>
  <!-- this aside is tangentially related to the page also, it
  contains twitter messages from the blog author -->
  <h1>Twitter Feed</h1>
  <blockquote cite="https://twitter.example.net/t31351234">
   I'm on vacation, writing my blog.
  </blockquote>
  <blockquote cite="https://twitter.example.net/t31219752">
   I'm going to go on vacation soon.
  </blockquote>
 </aside>
 <article>
  <!-- this is a blog post -->
  <h2>My last post</h2>
  <p>This is my last post.</p>
  <footer>
   <p><a href="/last-post" rel=bookmark>Permalink</a>
  </footer>
 </article>
 <article>
  <!-- this is also a blog post -->
  <h2>My first post</h2>
  <p>This is my first post.</p>
  <aside>
   <!-- this aside is about the blog post, since it's inside the
   <article> element; it would be wrong, for instance, to put the
   blogroll here, since the blogroll isn't really related to this post
   specifically, only to the page as a whole -->
   <h2>Posting</h2>
   <p>While I'm thinking about it, I wanted to say something about
   posting. Posting is fun!</p>
  </aside>
  <footer>
   <p><a href="/first-post" rel=bookmark>Permalink</a>
  </footer>
 </article>
 <footer>
  <p><a href="/archives">Archives</a> -
   <a href="/about">About me</a> -
   <a href="/copyright">Copyright</a></p>
 </footer>
</body>

4.3.6 h1, h2, h3, h4, h5, 및 h6 요소들

요소/Heading_Elements

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소/Heading_Elements

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소/Heading_Elements

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소/Heading_Elements

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소/Heading_Elements

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소/Heading_Elements

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLHeadingElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
헤딩 콘텐츠.
실체 콘텐츠.
이 요소를 사용할 수 있는 문맥:
hgroup 요소의 자식으로.
헤딩 콘텐츠가 예상되는 곳에서.
콘텐츠 모델:
구문 콘텐츠.
태그 생략 (text/html):
태그 생략 불가능.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
작성자를 위한 가이드.
구현자를 위한 가이드.
DOM 인터페이스:
[Exposed=Window]
interface HTMLHeadingElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 구식 멤버도 포함됨
};

이 요소들은 그들의 섹션에 대한 제목을 나타냅니다.

이 요소들의 의미와 정의는 제목과 개요 섹션에서 정의됩니다.

이 요소들은 이름에 있는 숫자로 주어진 제목 수준을 가지고 있습니다. 제목 수준은 중첩된 섹션의 레벨과 대응됩니다. h1 요소는 최상위 섹션을 위한 것이고, h2 는 하위 섹션을 위한 것이며, h3 는 하위의 하위 섹션을 위한 것이며, 계속해서 이어집니다.

각각의 문서 개요(제목 및 섹션 구조)와 관련하여, 이 두 스니펫은 의미적으로 동일합니다:

<body>
<h1>Let's call it a draw(ing surface)</h1>
<h2>Diving in</h2>
<h2>Simple shapes</h2>
<h2>Canvas coordinates</h2>
<h3>Canvas coordinates diagram</h3>
<h2>Paths</h2>
</body>
<body>
 <h1>Let's call it a draw(ing surface)</h1>
 <section>
  <h2>Diving in</h2>
 </section>
 <section>
  <h2>Simple shapes</h2>
 </section>
 <section>
  <h2>Canvas coordinates</h2>
  <section>
   <h3>Canvas coordinates diagram</h3>
  </section>
 </section>
 <section>
  <h2>Paths</h2>
 </section>
</body>

작성자는 전자의 스타일을 간결함 때문에 선호할 수 있고, 후자의 스타일을 추가적인 스타일링 훅 때문에 선호할 수 있습니다. 어느 것이 더 좋은지는 순전히 선호하는 작성 스타일의 문제입니다.

4.3.7 hgroup 요소

요소/hgroup

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android2.2+Samsung Internet?Opera Android11.1+
카테고리:
플로우 콘텐츠.
헤딩 콘텐츠.
실체 콘텐츠.
이 요소를 사용할 수 있는 문맥:
헤딩 콘텐츠가 예상되는 곳에서.
콘텐츠 모델:
하나 이상의 p 요소들로 시작하고, 그 다음에 하나의 h1, h2, h3, h4, h5, 또는 h6 요소가 있으며, 그 다음에 선택적으로 스크립트 지원 요소와 섞일 수 있는 하나 이상의 p 요소들이 옵니다.
태그 생략 (text/html):
태그 생략 불가능.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
작성자를 위한 가이드.
구현자를 위한 가이드.
DOM 인터페이스:
HTMLElement을 사용.

hgroup 요소는 제목과 관련된 콘텐츠를 나타냅니다. 이 요소는 h1h6 요소를 하나 이상의 p 요소와 함께 그룹화하여, 부제목, 대체 제목 또는 태그라인을 나타내는 콘텐츠를 포함할 수 있습니다.

hgroup 요소에 포함된 유효한 제목의 예가 있습니다.

<hgroup>
 <h1>The reality dysfunction</h1>
 <p>Space is not the only void</p>
</hgroup>
<hgroup>
 <h1>Dr. Strangelove</h1>
 <p>Or: How I Learned to Stop Worrying and Love the Bomb</p>
</hgroup>

4.3.8 header 요소

요소/header

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+
카테고리:
플로우 콘텐츠.
실체 콘텐츠.
이 요소를 사용할 수 있는 문맥:
플로우 콘텐츠가 예상되는 곳에서.
콘텐츠 모델:
플로우 콘텐츠, 하지만 하위 요소로 header 또는 footer 요소가 없어야 합니다.
태그 생략 (text/html):
태그 생략 불가능.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
상위 요소에 섹션 콘텐츠 요소가 있는 경우: 작성자를 위한 가이드; 구현자를 위한 가이드.
그 외의 경우: 작성자를 위한 가이드; 구현자를 위한 가이드.
DOM 인터페이스:
HTMLElement을 사용.

header 요소는 소개 또는 탐색 도구의 그룹을 나타냅니다.

header 요소는 일반적으로 제목 (h1h6 요소 또는 hgroup 요소)을 포함하도록 되어 있지만, 이는 필수가 아닙니다. header 요소는 또한 섹션의 목차, 검색 양식 또는 관련 로고를 감싸는 데 사용할 수 있습니다.

다음은 몇 가지 샘플 헤더입니다. 첫 번째 예시는 게임용 헤더입니다:

<header>
 <p>Welcome to...</p>
 <h1>Voidwars!</h1>
</header>

다음 스니펫은 요소가 사양의 헤더를 마크업하는 데 어떻게 사용될 수 있는지를 보여줍니다:

<header>
 <hgroup>
  <h1>Fullscreen API</h1>
  <p>Living Standard — Last Updated 19 October 2015<p>
 </hgroup>
 <dl>
  <dt>Participate:</dt>
  <dd><a href="https://github.com/whatwg/fullscreen">GitHub whatwg/fullscreen</a></dd>
  <dt>Commits:</dt>
  <dd><a href="https://github.com/whatwg/fullscreen/commits">GitHub whatwg/fullscreen/commits</a></dd>
 </dl>
</header>

header 요소는 섹션 콘텐츠가 아닙니다. 이 요소는 새로운 섹션을 도입하지 않습니다.

이 예에서, 페이지는 h1 요소에 의해 주어진 페이지 제목과, h2 요소들에 의해 주어진 두 개의 하위 섹션을 가지고 있습니다. header 요소 이후의 콘텐츠는 여전히 header 요소에서 시작된 마지막 하위 섹션의 일부입니다. 이는 header 요소가 개요 알고리즘에 참여하지 않기 때문입니다.

<body>
 <header>
  <h1>Little Green Guys With Guns</h1>
  <nav>
   <ul>
    <li><a href="/games">Games</a>
    <li><a href="/forum">Forum</a>
    <li><a href="/download">Download</a>
   </ul>
  </nav>
  <h2>Important News</h2> <!-- this starts a second subsection -->
  <!-- this is part of the subsection entitled "Important News" -->
  <p>To play today's games you will need to update your client.</p>
  <h2>Games</h2> <!-- this starts a third subsection -->
 </header>
 <p>You have three active games:</p>
 <!-- this is still part of the subsection entitled "Games" -->
 ...

요소/footer

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11.1+
카테고리:
플로우 콘텐츠.
실체 콘텐츠.
이 요소를 사용할 수 있는 문맥:
플로우 콘텐츠가 예상되는 곳에서.
콘텐츠 모델:
플로우 콘텐츠, 하지만 하위 요소로 header 또는 footer 요소가 없어야 합니다.
태그 생략 (text/html):
태그 생략 불가능.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
상위 요소에 섹션 콘텐츠 요소가 있는 경우: 작성자를 위한 가이드; 구현자를 위한 가이드.
그 외의 경우: 작성자를 위한 가이드; 구현자를 위한 가이드.
DOM 인터페이스:
HTMLElement을 사용.

footer 요소는 가장 가까운 상위 섹션 콘텐츠 요소나 그러한 상위 요소가 없을 경우 body 요소에 대한 푸터를 나타냅니다. 푸터에는 일반적으로 섹션의 작성자에 대한 정보, 관련 문서 링크, 저작권 정보 등이 포함됩니다.

footer 요소가 전체 섹션을 포함하는 경우, 그것은 부록, 인덱스, 긴 판권 페이지, 상세한 라이선스 계약서, 또는 이와 유사한 내용을 나타냅니다.

섹션의 작성자 또는 편집자에 대한 연락처 정보는 address 요소에 속하며, 이는 footer 내부에 있을 수 있습니다. 작성자에 대한 정보나 기타 정보는 header 또는 footer에 배치할 수 있습니다(또는 그 어느 곳에도 배치하지 않을 수 있습니다). 이 요소들의 주요 목적은 단지 작성자가 유지 관리 및 스타일링하기 쉬운 자기 설명적인 마크업을 작성할 수 있도록 돕는 것입니다. 이 요소들은 작성자에게 특정한 구조를 강요하려는 의도가 아닙니다.

푸터는 보통 섹션의 에 나타나지만, 반드시 그렇게 해야 하는 것은 아닙니다.

상위에 섹션 콘텐츠 요소가 없을 경우, 페이지 전체에 적용됩니다.

footer 요소는 자체적으로 섹션 콘텐츠가 아닙니다. 이 요소는 새로운 섹션을 도입하지 않습니다.

여기에 동일한 내용으로 상단과 하단에 두 개의 푸터가 있는 페이지가 있습니다:

<body>
 <footer><a href="../">Back to index...</a></footer>
 <hgroup>
  <h1>Lorem ipsum</h1>
  <p>The ipsum of all lorems</p>
 </hgroup>
 <p>A dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
 veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
 ea commodo consequat. Duis aute irure dolor in reprehenderit in
 voluptate velit esse cillum dolore eu fugiat nulla
 pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
 culpa qui officia deserunt mollit anim id est laborum.</p>
 <footer><a href="../">Back to index...</a></footer>
</body>

다음은 footer 요소가 사이트 전체의 푸터와 섹션 푸터 모두에 사용된 예시입니다.

<!DOCTYPE HTML>
<HTML LANG="en"><HEAD>
<TITLE>The Ramblings of a Scientist</TITLE>
<BODY>
<H1>The Ramblings of a Scientist</H1>
<ARTICLE>
 <H1>Episode 15</H1>
 <VIDEO SRC="/fm/015.ogv" CONTROLS PRELOAD>
  <P><A HREF="/fm/015.ogv">Download video</A>.</P>
 </VIDEO>
 <FOOTER> <!-- footer for article -->
  <P>Published <TIME DATETIME="2009-10-21T18:26-07:00">on 2009/10/21 at 6:26pm</TIME></P>
 </FOOTER>
</ARTICLE>
<ARTICLE>
 <H1>My Favorite Trains</H1>
 <P>I love my trains. My favorite train of all time is a Köf.</P>
 <P>It is fun to see them pull some coal cars because they look so
 dwarfed in comparison.</P>
 <FOOTER> <!-- footer for article -->
  <P>Published <TIME DATETIME="2009-09-15T14:54-07:00">on 2009/09/15 at 2:54pm</TIME></P>
 </FOOTER>
</ARTICLE>
<FOOTER> <!-- site wide footer -->
 <NAV>
  <P><A HREF="/credits.html">Credits</A><A HREF="/tos.html">Terms of Service</A><A HREF="/index.html">Blog Index</A></P>
 </NAV>
 <P>Copyright © 2009 Gordon Freeman</P>
</FOOTER>
</BODY>
</HTML>

일부 사이트 디자인에는 "fat footers"라고 불리는 푸터가 포함되어 있습니다. 이러한 푸터는 이미지, 다른 기사로의 링크, 피드백을 보낼 수 있는 페이지로의 링크, 특별 제안 등 많은 자료를 포함하고 있어, 어떤 면에서는 푸터에 "전체 첫 페이지"가 있는 것과 같습니다.

이 조각은 "fat footer"가 있는 사이트 페이지의 하단을 보여줍니다:

...
 <footer>
  <nav>
   <section>
    <h1>Articles</h1>
    <p><img src="images/somersaults.jpeg" alt=""> Go to the gym with
    our somersaults class! Our teacher Jim takes you through the paces
    in this two-part article. <a href="articles/somersaults/1">Part
    1</a> · <a href="articles/somersaults/2">Part 2</a></p>
    <p><img src="images/kindplus.jpeg"> Tired of walking on the edge of
    a clif<!-- sic -->? Our guest writer Lara shows you how to bumble
    your way through the bars. <a href="articles/kindplus/1">Read
    more...</a></p>
    <p><img src="images/crisps.jpeg"> The chips are down, now all
    that's left is a potato. What can you do with it? <a
    href="articles/crisps/1">Read more...</a></p>
   </section>
   <ul>
    <li> <a href="/about">About us...</a>
    <li> <a href="/feedback">Send feedback!</a>
    <li> <a href="/sitemap">Sitemap</a>
   </ul>
  </nav>
  <p><small>Copyright © 2015 The Snacker —
  <a href="/tos">Terms of Service</a></small></p>
 </footer>
</body>

4.3.10 address 요소

요소/address

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
실체 콘텐츠.
이 요소를 사용할 수 있는 문맥:
플로우 콘텐츠가 예상되는 곳에서.
콘텐츠 모델:
플로우 콘텐츠, 하지만 하위 요소로 헤딩 콘텐츠, 섹션 콘텐츠, header, footer, 또는 address 요소가 없어야 합니다.
태그 생략 (text/html):
태그 생략 불가능.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
작성자를 위한 가이드.
구현자를 위한 가이드.
DOM 인터페이스:
HTMLElement을 사용.

address 요소는 가장 가까운 상위 article 또는 body 요소의 연락처 정보를 나타냅니다. 만약 그것이 body 요소라면, 이 연락처 정보는 문서 전체에 적용됩니다.

예를 들어, W3C 웹사이트의 HTML 관련 페이지에는 다음과 같은 연락처 정보가 포함될 수 있습니다:

<ADDRESS>
 <A href="../People/Raggett/">Dave Raggett</A>,
 <A href="../People/Arnaud/">Arnaud Le Hors</A>,
 contact persons for the <A href="Activity">W3C HTML Activity</A>
</ADDRESS>

address 요소는 그 주소가 실제로 관련된 연락처 정보가 아닌 경우 임의의 주소(예: 우편 주소)를 나타내는 데 사용해서는 안 됩니다. (우편 주소를 마크업하는 데는 p 요소가 적절한 요소입니다.)

address 요소에는 연락처 정보 이외의 정보가 포함되어서는 안 됩니다.

예를 들어, 다음은 address 요소의 비준수 사용 사례입니다:

<ADDRESS>Last Modified: 1999/12/24 23:37:50</ADDRESS>

일반적으로 address 요소는 다른 정보와 함께 footer 요소에 포함됩니다.

노드 node의 연락처 정보는 다음 목록에서 처음 해당하는 항목으로 정의된 address 요소들의 집합입니다:

만약 nodearticle 요소라면
만약 nodebody 요소라면

연락처 정보는 node를 상위 요소로 가지며 node의 하위 요소가 아닌 다른 body 또는 article 요소를 상위 요소로 가지지 않는 모든 address 요소들로 구성됩니다.

만약 nodearticle 요소를 상위 요소로 가진다면
만약 nodebody 요소를 상위 요소로 가진다면

node의 연락처 정보는 가장 가까운 article 또는 body 요소 상위 요소의 연락처 정보와 동일합니다.

만약 node노드 문서body 요소를 가진다면

node의 연락처 정보는 documentbody 요소의 연락처 정보와 동일합니다.

그 외의 경우

node에 대한 연락처 정보가 없습니다.

사용자 에이전트는 사용자가 노드의 연락처 정보를 노출하거나, 섹션의 연락처 정보를 기반으로 섹션을 인덱싱하는 등의 다른 목적으로 사용할 수 있습니다.

이 예제에서는 푸터에 연락처 정보와 저작권 고지가 포함되어 있습니다.

<footer>
 <address>
  For more details, contact
  <a href="mailto:js@example.com">John Smith</a>.
 </address>
 <p><small>© copyright 2038 Example Corp.</small></p>
</footer>

4.3.11 제목과 개요

h1h6 요소는 요소 이름의 숫자에 의해 주어지는 제목 수준을 가집니다.

이 요소들은 제목나타냅니다. 제목제목 수준이 낮을수록, 해당 제목이 갖는 상위 섹션의 수가 적습니다.

개요는 문서의 모든 제목트리 순서로 포함합니다.

개요는 예를 들어, 목차를 생성할 때와 같이 문서 개요를 생성하는 데 사용되어야 합니다. 인터랙티브한 목차를 만들 때, 항목은 사용자를 관련 제목으로 이동시켜야 합니다.

문서에 하나 이상의 제목이 있는 경우, 개요 내의 적어도 하나의 제목은 1의 제목 수준을 가져야 합니다.

또한, 개요에서 다른 제목을 따르는 각 제목은 선행 lead제목 수준보다 낮거나, 같거나, 1만큼 높은 제목 수준을 가져야 합니다.

다음 예시는 비준수 사례입니다:

<body>
 <h1>Apples</h1>
 <p>Apples are fruit.</p>
 <section>
  <h3>Taste</h3>
  <p>They taste lovely.</p>
 </section>
</body>

다음과 같이 작성하면 준수하게 됩니다:

<body>
 <h1>Apples</h1>
 <p>Apples are fruit.</p>
 <section>
  <h2>Taste</h2>
  <p>They taste lovely.</p>
 </section>
</body>
4.3.11.1 샘플 개요

다음 마크업 조각:

<body>
  <hgroup id="document-title">
    <h1>HTML: Living Standard</h1>
    <p>Last Updated 12 August 2016</p>
  </hgroup>
  <p>Some intro to the document.</p>
  <h2>Table of contents</h2>
  <ol id=toc>...</ol>
  <h2>First section</h2>
  <p>Some intro to the first section.</p>
</body>

...는 3개의 문서 제목을 생성합니다:

  1. <h1>HTML: Living Standard</h1>

  2. <h2>Table of contents</h2>.

  3. <h2>First section</h2>.

개요의 렌더링된 뷰는 다음과 같이 보일 수 있습니다:

상위 섹션 제목이 "HTML: Living Standard"이고, 두 개의 하위 섹션이 "Table of contents"와 "First section"인 문서 개요입니다.

먼저, 다음은 장과 하위 섹션이 매우 짧은 책으로 구성된 문서입니다:

<!DOCTYPE HTML>
<html lang=en>
<title>The Tax Book (all in one page)</title>
<h1>The Tax Book</h1>
<h2>Earning money</h2>
<p>Earning money is good.</p>
<h3>Getting a job</h3>
<p>To earn money you typically need a job.</p>
<h2>Spending money</h2>
<p>Spending is what money is mainly used for.</p>
<h3>Cheap things</h3>
<p>Buying cheap things often not cost-effective.</p>
<h3>Expensive things</h3>
<p>The most expensive thing is often not the most cost-effective either.</p>
<h2>Investing money</h2>
<p>You can lend your money to other people.</p>
<h2>Losing money</h2>
<p>If you spend money or invest money, sooner or later you will lose money.
<h3>Poor judgement</h3>
<p>Usually if you lose money it's because you made a mistake.</p>

개요는 다음과 같이 표현될 수 있습니다:

  1. The Tax Book
    1. Earning money
      1. Getting a job
    2. Spending money
      1. Cheap things
      2. Expensive things
    3. Investing money
    4. Losing money
      1. Poor judgement

title 요소는 제목이 아님에 유의하세요.

문서에는 여러 개의 최상위 제목이 포함될 수 있습니다:

<!DOCTYPE HTML>
<html lang=en>
<title>Alphabetic Fruit</title>
<h1>Apples</h1>
<p>Pomaceous.</p>
<h1>Bananas</h1>
<p>Edible.</p>
<h1>Carambola</h1>
<p>Star.</p>

문서의 개요는 다음과 같이 표현될 수 있습니다:

  1. Apples
  2. Bananas
  3. Carambola

header 요소는 문서의 개요에 영향을 주지 않습니다:

<!DOCTYPE HTML>
<html lang="en">
<title>We're adopting a child! — Ray's blog</title>
<h1>Ray's blog</h1>
<article>
 <header>
  <nav>
   <a href="?t=-1d">Yesterday</a>;
   <a href="?t=-7d">Last week</a>;
   <a href="?t=-1m">Last month</a>
  </nav>
  <h2>We're adopting a child!</h2>
 </header>
 <p>As of today, Janine and I have signed the papers to become
 the proud parents of baby Diane! We've been looking forward to
 this day for weeks.</p>
</article>
</html>

문서의 개요는 다음과 같이 표현될 수 있습니다:

  1. Ray's blog
    1. We're adopting a child!

다음 예제는 준수하지만, 제목 수준이 1인 제목이 없기 때문에 권장되지는 않습니다:

<!DOCTYPE HTML>
<html lang=en>
<title>Alphabetic Fruit</title>
<section>
 <h2>Apples</h2>
 <p>Pomaceous.</p>
</section>
<section>
 <h2>Bananas</h2>
 <p>Edible.</p>
</section>
<section>
 <h2>Carambola</h2>
 <p>Star.</p>
</section>

문서의 개요는 다음과 같이 표현될 수 있습니다:

    1. Apples
    2. Bananas
    3. Carambola

다음 예제는 준수하지만, 첫 번째 제목제목 수준이 1이 아니기 때문에 권장되지는 않습니다:

<!DOCTYPE HTML>
<html lang=en>
<title>Feathers on The Site of Encyclopedic Knowledge</title>
 <h2>A plea from our caretakers</h2>
 <p>Please, we beg of you, send help! We're stuck in the server room!</p>
<h1>Feathers</h1>
<p>Epidermal growths.</p>

문서의 개요는 다음과 같이 표현될 수 있습니다:

    1. A plea from our caretakers
  1. Feathers
4.3.11.2 사용자에게 개요 노출

사용자 에이전트는 페이지 개요를 사용자에게 노출하여 탐색을 돕도록 권장됩니다. 이는 특히 스크린 리더와 같은 비시각적 미디어에 해당됩니다.

예를 들어, 사용자 에이전트는 화살표 키를 다음과 같이 매핑할 수 있습니다:

Shift + ← Left
이전 제목으로 이동
Shift + → Right
다음 제목으로 이동
Shift + ↑ Up
현재 제목의 레벨보다 하나 낮은 레벨의 다음 제목으로 이동
Shift + ↓ Down
현재 제목과 같은 레벨의 다음 제목으로 이동

4.3.12 사용 요약

이 섹션은 규범적이지 않습니다.

요소 목적
예시
body 문서의 내용.
<!DOCTYPE HTML>
<html lang="en">
 <head> <title>Steve Hill's Home Page</title> </head>
 <body> <p>Hard Trance is My Life.</p> </body>
</html>
article 문서, 페이지, 애플리케이션 또는 사이트 내에서 완전하거나 독립적인 구성을 가지며 원칙적으로 독립적으로 배포되거나 재사용될 수 있는 콘텐츠, 예를 들어 배포용으로 사용될 수 있는 포럼 게시물, 잡지 또는 신문 기사, 블로그 게시물, 사용자가 제출한 댓글, 인터랙티브 위젯 또는 도구, 또는 기타 독립적인 콘텐츠 항목을 의미합니다.
<article>
 <img src="/tumblr_masqy2s5yn1rzfqbpo1_500.jpg" alt="Yellow smiley face with the caption 'masif'">
 <p>My fave Masif tee so far!</p>
 <footer>Posted 2 days ago</footer>
</article>
<article>
 <img src="/tumblr_m9tf6wSr6W1rzfqbpo1_500.jpg" alt="">
 <p>Happy 2nd birthday Masif Saturdays!!!</p>
 <footer>Posted 3 weeks ago</footer>
</article>
section 문서 또는 애플리케이션의 일반적인 섹션. 이 문맥에서 섹션은 일반적으로 제목이 있는 내용의 주제별 그룹화를 의미합니다.
<h1>Biography</h1>
<section>
 <h1>The facts</h1>
 <p>1500+ shows, 14+ countries</p>
</section>
<section>
 <h1>2010/2011 figures per year</h1>
 <p>100+ shows, 8+ countries</p>
</section>
nav 다른 페이지 또는 페이지 내의 부분으로 연결되는 섹션: 내비게이션 링크가 있는 섹션.
<nav>
 <p><a href="/">Home</a>
 <p><a href="/biog.html">Bio</a>
 <p><a href="/discog.html">Discog</a>
</nav>
aside 페이지의 섹션으로, 주변 콘텐츠와 간접적으로 관련된 콘텐츠로 구성되며, 해당 콘텐츠와 분리될 수 있는 섹션입니다. 이러한 섹션은 인쇄된 활자에서 사이드바로 자주 표현됩니다.
<h1>Music</h1>
<p>As any burner can tell you, the event has a lot of trance.</p>
<aside>You can buy the music we played at our <a href="buy.html">playlist page</a>.</aside>
<p>This year we played a kind of trance that originated in Belgium, Germany, and the Netherlands in the mid-90s.</p>
h1h6 제목
<h1>The Guide To Music On The Playa</h1>
<h2>The Main Stage</h2>
<p>If you want to play on a stage, you should bring one.</p>
<h2>Amplified Music</h2>
<p>Amplifiers up to 300W or 90dB are welcome.</p>
hgroup 제목 및 관련 콘텐츠. 이 요소는 h1h6 요소와 하나 이상의 p 요소를 그룹화하여 하위 제목, 대체 제목 또는 태그라인을 나타내는 콘텐츠를 포함할 수 있습니다.
<hgroup>
 <h1>Burning Music</h1>
 <p>The Guide To Music On The Playa</p>
</hgroup>
<section>
 <hgroup>
  <h1>Main Stage</h1>
  <p>The Fiction Of A Music Festival</p>
 </hgroup>
 <p>If you want to play on a stage, you should bring one.</p>
header 소개 또는 내비게이션 요소의 그룹.
<article>
 <header>
  <h1>Hard Trance is My Life</h1>
  <p>By DJ Steve Hill and Technikal</p>
 </header>
 <p>The album with the amusing punctuation has red artwork.</p>
footer 가장 가까운 상위 섹션 콘텐츠 요소나, 그러한 상위 요소가 없을 경우 body 요소에 대한 푸터입니다. 푸터에는 보통 해당 섹션에 대한 정보, 작성자 정보, 관련 문서로의 링크, 저작권 데이터 등이 포함됩니다.
<article>
 <h1>Hard Trance is My Life</h1>
 <p>The album with the amusing punctuation has red artwork.</p>
 <footer>
  <p>Artists: DJ Steve Hill and Technikal</p>
 </footer>
</article>
4.3.12.1 아티클 또는 섹션?

이 섹션은 비규범적입니다.

섹션은 다른 것의 일부를 형성합니다. 아티클은 그 자체로 독립된 것입니다. 하지만 어떤 것이 섹션이고 어떤 것이 아티클인지 어떻게 알 수 있을까요? 대부분의 경우, 진짜 답은 "작성자의 의도에 달려 있다"입니다.

예를 들어, "이 즙이 많은 녹색 사과는 애플 파이 속을 채우기에 좋습니다."라고만 적힌 "그래니 스미스" 챕터가 있는 책을 상상해볼 수 있습니다. 이 경우 다른 종류의 사과에 대한 여러 챕터가 있을 것이므로 이는 섹션입니다.

반면에 "그래니 스미스. 이 즙이 많은 녹색 사과는 애플 파이 속을 채우기에 좋습니다."라고만 적힌 트윗이나 레딧 댓글, 텀블러 게시물, 신문 광고를 상상할 수도 있습니다. 이 경우 이는 전체 내용을 담고 있기 때문에 아티클이 됩니다.

아티클에 대한 댓글은 그 아티클의 일부가 아니므로, 이는 독립된 아티클입니다.

4.4 내용 그룹화

4.4.1 p 요소

Element/p

모든 최신 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLParagraphElement

모든 최신 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
문구 콘텐츠.
텍스트/HTML에서 태그 생략:
p 요소의 끝 태그address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, main, menu, nav, ol, p, pre, search, section, table, 또는 ul 요소가 바로 뒤따라오거나, 부모 요소에 더 이상 콘텐츠가 없고 부모 요소가 a, audio, del, ins, map, noscript, 또는 video 요소가 아닌 HTML 요소일 경우 생략될 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLParagraphElement : HTMLElement {
[HTMLConstructor] constructor();

// 더 이상 사용되지 않는 멤버가 있습니다.
};

p 요소는 단락표현합니다.

단락은 일반적으로 인접한 블록과 빈 줄 또는 첫 줄 들여쓰기로 물리적으로 구분된 텍스트 블록으로 시각적 매체에서 표현되지만, 스타일 시트나 사용자 에이전트는 예를 들어 줄바꿈 기호(¶)를 사용하여 단락 구분을 다르게 표시하는 것도 가능합니다.

다음 예시는 적합한 HTML 조각입니다:

<p>작은 새끼 고양이가 조심스럽게 카펫 조각 위에 앉았습니다. 나중에 이 순간은 고양이가 매트 위에 앉아 있었던 시간으로 기억될 것입니다.</p>
<fieldset>
<legend>개인 정보</legend>
<p>
<label>이름: <input name="n"></label>
<label><input name="anon" type="checkbox"> 다른 사용자로부터 숨기기</label>
</p>
<p><label>주소: <textarea name="a"></textarea></label></p>
</fieldset>
<p>한때 펨리에서 나온 예제가 있었는데, <br>
마크업의 품질이 의심스러웠다. <br>
검증기는 불평했고, <br>
저자는 고통을 겪었다, <br>
오류를 마크업에서 운율로 이동시키는 것에 대해. </p>

p 요소는 더 적합한 요소가 있을 때 사용하지 않아야 합니다.

다음 예제는 기술적으로는 맞지만:

<section>
<!-- ... -->
<p>마지막 수정일: 2001-04-23</p>
<p>저자: fred@example.com</p>
</section>

더 좋은 마크업은 다음과 같습니다:

<section>
<!-- ... -->
<footer>마지막 수정일: 2001-04-23</footer>
<address>저자: fred@example.com</address>
</section>

또는:

<section>
<!-- ... -->
<footer>
<p>마지막 수정일: 2001-04-23</p>
<address>저자: fred@example.com</address>
</footer>
</section>

리스트 요소(특히 olul 요소)는 p 요소의 자식이 될 수 없습니다. 따라서 문장에 불릿 목록이 포함될 경우, 어떻게 마크업해야 할지 궁금할 수 있습니다.

예를 들어, 이 환상적인 문장은 다음과 관련된 불릿을 포함합니다:

그리고 아래에서 더 자세히 설명됩니다.

해결책은 단락이 HTML 용어에서는 논리적 개념이 아니라 구조적 개념이라는 점을 이해하는 것입니다. 위의 환상적인 예에서, 실제로는 다섯 개의 단락이 이 사양에 따라 정의됩니다: 목록 전 하나, 각 불릿마다 하나씩, 그리고 목록 후 하나.

위의 예제에 대한 마크업은 다음과 같습니다:

<p>예를 들어, 이 환상적인 문장은 다음과 관련된 불릿을 포함합니다:</p>
<ul>
<li>마법사,
<li>광속 여행, 및
<li>텔레파시,
</ul>
<p>그리고 아래에서 더 자세히 설명됩니다.</p>

이와 같은 "논리적" 단락을 여러 개의 "구조적" 단락으로 간편하게 스타일링하려는 저자는 div 요소를 p 요소 대신 사용할 수 있습니다.

따라서 예를 들어 위의 예제는 다음과 같이 변환될 수 있습니다:

<div>예를 들어, 이 환상적인 문장은 다음과 관련된 불릿을 포함합니다.
<ul>
<li>마법사,
<li>광속 여행, 및
<li>텔레파시,
</ul>
그리고 아래에서 더 자세히 설명됩니다.</div>

이 예제는 여전히 다섯 개의 구조적 단락을 가지고 있지만, 이제 저자는 예제를 개별적으로 고려할 필요 없이 div만 스타일링할 수 있습니다.

4.4.2 hr 요소

요소/hr

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
이 요소가 사용될 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
select 요소의 자식으로 사용될 수 있습니다.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그가 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLHRElement : HTMLElement {
  [HTMLConstructor] constructor();

// 더 이상 사용되지 않는 멤버가 있습니다.
};

hr 요소는 단락 수준의 주제적 구분을 나타냅니다. 예를 들어, 이야기에서 장면 전환, 참고 서적의 섹션 내에서 주제 전환 등을 나타낼 수 있습니다. 또는 select 요소의 옵션 집합 사이의 구분선 역할을 할 수도 있습니다.

다음 가상의 프로젝트 매뉴얼 발췌는 섹션 내에서 주제를 구분하기 위해 hr 요소를 사용하는 두 개의 섹션을 보여줍니다.

<section>
 <h1>Communication</h1>
 <p>There are various methods of communication. This section
 covers a few of the important ones used by the project.</p>
 <hr>
 <p>Communication stones seem to come in pairs and have mysterious
 properties:</p>
 <ul>
  <li>They can transfer thoughts in two directions once activated
  if used alone.</li>
  <li>If used with another device, they can transfer one's
  consciousness to another body.</li>
  <li>If both stones are used with another device, the
  consciousnesses switch bodies.</li>
 </ul>
 <hr>
 <p>Radios use the electromagnetic spectrum in the meter range and
 longer.</p>
 <hr>
 <p>Signal flares use the electromagnetic spectrum in the
 nanometer range.</p>
</section>
<section>
 <h1>Food</h1>
 <p>All food at the project is rationed:</p>
 <dl>
  <dt>Potatoes</dt>
  <dd>Two per day</dd>
  <dt>Soup</dt>
  <dd>One bowl per day</dd>
 </dl>
 <hr>
 <p>Cooking is done by the chefs on a set rotation.</p>
</section>

섹션들 자체 사이에는 hr 요소가 필요하지 않습니다. section 요소와 h1 요소가 자체적으로 주제 변화를 암시하기 때문입니다.

Peter F. Hamilton의 Pandora's Star에서 발췌한 다음 내용은 장면 전환을 앞두고 있는 두 개의 단락과 전환 이후의 단락을 보여줍니다. 장면 전환은 인쇄된 책에서 두 번째와 세 번째 단락 사이에 별 하나가 중앙에 배치된 공백으로 표현되며, 여기서는 hr 요소를 사용해 표현되었습니다.

<p>Dudley was ninety-two, in his second life, and fast approaching
time for another rejuvenation. Despite his body having the physical
age of a standard fifty-year-old, the prospect of a long degrading
campaign within academia was one he regarded with dread. For a
supposedly advanced civilization, the Intersolar Commonwealth could be
appallingly backward at times, not to mention cruel.</p>
<p><i>Maybe it won't be that bad</i>, he told himself. The lie was
comforting enough to get him through the rest of the night's
shift.</p>
<hr>
<p>The Carlton AllLander drove Dudley home just after dawn. Like the
astronomer, the vehicle was old and worn, but perfectly capable of
doing its job. It had a cheap diesel engine, common enough on a
semi-frontier world like Gralmond, although its drive array was a
thoroughly modern photoneural processor. With its high suspension and
deep-tread tyres it could plough along the dirt track to the
observatory in all weather and seasons, including the metre-deep snow
of Gralmond's winters.</p>

hr 요소는 문서의 개요에 영향을 미치지 않습니다.

4.4.3 pre 요소

요소/pre

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (레거시)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
유의미한 콘텐츠.
이 요소가 사용될 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
문장 콘텐츠.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성.
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLPreElement : HTMLElement {
  [HTMLConstructor] constructor();

// 더 이상 사용되지 않는 멤버가 있습니다.
};

pre 요소는 미리 서식화된 텍스트의 블록을 나타내며, 이 텍스트는 요소 대신 전형적인 타이포그래픽 관습에 의해 구조화됩니다.

HTML 구문에서, pre 요소 시작 태그 바로 뒤에 오는 선행 개행 문자는 제거됩니다.

다음은 pre 요소를 사용할 수 있는 몇 가지 사례입니다:

저자들은 서식이 손실될 때(예: 음성 합성기, 점자 디스플레이 등 사용자에게) 미리 서식화된 텍스트가 어떻게 표시될지 고려하는 것이 좋습니다. ASCII 아트와 같은 경우에는 텍스트 설명과 같은 대체 표현이 문서의 독자들에게 더 보편적으로 접근 가능할 수 있습니다.

컴퓨터 코드 블록을 나타내기 위해 pre 요소와 code 요소를 함께 사용할 수 있으며, 컴퓨터 출력 블록을 나타내기 위해서는 pre 요소와 samp 요소를 함께 사용할 수 있습니다. 마찬가지로, 사용자가 입력해야 하는 텍스트를 표시하기 위해 kbd 요소를 pre 요소 내에 사용할 수 있습니다.

이 요소는 양방향 알고리즘과 관련된 렌더링 요구 사항을 포함합니다.

다음 스니펫에서는 컴퓨터 코드 샘플이 제시됩니다.

<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
  this.element = element;
  this.canClose = canClose;
  this.closeHandler = function () { if (closeHandler) closeHandler() };
}</code></pre>

다음 스니펫에서는 sampkbd 요소가 pre 요소의 내용에 섞여서 Zork I 세션을 보여줍니다.

<pre><samp>You are in an open field west of a big white house with a boarded
front door.
There is a small mailbox here.

></samp> <kbd>open mailbox</kbd>

<samp>Opening the mailbox reveals:
A leaflet.

></samp></pre>

다음 예시는 pre 요소를 사용하여 특이한 서식이 본래 시 자체의 일부를 이루는 현대 시를 보여줍니다.

<pre>                maxling

it is with a          heart
               heavy

that i admit loss of a feline
        so           loved

a friend lost to the
        unknown
                                (night)

~cdr 11dec07</pre>

4.4.4 blockquote 요소

요소/blockquote

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (레거시)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

<blockquote>

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
유의미한 콘텐츠.
이 요소가 사용될 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
cite — 인용문의 출처 또는 수정에 대한 추가 정보를 연결
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLQuoteElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString cite;
};

HTMLQuoteElement 인터페이스는 q 요소에서도 사용됩니다.

blockquote 요소는 다른 출처에서 인용된 섹션을 나타냅니다.

blockquote 내의 콘텐츠는 다른 출처에서 인용된 것이어야 하며, 해당 출처의 주소가 있는 경우 cite 속성에서 인용할 수 있습니다.

cite 속성이 존재하는 경우, 유효한 URL이어야 합니다. 해당 속성 값은 요소의 노드 문서에 상대적으로 구문 분석되어야 합니다. 사용자 에이전트는 사용자가 이러한 인용 링크를 따라가도록 허용할 수 있지만, 이는 주로 개인적인 용도(예: 사이트의 인용문 사용 통계 수집을 위한 서버 측 스크립트)로 사용되며, 독자를 위한 것이 아닙니다.

blockquote의 내용은 생략되거나 해당 언어의 전통적인 방식으로 문맥이 추가될 수 있습니다.

예를 들어, 영어에서는 일반적으로 대괄호를 사용합니다. "Jane ate the cracker. She then said she liked apples and fish."라는 문장이 있는 페이지가 있다고 가정하면 다음과 같이 인용될 수 있습니다:

<blockquote>
 <p>[Jane] then said she liked [...] fish.</p>
</blockquote>

인용문의 출처는 blockquote 요소 외부에 배치해야 합니다.

예를 들어, 인용문 뒤에 단락으로 출처가 제공되는 예시입니다:

<blockquote>
 <p>I contend that we are both atheists. I just believe in one fewer god than you do. When you understand why you dismiss all the other possible gods, you will understand why I dismiss yours.</p>
</blockquote>
<p>— Stephen Roberts</p>

아래의 다른 예시에서는 출처를 표시하는 다양한 방법을 보여줍니다.

cite IDL 속성은 요소의 cite 콘텐츠 속성을 반영해야 합니다.

여기서는 blockquote 요소가 figure 요소 및 figcaption과 함께 사용되어, 인용문을 그 출처와 명확하게 연결하는 방법을 보여줍니다(이는 인용문의 일부가 아니므로 blockquote 내부에 포함되지 않아야 합니다):

<figure>
 <blockquote>
  <p>The truth may be puzzling. It may take some work to grapple with.
  It may be counterintuitive. It may contradict deeply held
  prejudices. It may not be consonant with what we desperately want to
  be true. But our preferences do not determine what's true. We have a
  method, and that method helps us to reach not absolute truth, only
  asymptotic approaches to the truth — never there, just closer
  and closer, always finding vast new oceans of undiscovered
  possibilities. Cleverly designed experiments are the key.</p>
 </blockquote>
 <figcaption>Carl Sagan, in "<cite>Wonder and Skepticism</cite>", from
 the <cite>Skeptical Inquirer</cite> Volume 19, Issue 1 (January-February
 1995)</figcaption>
</figure>

다음 예시에서는 citeblockquote를 함께 사용하는 방법을 보여줍니다:

<p>His next piece was the aptly named <cite>Sonnet 130</cite>:</p>
<blockquote cite="https://quotes.example.org/s/sonnet130.html">
  <p>My mistress' eyes are nothing like the sun,<br>
  Coral is far more red, than her lips red,<br>
  ...

이 예시는 포럼 게시물에서 사용자가 응답하는 게시물을 보여주는 blockquote의 사용 방법을 보여줍니다. article 요소는 각 게시물을 나타내는 데 사용되어 스레드를 마크업합니다.

<article>
 <h1><a href="https://bacon.example.com/?blog=109431">Bacon on a crowbar</a></h1>
 <article>
  <header><strong>t3yw</strong> 12 포인트 1시간 전</header>
  <p>저것을 보고 나르왈이 참 좋아할 거야.</p>
  <footer><a href="?pid=29578">퍼머링크</a></footer>
  <article>
   <header><strong>greg</strong> 8 포인트 1시간 전</header>
   <blockquote><p>저것을 보고 나르왈이 참 좋아할 거야.</p></blockquote>
   <p>나르왈은 베이컨을 먹지 않아.</p>
   <footer><a href="?pid=29579">퍼머링크</a></footer>
   </article>
    <header><strong>t3yw</strong> 15 포인트 1시간 전</header>
    <blockquote>
     <blockquote><p>저것을 보고 나르왈이 참 좋아할 거야.</p></blockquote>
     <p>나르왈은 베이컨을 먹지 않아.</p>
    </blockquote>
    <p>다음으로 그들은 바나나를 깠다고 할 것 같아!</p>
    <footer><a href="?pid=29580">퍼머링크</a></footer>
    </article>
   </article>
  </article>
  </article>
   <header><strong>fred</strong> 1 포인트 23분 전</header>
   <blockquote><p>저것을 보고 나르왈이 참 좋아할 거야.</p></blockquote>
   <p>그들은 아마도 바나나를 까는 것도 좋아할 거야.</p>
   <footer><a href="?pid=29582">퍼머링크</a></footer>
  </article>
 </article>

다음 예시는 짧은 인용문을 보여주는 blockquote의 사용 방법을 보여줍니다. 이 예시는 p 요소를 blockquote 요소 안에 넣을 필요가 없음을 보여줍니다:

<p>He began his list of "lessons" with the following:</p>
<blockquote>One should never assume that his side of the issue will be recognized, let alone that it will be conceded to have merits.</blockquote>
<p>He continued with a number of similar points, ending with:</p>
<blockquote>Finally, one should be prepared for the threat of breakdown in negotiations at any given moment and not be cowed by the possibility.</blockquote>
<p>We shall now discuss these points...

대화 표현 방법 예시가 후반부 섹션에 나와 있으며, 이를 위해 citeblockquote 요소를 사용하는 것은 적절하지 않습니다.

4.4.5 ol 요소

Element/ol

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLOListElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
범주:
플로우 콘텐츠.
요소의 자식에 적어도 하나의 li 요소가 포함되어 있는 경우: 만져질 수 있는 콘텐츠.
이 요소를 사용할 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
제로 또는 그 이상의 li스크립트 지원 요소.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
reversed — 리스트를 역순으로 번호 매기기
start — 리스트의 시작 값
type — 리스트 마커의 종류
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLOListElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean reversed;
  [CEReactions] attribute long start;
  [CEReactions] attribute DOMString type;

  // 폐기된 멤버도 있습니다
};

ol 요소는 문서의 의미를 변경할 정도로 항목의 순서가 의도적으로 정해진 목록을 나타냅니다.

목록의 항목들은 li 요소 자식 노드이며, ol 요소의 트리 순서에 따라 정렬됩니다.

ol 요소는 시작 값을 가지며, 이는 다음과 같이 결정됩니다:

  1. ol 요소에 start 속성이 있는 경우:

    1. 해당 속성 값을 정수로 파싱한 결과parsed로 정의합니다.

    2. 만약 parsed가 오류가 아닌 경우, parsed를 반환합니다.

  2. ol 요소에 reversed 속성이 있는 경우, 소유된 li 요소들의 수를 반환합니다.

  3. 1을 반환합니다.

목록에서 사용할 마커 종류를 지정해야 하는 경우(예: 항목이 숫자/문자로 참조될 수 있기 때문에) type 속성을 사용할 수 있습니다. 지정된 경우, 속성 값은 아래 표의 첫 번째 열에 주어진 문자 중 하나와 일치해야 합니다. type 속성은 첫 번째 셀이 속성 값과 일치하는 행의 두 번째 열에 표시된 상태를 나타냅니다. 셀이 일치하지 않거나 속성이 생략된 경우, 속성은 십진수 상태를 나타냅니다.

키워드 상태 설명 값 1-3 및 3999-4001의 예
1 (U+0031) 십진법 십진수 1. 2. 3. ... 3999. 4000. 4001. ...
a (U+0061) 소문자 알파벳 소문자 라틴 알파벳 a. b. c. ... ewu. ewv. eww. ...
A (U+0041) 대문자 알파벳 대문자 라틴 알파벳 A. B. C. ... EWU. EWV. EWW. ...
i (U+0069) 소문자 로마 숫자 소문자 로마 숫자 i. ii. iii. ... mmmcmxcix. i̅v̅. i̅v̅i. ...
I (U+0049) 대문자 로마 숫자 대문자 로마 숫자 I. II. III. ... MMMCMXCIX. I̅V̅. I̅V̅I. ...

사용자 에이전트는 type 속성의 상태와 일치하는 방식으로 목록 항목을 렌더링해야 합니다. 0 이하의 숫자는 type 속성과 상관없이 항상 십진법을 사용해야 합니다.

CSS 사용자 에이전트를 위한 이 속성의 매핑은 'list-style-type' CSS 속성에 대한 매핑이 렌더링 섹션에 제공됩니다(매핑은 간단합니다: 위의 상태는 해당하는 CSS 값과 동일한 이름을 가집니다).

이 속성을 구현하는 기본 CSS 목록 스타일을 재정의할 수 있으며, 이를 통해 목록 항목이 렌더링되는 방식을 변경할 수 있습니다.

reversedtype IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

start IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 하며, 기본 값은 1입니다.

이는 start IDL 속성이 start 콘텐츠 속성이 생략된 경우 및 reversed 콘텐츠 속성이 지정된 경우, 목록의 시작 값과 반드시 일치하지 않는다는 것을 의미합니다.

다음 마크업은 순서가 중요한 목록을 보여주며, ol 요소가 적절하게 사용된 예입니다. 이 목록을 ul 섹션의 동일한 항목으로 구성된 목록과 비교하여, ul 요소를 사용하는 예를 볼 수 있습니다.

<p>나는 다음 나라에 살았었다 (거주 시작 순서대로 나열됨):</p>
<ol>
 <li>스위스
 <li>영국
 <li>미국
 <li>노르웨이
</ol>

목록의 순서를 변경하면 문서의 의미가 어떻게 달라지는지 주목하십시오. 다음 예에서는 첫 두 항목의 순서를 바꿈으로써 작성자의 출생지가 바뀌었습니다:

<p>나는 다음 나라에 살았었다 (거주 시작 순서대로 나열됨):</p>
<ol>
 <li>영국
 <li>스위스
 <li>미국
 <li>노르웨이
</ol>

4.4.6 ul 요소

요소/ul

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구 버전)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
요소의 자식들이 최소한 하나의 li 요소를 포함하고 있다면: Palpable content.
이 요소가 사용될 수 있는 컨텍스트:
Flow content가 예상되는 곳.
컨텐츠 모델:
영(0)개 이상의 li 요소들과 스크립트 지원 요소들.
text/html에서의 태그 생략:
태그 생략 불가.
내용 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLUListElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 폐기된 멤버도 있습니다
};

ul 요소는 항목의 순서가 중요하지 않은 목록을 나타냅니다 — 즉, 순서를 변경해도 문서의 의미에 큰 영향을 주지 않는 경우입니다.

목록의 항목들은 li 요소 자식 노드이며, ul 요소의 자식 노드입니다.

다음 마크업은 순서가 중요하지 않은 목록을 보여주며, ul 요소가 적절하게 사용된 예입니다. 이 목록을 ol 섹션의 동일한 항목으로 구성된 목록과 비교하여, ol 요소를 사용하는 예를 볼 수 있습니다.

<p>나는 다음 나라에 살았었다:</p>
<ul>
 <li>노르웨이
 <li>스위스
 <li>영국
 <li>미국
</ul>

목록의 순서를 변경해도 문서의 의미가 변하지 않는다는 점에 주목하십시오. 위의 예에서는 항목들이 알파벳 순으로 나열되어 있지만, 아래의 예에서는 2007년 현재 계좌 잔고 크기 순으로 나열되어 있으며, 문서의 의미에는 전혀 변화가 없습니다:

<p>나는 다음 나라에 살았었다:</p>
<ul>
 <li>스위스
 <li>노르웨이
 <li>영국
 <li>미국
</ul>

4.4.7 menu 요소

요소/menu

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구 버전)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLMenuElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구 버전)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
Flow content.
요소의 자식들이 최소한 하나의 li 요소를 포함하고 있다면: Palpable content.
이 요소가 사용될 수 있는 컨텍스트:
Flow content가 예상되는 곳.
컨텐츠 모델:
영(0)개 이상의 li 요소들과 스크립트 지원 요소들.
text/html에서의 태그 생략:
태그 생략 불가.
내용 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLMenuElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 폐기된 멤버도 있습니다
};

menu 요소는 그 안에 포함된 항목들로 이루어진 툴바를 나타냅니다. 이 항목들은 li 요소들로 표현되며, 각 항목은 사용자가 수행하거나 활성화할 수 있는 명령을 나타냅니다.

menu 요소는 명령 목록을 표현하기 위해 ul의 의미적 대안일 뿐입니다(즉, "툴바"를 나타냅니다).

이 예에서는 텍스트 편집 애플리케이션이 menu 요소를 사용하여 일련의 편집 명령을 제공합니다:

<menu>
 <li><button onclick="copy()"><img src="copy.svg" alt="Copy"></button></li>
 <li><button onclick="cut()"><img src="cut.svg" alt="Cut"></button></li>
 <li><button onclick="paste()"><img src="paste.svg" alt="Paste"></button></li>
</menu>

이것을 전통적인 툴바 메뉴로 보이도록 스타일링하는 것은 애플리케이션에 달려 있습니다.

4.4.8 li 요소

요소/li

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구 버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLLIElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (구 버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소가 사용될 수 있는 컨텍스트:
ol 요소 내부.
ul 요소 내부.
menu 요소 내부.
컨텐츠 모델:
Flow content.
text/html에서의 태그 생략:
li 요소의 끝 태그li 요소가 즉시 다음 li 요소나 부모 요소의 더 이상의 컨텐츠가 없을 때 생략할 수 있습니다.
내용 속성:
전역 속성
요소가 ul 또는 menu 요소의 자식이 아닌 경우: value — 목록 항목의 순번 값.
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLLIElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute long value;

  // 폐기된 멤버도 있습니다
};

li 요소는 목록 항목을 표현합니다. 부모 요소가 ol, ul, 또는 menu 요소인 경우, 이 요소는 정의된 대로 부모 요소의 목록 항목입니다. 그렇지 않으면 목록 항목은 다른 li 요소와 정의된 목록 관련 관계가 없습니다.

value 속성이 존재하는 경우, 이는 유효한 정수여야 하며, 목록 항목의 순번 값을 결정하는 데 사용됩니다. 이는 li목록 소유자ol 요소일 때 적용됩니다.


‘display’ 속성의 계산된 값이 ‘list-item’인 요소는 다음과 같이 결정되는 목록 소유자를 가집니다:

  1. 요소가 렌더링 중이 아니라면, null을 반환하고, 요소는 목록 소유자를 가지지 않습니다.

  2. ancestor를 요소의 부모로 설정합니다.

  3. 요소에 ol, ul, 또는 menu 조상이 있는 경우, ancestor를 가장 가까운 조상 요소로 설정합니다.

  4. 가장 가까운 포함 조상인 ancestor를 반환하고, 이 요소는 CSS 상자를 생성합니다.

    이러한 요소는 항상 존재하며, 최소한 문서 요소는 항상 CSS 상자를 생성합니다.

주어진 목록 소유자 owner에 의해 소유된 각 요소의 순번 값을 결정하려면 다음 단계를 수행합니다:

  1. i를 1로 설정합니다.

  2. ownerol 요소인 경우, numberingowner시작 값으로 설정합니다. 그렇지 않으면 numbering을 1로 설정합니다.

  3. 반복: i목록 소유자가 소유한 owner의 목록 항목 수를 초과하면 종료합니다; owner의 모든 소유 목록 항목순번 값을 할당받았습니다.

  4. itemi번째 owner소유 목록 항목으로 설정하며, 이는 트리 순서에 따릅니다.

  5. itemli 요소이며 value 속성을 가지고 있다면:

    1. parsed정수로 속성 값을 구문 분석한 결과로 설정합니다.

    2. parsed가 오류가 아니라면 numberingparsed로 설정합니다.

  6. item순번 값numbering입니다.

  7. ownerol 요소이고, ownerreversed 속성이 있으면 numbering을 1 감소시키고, 그렇지 않으면 numbering을 1 증가시킵니다.

  8. i를 1 증가시킵니다.

  9. ‘반복’으로 이동합니다.


value IDL 속성은 value 내용 속성의 값을 반영해야 합니다.

요소의 value IDL 속성은 순번 값과 직접적으로 일치하지 않으며, 단순히 내용 속성을 반영합니다. 예를 들어, 다음 목록을 보면:

<ol>
 <li>Item 1
 <li value="3">Item 3
 <li>Item 4
</ol>

순번 값은 1, 3, 4이며, value IDL 속성은 가져올 때 0, 3, 0을 반환합니다.

다음 예에서는, 역순으로 상위 10개의 영화가 나열됩니다. 목록은 figure 요소와 그 figcaption 요소를 사용하여 제목을 부여받습니다.

<figure>
 <figcaption>역대 최고의 영화 10편</figcaption>
 <ol>
  <li value="10"><cite>Josie and the Pussycats</cite>, 2001</li>
  <li value="9"><cite lang="sh">Црна мачка, бели мачор</cite>, 1998</li>
  <li value="8"><cite>A Bug's Life</cite>, 1998</li>
  <li value="7"><cite>Toy Story</cite>, 1995</li>
  <li value="6"><cite>Monsters, Inc</cite>, 2001</li>
  <li value="5"><cite>Cars</cite>, 2006</li>
  <li value="4"><cite>Toy Story 2</cite>, 1999</li>
  <li value="3"><cite>Finding Nemo</cite>, 2003</li>
  <li value="2"><cite>The Incredibles</cite>, 2004</li>
  <li value="1"><cite>Ratatouille</cite>, 2007</li>
 </ol>
</figure>

마크업은 또한 reversed 속성을 사용하여 다음과 같이 작성될 수 있습니다:

<figure>
 <figcaption>역대 최고의 영화 10편</figcaption>
 <ol reversed>
  <li><cite>Josie and the Pussycats</cite>, 2001</li>
  <li><cite lang="sh">Црна мачка, бели мачор</cite>, 1998</li>
  <li><cite>A Bug's Life</cite>, 1998</li>
  <li><cite>Toy Story</cite>, 1995</li>
  <li><cite>Monsters, Inc</cite>, 2001</li>
  <li><cite>Cars</cite>, 2006</li>
  <li><cite>Toy Story 2</cite>, 1999</li>
  <li><cite>Finding Nemo</cite>, 2003</li>
  <li><cite>The Incredibles</cite>, 2004</li>
  <li><cite>Ratatouille</cite>, 2007</li>
 </ol>
</figure>

li 요소 내부에 제목 요소(e.g. h1)를 포함하는 것이 합법적이지만, 이는 저자가 의도한 의미를 전달하지 않을 수 있습니다. 제목은 새로운 섹션을 시작하므로, 목록의 제목이 목록을 여러 섹션으로 암묵적으로 분할합니다.

4.4.9 dl 요소

Element/dl

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLDListElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
요소의 자식에 하나 이상의 이름-값 그룹이 포함된 경우: 구체적 콘텐츠.
이 요소를 사용할 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
다음 중 하나: 하나 이상의 dt 요소에 이어 하나 이상의 dd 요소로 구성된 그룹, 스크립트 지원 요소와 혼합 가능.
또는: 하나 이상의 div 요소, 스크립트 지원 요소와 혼합 가능.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자를 위한.
구현자를 위한.
DOM 인터페이스:
[Exposed=Window]
interface HTMLDListElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 이전 멤버도 포함
};

dl 요소는 하나 이상의 이름-값 그룹(설명 목록)으로 구성된 연관 목록을 나타냅니다. 이름-값 그룹은 하나 이상의 이름(dt 요소로, 자식 div 요소일 수 있음)과 하나 이상의 값(dd 요소로, 자식 div 요소일 수 있음)으로 구성되며, dtdd 요소 외에는 모든 노드를 무시합니다. 하나의 dl 요소 내에서 각 이름에 대해 하나 이상의 dt 요소가 존재해서는 안 됩니다.

이름-값 그룹은 용어와 정의, 메타데이터 주제와 값, 질문과 답변 또는 기타 이름-값 데이터의 그룹일 수 있습니다.

그룹 내의 값은 대안입니다. 같은 값을 구성하는 여러 단락은 동일한 dd 요소 내에 모두 포함되어야 합니다.

그룹 목록의 순서와 각 그룹 내의 이름과 값의 순서가 중요할 수 있습니다.

마이크로데이터 속성 또는 그룹 전체에 적용되는 다른 전역 속성을 주석으로 달거나 스타일링 목적으로 dl 요소의 각 그룹을 div 요소로 감쌀 수 있습니다. 이것은 dl 요소의 의미를 변경하지 않습니다.

dl 요소의 이름-값 그룹 dl은 다음 알고리즘을 사용하여 결정됩니다. 이름-값 그룹은 이름(처음에는 비어 있는 dt 요소 목록)과 값(처음에는 비어 있는 dd 요소 목록)으로 구성됩니다.

  1. groups를 비어 있는 이름-값 그룹 목록으로 설정합니다.

  2. current를 새로운 이름-값 그룹으로 설정합니다.

  3. seenDd를 false로 설정합니다.

  4. childdl첫 번째 자식으로 설정합니다.

  5. grandchild를 null로 설정합니다.

  6. child가 null이 아닐 때까지:

    1. childdiv 요소인 경우:

      1. grandchildchild첫 번째 자식으로 설정합니다.

      2. grandchild가 null이 아닐 때까지:

        1. dt 또는 ddgrandchild에 대해 처리합니다.

        2. grandchildgrandchild다음 형제로 설정합니다.

    2. 그렇지 않으면, dt 또는 ddchild에 대해 처리합니다.

    3. childchild다음 형제로 설정합니다.

  7. current가 비어 있지 않으면, currentgroups에 추가합니다.

  8. groups를 반환합니다.

dt 또는 ddnode에 대해 처리하는 것은 다음 단계를 따릅니다:

  1. groups, current, 및 seenDd는 이 단계를 호출한 알고리즘에서 같은 이름을 가진 변수와 동일합니다.

  2. nodedt 요소인 경우:

    1. seenDd가 true이면, currentgroups에 추가하고, current를 새로운 이름-값 그룹으로 설정하며, seenDd를 false로 설정합니다.

    2. nodecurrent의 이름에 추가합니다.

  3. 그렇지 않고, nodedd 요소인 경우, nodecurrent의 값에 추가하고 seenDd를 true로 설정합니다.

이름 또는 값이 빈 목록인 이름-값 그룹은 dd 요소를 dt 요소로 잘못 사용했거나 그 반대의 경우가 많습니다. 적합성 검사기는 이러한 실수를 발견할 수 있으며 저자에게 올바른 마크업 사용 방법을 조언할 수 있습니다.

다음 예에서는 하나의 항목("저자")이 두 개의 값("John"과 "Luke")에 연결됩니다.

<dl>
 <dt> 저자
 <dd> John
 <dd> Luke
 <dt> 편집자
 <dd> Frank
</dl>

다음 예에서는 하나의 정의가 두 개의 용어에 연결됩니다.

<dl>
 <dt lang="en-US"> <dfn>color</dfn> </dt>
 <dt lang="en-GB"> <dfn>colour</dfn> </dt>
 <dd> 인간의 경우, 눈의 정밀한 구조가 시야를 세 가지 다른 필터로 분석하여 구별할 수 있는 능력에서 파생된 감각. </dd>
</dl>

다음 예는 dl 요소를 사용하여 일종의 메타데이터를 마크업하는 방법을 보여줍니다. 예제 끝에는 하나의 그룹에 두 개의 메타데이터 레이블("저자"와 "편집자")과 두 개의 값("Robert Rothman"과 "Daniel Jackson")이 있습니다. 이 예제는 또한 스타일링을 돕기 위해 div 요소를 dtdd 요소 그룹 주위에 사용합니다.

<dl>
 <div>
  <dt> 마지막 수정 시간 </dt>
  <dd> 2004-12-23T23:33Z </dd>
 </div>
 <div>
  <dt> 권장 업데이트 간격 </dt>
  <dd> 60초 </dd>
 </div>
 <div>
  <dt> 저자 </dt>
  <dt> 편집자 </dt>
  <dd> Robert Rothman </dd>
  <dd> Daniel Jackson </dd>
 </div>
</dl>

다음 예는 dl 요소를 사용하여 지시 사항 집합을 제공합니다. 여기서 지시 사항의 순서는 중요합니다(다른 예에서는 블록의 순서가 중요하지 않았습니다).

<p>다음과 같이 승리 포인트를 결정하십시오(일치하는 첫 번째 경우를 사용):</p>
<dl>
 <dt> 금화가 정확히 다섯 개 있는 경우 </dt>
 <dd> 다섯 개의 승리 포인트를 얻습니다 </dd>
 <dt> 금화가 하나 이상 있고 은화도 하나 이상 있는 경우 </dt>
 <dd> 두 개의 승리 포인트를 얻습니다 </dd>
 <dt> 은화가 하나 이상 있는 경우 </dt>
 <dd> 하나의 승리 포인트를 얻습니다 </dd>
 <dt> 그렇지 않은 경우 </dt>
 <dd> 승리 포인트를 얻지 못합니다 </dd>
</dl>

다음 코드 스니펫은 dl 요소가 용어집으로 사용되는 모습을 보여줍니다. 정의된 단어를 나타내기 위해 dfn이 사용된 점에 주목하십시오.

<dl>
 <dt><dfn>아파트</dfn>, 명사.</dt>
 <dd>하나 이상의 스레드와 하나 이상의 COM 개체를 그룹화하는 실행 컨텍스트.</dd>
 <dt><dfn>평평함</dfn>, 명사.</dt>
 <dd>공기가 빠진 타이어.</dd>
 <dt><dfn></dfn>, 명사.</dt>
 <dd>사용자의 로그인 디렉터리.</dd>
</dl>

이 예제는 dl 요소와 함께 div 요소를 사용하여 프랑스 레스토랑에서 아이스크림 디저트를 주석으로 다는 마이크로데이터 속성을 사용합니다.

<dl>
 <div itemscope itemtype="http://schema.org/Product">
  <dt itemprop="name">Café ou Chocolat Liégeois
  <dd itemprop="offers" itemscope itemtype="http://schema.org/Offer">
   <span itemprop="price">3.50</span>
   <data itemprop="priceCurrency" value="EUR"></data>
  <dd itemprop="description">2개의 카페 또는 초콜릿, 1개의 바닐라, 카페 또는 초콜릿 소스, 휘핑 크림
 </div>

 <div itemscope itemtype="http://schema.org/Product">
  <dt itemprop="name">Américaine
  <dd itemprop="offers" itemscope itemtype="http://schema.org/Offer">
   <span itemprop="price">3.50</span>
   <data itemprop="priceCurrency" value="EUR"></data>
  <dd itemprop="description">1개의 크렘 브륄레, 1개의 바닐라, 1개의 카라멜, 휘핑 크림
 </div>

</dl>

div 요소가 없으면 마크업은 itemref 속성을 사용하여 dd 요소의 데이터를 항목과 연결해야 합니다. 다음과 같이 됩니다.

<dl>
 <dt itemscope itemtype="http://schema.org/Product" itemref="1-offer 1-description">
  <span itemprop="name">Café ou Chocolat Liégeois</span>
 <dd id="1-offer" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
  <span itemprop="price">3.50</span>
  </data itemprop="priceCurrency" value="EUR"></data>

 <dd id="1-description" itemprop="description">
  2개의 카페 또는 초콜릿, 1개의 바닐라, 카페 또는 초콜릿 소스, 휘핑 크림

 <dt itemscope itemtype="http://schema.org/Product" itemref="2-offer 2-description">
  <span itemprop="name">Américaine</span>
 <dd id="2-offer" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
  <span itemprop="price">3.50</span>
  </data itemprop="priceCurrency" value="EUR"></data>

 <dd id="2-description" itemprop="description">1개의 크렘 브륄레, 1개의 바닐라, 1개의 카라멜, 휘핑 크림
</dl>

dl 요소는 대화를 마크업하는 데 적합하지 않습니다. 대화 마크업 예제를 참조하세요.

4.4.10 dt 요소

Element/dt

모든 현재 엔진에서 지원.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
없음.
이 요소가 사용될 수 있는 맥락:
dd 또는 dt 요소들 앞에, dl 요소 내에서 사용됩니다.
dd 또는 dt 요소들 앞에, div 요소 내에서, dl 요소의 자식으로 사용됩니다.
콘텐츠 모델:
플로우 콘텐츠, 하지만 header, footer, 섹셔닝 콘텐츠 또는 헤딩 콘텐츠 자손을 포함하지 않습니다.
텍스트/HTML에서 태그 생략:
dt 요소의 끝 태그dt 요소 바로 뒤에 다른 dt 요소 또는 dd 요소가 있을 경우 생략할 수 있습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려 사항:
작성자를 위한 안내.
구현자를 위한 안내.
DOM 인터페이스:
HTMLElement를 사용합니다.

dt 요소는 설명 목록(dl 요소)에서 용어 또는 이름 부분을 나타냅니다.

dt 요소 자체는 dl 요소 내에서 사용될 때 그 내용이 정의된 용어임을 나타내지 않지만, 이는 dfn 요소를 사용하여 나타낼 수 있습니다.

이 예제는 dt 요소를 질문에 사용하고 dd 요소를 답변에 사용하여 마크업된 자주 묻는 질문(FAQ) 목록을 보여줍니다.

<article>
 <h1>FAQ</h1>
 <dl>
  <dt>우리가 원하는 것은 무엇입니까?</dt>
  <dd>우리의 데이터입니다.</dd>
  <dt>언제 그것을 원합니까?</dt>
  <dd>지금.</dd>
  <dt>그것은 어디에 있습니까?</dt>
  <dd>우리는 확신할 수 없습니다.</dd>
 </dl>
</article>

4.4.11 dd 요소

Element/dd

모든 현재 엔진에서 지원.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
없음.
이 요소가 사용될 수 있는 맥락:
dt 또는 dd 요소들 뒤에, dl 요소 내에서 사용됩니다.
dt 또는 dd 요소들 뒤에, div 요소 내에서, dl 요소의 자식으로 사용됩니다.
콘텐츠 모델:
플로우 콘텐츠.
텍스트/HTML에서 태그 생략:
dd 요소의 끝 태그dd 요소 바로 뒤에 다른 dd 요소 또는 dt 요소가 있을 경우, 또는 부모 요소에 더 이상 콘텐츠가 없을 경우 생략할 수 있습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려 사항:
작성자를 위한 안내.
구현자를 위한 안내.
DOM 인터페이스:
HTMLElement를 사용합니다.

dd 요소는 설명 목록(dl 요소)에서 용어-설명 그룹의 설명, 정의 또는 값을 나타냅니다.

dl은 사전과 같은 어휘 목록을 정의하는 데 사용될 수 있습니다. 다음 예제에서, dtdfn에 의해 주어진 각 항목에는 여러 개의 dd가 있어 정의의 다양한 부분을 보여줍니다.

<dl>
 <dt><dfn>행복</dfn></dt>
 <dd class="발음">/ˈhæpinəs/</dd>
 <dd class="품사"><i><abbr>n.</abbr></i></dd>
 <dd>행복한 상태.</dd>
 <dd>행운; 성공. <q><b>행복</b>이여! 그것이 성공했습니다!</q></dd>
 <dt><dfn>기쁨</dfn></dt>
 <dd class="발음">/rɪˈdʒɔɪs/</dd>
 <dd><i class="품사"><abbr>v.intr.</abbr></i> 스스로 기뻐하다.</dd>
 <dd><i class="품사"><abbr>v.tr.</abbr></i> 남을 기쁘게 하다.</dd>
</dl>

4.4.12 figure 요소

Element/figure

모든 현재 엔진에서 지원.

Firefox4+Safari5.1+Chrome8+
Opera11+Edge79+
Edge (Legacy)12+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+
카테고리:
플로우 콘텐츠.
명백한 콘텐츠.
이 요소가 사용될 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
다음 중 하나: 하나의 figcaption 요소가 뒤따르는 플로우 콘텐츠.
또는: 플로우 콘텐츠가 뒤따르는 하나의 figcaption 요소.
또는: 플로우 콘텐츠.
텍스트/HTML에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려 사항:
작성자를 위한 안내.
구현자를 위한 안내.
DOM 인터페이스:
HTMLElement를 사용합니다.

figure 요소는 플로우 콘텐츠를 나타내며, 선택적으로 캡션과 함께 자체적으로 포함된 콘텐츠를 나타내며(완전한 문장과 같은) 문서의 주 흐름에서 단일 단위로 참조됩니다.

이 문맥에서 "자체 포함"이 반드시 독립적이라는 것을 의미하는 것은 아닙니다. 예를 들어, 단락의 각 문장은 자체 포함되어 있습니다. 문장의 일부인 이미지는 figure에 적합하지 않지만, 이미지로 구성된 전체 문장은 적합할 수 있습니다.

이 요소는 따라서 일러스트레이션, 다이어그램, 사진, 코드 목록 등을 주석으로 달 때 사용할 수 있습니다.

figure가 문서의 주요 콘텐츠에서 캡션(예: 그림 번호)으로 식별되어 참조되는 경우, 이러한 콘텐츠를 페이지의 측면, 전용 페이지 또는 부록으로 이동시켜도 문서의 흐름에 영향을 미치지 않고 쉽게 이동할 수 있습니다.

figure 요소가 상대적인 위치로 참조되는 경우, 예를 들어 "위의 사진에서" 또는 "다음 그림에서 보여주는 것처럼"이라면, 그림을 이동하면 페이지의 의미가 혼란스러워집니다. 작성자는 페이지를 쉽게 다시 스타일링할 수 있도록 상대적 참조 대신 라벨을 사용하여 그림을 참조하는 것을 고려해야 합니다.

첫 번째 figcaption 요소 자식 요소는, 만약 있다면, figure 요소의 콘텐츠의 캡션을 나타냅니다. 자식 figcaption 요소가 없는 경우 캡션은 존재하지 않습니다.

figure 요소의 내용은 주변 흐름의 일부입니다. 예를 들어 이미지 공유 사이트에서 사진을 표시하는 것이 페이지의 목적이라면, figurefigcaption 요소를 사용하여 해당 figure에 대한 캡션을 명시적으로 제공할 수 있습니다. 주변 흐름과는 관련이 없거나 별도의 목적을 가지는 콘텐츠의 경우, aside 요소를 사용해야 하며(그리고 figure를 감쌀 수 있습니다). 예를 들어, article에서 내용을 반복하는 인용문은 콘텐츠의 일부가 아니라 독자를 유도하거나 주요 주제를 강조하기 위한 반복이므로 figure보다는 aside에 포함하는 것이 더 적절합니다.

이 예제는 코드 목록을 마크업하는 데 사용된 figure 요소를 보여줍니다.

<p><a href="#l4">리스트 4</a>에서 우리는 기본 핵심 인터페이스 API 선언을 봅니다.</p>
<figure id="l4">
 <figcaption>리스트 4. 기본 핵심 인터페이스 API 선언.</figcaption>
 <pre><code>interface PrimaryCore {
 boolean verifyDataLine();
 undefined sendData(sequence&lt;byte> data);
 undefined initSelfDestruct();
}</code></pre>
</figure>
<p>API는 UTF-8을 사용하도록 설계되었습니다.</p>

여기에서 우리는 페이지의 주요 콘텐츠인 사진을 마크업하는 데 사용된 figure 요소를 봅니다(갤러리와 같은).

<!DOCTYPE HTML>
<html lang="en">
<title>일하는 거품들 — 내 갤러리™</title>
<figure>
 <img src="bubbles-work.jpeg"
      alt="거품이 사무실 의자에 앉아 그의 최신 프로젝트에 열중하고 있습니다.">
 <figcaption>일하는 거품들</figcaption>
</figure>
<nav><a href="19414.html">이전</a><a href="19416.html">다음</a></nav>

이 예에서 우리는 figure가 아닌 이미지와 figure 요소로 마크업된 이미지 및 비디오를 봅니다. 첫 번째 이미지는 예제의 두 번째 문장의 일부이므로 독립된 단위가 아니며 figure에 적합하지 않습니다.

<h2>Malinko의 만화</h2>

<p>이 사건은 만화와 관련된 어떤 "지적 재산권" 침해에 중점을 두었습니다 (참조: Exhibit A). 이 소송은 이러한 말로 끝나는 예고편 이후 시작되었습니다:

<blockquote>
 <img src="promblem-packed-action.png" alt="ROUGH COPY! Promblem-Packed Action!">
</blockquote>

<p>...방영되었습니다. 더 큰 노트북을 들고 있는 변호사가 눈덩이를 사용하여 선제공격을 시작했습니다. 예고편의 전체 사본은 Exhibit B와 함께 포함되어 있습니다.

<figure>
 <img src="ex-a.png" alt="더러운 종이에 그려진 두 개의 낙서.">
 <figcaption>Exhibit A. 소위 <cite>rough copy</cite> 만화.</figcaption>
</figure>

<figure>
 <video src="ex-b.mov"></video>
 <figcaption>Exhibit B. <cite>Rough Copy</cite> 예고편.</figcaption>
</figure>

<p>이 사건은 법정 밖에서 해결되었습니다.

여기서 시의 일부가 figure를 사용하여 마크업되었습니다.

<figure>
 <p>'Twas brillig, and the slithy toves<br>
 Did gyre and gimble in the wabe;<br>
 All mimsy were the borogoves,<br>
 And the mome raths outgrabe.</p>
 <figcaption><cite>Jabberwocky</cite> (첫 번째 절). 루이스 캐롤, 1832-98</figcaption>
</figure>

이 예제에서는, 더 큰 작업의 일부일 수 있는 예로서, 성을 다루는 텍스트에서 중첩된 figure 요소들이 그룹 캡션과 각 figure에 대한 개별 캡션을 제공합니다:

<figure>
 <figcaption>세월에 따른 성의 모습: 각각 1423년, 1858년, 1999년.</figcaption>
 <figure>
  <figcaption>에칭. 익명, 약 1423년.</figcaption>
  <img src="castle1423.jpeg" alt="성에는 하나의 탑과 그 주위를 둘러싼 높은 벽이 있습니다.">
 </figure>
 <figure>
  <figcaption>유화. 마리아 타울, 1858년.</figcaption>
  <img src="castle1858.jpeg" alt="성에는 이제 두 개의 탑과 두 개의 벽이 있습니다.">
 </figure>
 <figure>
  <figcaption>필름 사진. 피터 얀클, 1999년.</figcaption>
  <img src="castle1999.jpeg" alt="성은 폐허가 되었고, 원래의 탑만이 온전하게 남아 있습니다.">
 </figure> 
</figure>

이전 예제는 다음과 같이 더 간결하게 작성될 수 있습니다 (중첩된 figure/figcaption 쌍 대신 title 속성을 사용하여):

<figure>
 <img src="castle1423.jpeg" title="에칭. 익명, 약 1423년."
      alt="성에는 하나의 탑과 그 주위를 둘러싼 높은 벽이 있습니다.">
 <img src="castle1858.jpeg" title="유화. 마리아 타울, 1858년."
      alt="성에는 이제 두 개의 탑과 두 개의 벽이 있습니다."> 
 <img src="castle1999.jpeg" title="필름 사진. 피터 얀클, 1999년."
      alt="성은 폐허가 되었고, 원래의 탑만이 온전하게 남아 있습니다."> 
 <figcaption>세월에 따른 성의 모습: 각각 1423년, 1858년, 1999년.</figcaption> 
</figure>

때때로 figure는 콘텐츠에서 암시적으로만 참조됩니다:

<article>
 <h1>의회에서 재정 협상이 난항을 겪으며 기한이 다가옵니다</h1> 
 <figure>
  <img src="obama-reid.jpeg" alt="오바마와 리드가 함께 앉아 웃고 있는 모습입니다.">
  <figcaption>바락 오바마와 해리 리드. 백악관 언론 사진.</figcaption>
 </figure>
 <p>의회에서 재정 교착 상태를 해결하기 위한 협상이 화요일에 중단되어 양쪽 의회 모두 정부를 재개하고 국가의 차입 권한을 확장하기 위한 방법을 모색하고 있습니다. 기한은 목요일로 다가오고 있습니다.</p> 
 ...
</article>

4.4.13 figcaption 요소

Element/figcaption

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5.1+Chrome8+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
figure 요소의 첫 번째 또는 마지막 자식 요소로 사용될 수 있습니다.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려 사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용합니다.

figcaption 요소는 figure 요소의 나머지 내용을 설명하는 캡션이나 레전드를 나타냅니다.

이 요소는 소스에 대한 추가 정보를 포함할 수 있습니다:

<figcaption>
 <p>오리입니다.</p>
 <p><small>사진 제공: 🌟 뉴스.</small></p>
</figcaption>
<figcaption>
 <p>3룸 아파트의 평균 임대료, 비영리 아파트 제외</p>
 <p>취리히 통계청 — <time datetime=2017-11-14>2017년 11월 14일</time></p>
</figcaption>

4.4.14 main 요소

Element/main

모든 현재 엔진에서 지원됩니다.

Firefox21+Safari7+Chrome26+
Opera16+Edge79+
Edge (Legacy)12+Internet Explorer지원하지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
감지할 수 있는 콘텐츠.
이 요소를 사용할 수 있는 문맥:
플로우 콘텐츠가 예상되는 곳, 단, 계층적으로 올바른 main 요소여야 합니다.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려 사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용합니다.

main 요소는 문서의 주요 콘텐츠를 나타냅니다.

문서에는 main 요소가 hidden 속성이 지정되지 않은 경우 하나만 있어야 합니다.

계층적으로 올바른 main 요소는 조상 요소가 html, body, div, form (접근 가능한 이름이 없는 경우), 및 자율 커스텀 요소로 제한된 요소입니다. 각 main 요소는 계층적으로 올바른 main 요소여야 합니다.

이 예에서 작성자는 페이지의 각 구성 요소가 상자에 렌더링되는 프레젠테이션을 사용했습니다. 페이지의 주요 콘텐츠를 감싸기 위해 (헤더, 푸터, 탐색 표시줄 및 사이드바와는 반대로), main 요소가 사용됩니다.

<!DOCTYPE html>
<html lang="en">
<title>RPG System 17</title>
<style>
 header, nav, aside, main, footer {
   margin: 0.5em; border: thin solid; padding: 0.5em;
   background: #EFF; color: black; box-shadow: 0 0 0.25em #033;
 }
 h1, h2, p { margin: 0; }
 nav, main { float: left; }
 aside { float: right; }
 footer { clear: both; }
</style>
<header>
 <h1>System Eighteen</h1>
</header>
<nav>
 <a href="../16/">← System 17</a>
 <a href="../18/">RPXIX →</a>
</nav>
<aside>
 <p>이 시스템에는 HP 메커니즘이 없으므로 치유가 없습니다.</p>
</aside>
<main>
 <h2>캐릭터 생성</h2>
 <p>속성(마법, 힘, 민첩성)은 레벨당 한 포인트의 비용으로 구매할 수 있습니다.</p>
 <h2>주사위 굴리기</h2>
 <p>각 만남 시 모든 스킬에 대해 주사위를 굴리세요. 상대보다 높은 수를 굴리면 승리합니다.</p>
</main>
<footer>
 <p>Copyright © 2013</footer>
</html>

다음 예에서 여러 main 요소가 사용되며 스크립트가 사용되어 탐색이 서버 라운드트립 없이 작동하고 현재가 아닌 요소에 hidden 속성을 설정합니다:

<!doctype html>
<html lang=en-CA>
<meta charset=utf-8>
<title></title>
<link rel=stylesheet href=spa.css>
<script src=spa.js async></script>
<nav>
 <a href=/>Home</a>
 <a href=/about>About</a>
 <a href=/contact>Contact</a>
</nav>
<main>
 <h1>Home</h1></main>
<main hidden>
 <h1>About</h1></main>
<main hidden>
 <h1>Contact</h1></main>
<footer>Made with ❤️ by <a href=https://example.com/>Example 👻</a>.</footer>

4.4.15 search 요소

요소/search

현재 엔진에서 지원되지 않음.

Firefox아니오Safari아니오Chrome아니오
Opera아니오Edge아니오
Edge (Legacy)아니오Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android아니오WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
인식 가능한 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서의 태그 생략:
어떤 태그도 생략할 수 없음.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement을 사용합니다.

search 요소는 검색 또는 필터링 작업과 관련된 양식 제어나 기타 콘텐츠를 포함하는 문서 또는 애플리케이션의 일부를 나타냅니다. 이는 웹사이트나 애플리케이션에 대한 검색, 현재 웹 페이지에서의 검색 또는 필터링 방법, 또는 전체 인터넷 또는 그 하위 섹션에 대한 전역 검색 기능일 수 있습니다.

search 요소는 검색 결과를 단순히 표시하는 데 사용하는 것이 적절하지 않지만, '빠른 검색' 결과의 일부로서 제안 및 링크를 포함할 수 있습니다. 반면에 검색 결과가 포함된 웹 페이지는 해당 웹 페이지의 주요 콘텐츠로 제시될 것으로 예상됩니다.

다음 예에서 작성자는 웹 페이지의 header에 검색 양식을 포함하고 있습니다:

<header>
  <h1><a href="/">내 멋진 블로그</a></h1>
  ...
  <search>
    <form action="search.php">
      <label for="query">기사 찾기</label>
      <input id="query" name="q" type="search">
      <button type="submit">검색</button>
    </form>
  </search>
</header>

이 예에서 작성자는 웹 애플리케이션의 검색 기능을 JavaScript만으로 구현했습니다. 서버 측 제출을 수행하기 위해 form 요소를 사용하지 않았지만, 포함된 search 요소는 하위 콘텐츠의 목적이 검색 기능을 나타낸다고 의미적으로 식별합니다.

<search>
  <label>
    검색 및 필터링
    <input type="search" id="query">
  </label>
  <label>
    <input type="checkbox" id="exact-only">
    정확한 일치만 검색
  </label>

  <section>
    <h3>검색 결과:</h3>
    <ul id="results">
      <li>
        <p><a href="services/consulting">컨설팅 서비스</a></p>
        <p>
          당사의 통합 컨설턴트 Bob과 Bob을 통해 비즈니스를 개선할 수 있는 방법을 알아보세요.
        </p>
      </li>
      ...
    </ul>
    <!--
      쿼리 결과가 없거나 모든 결과가 필터링된 경우
      여기에 결과 없음 메시지를 렌더링합니다.
    -->
    <output id="no-results"></output>
  </section>
</search>

다음 예에서 페이지에는 두 가지 검색 기능이 있습니다. 첫 번째는 웹 페이지의 header에 위치하여 웹사이트의 콘텐츠를 검색하는 전역 메커니즘 역할을 합니다. 그 목적은 지정된 title 속성으로 표시됩니다. 두 번째는 현재 페이지의 콘텐츠를 검색 및 필터링하는 메커니즘으로, 페이지의 주요 콘텐츠의 일부로 포함됩니다. 이 메커니즘의 목적을 나타내기 위해 헤딩을 포함하고 있습니다.

<body>
  <header>
    ...
    <search title="Website">
      ...
    </search>
  </header>
  <main>
    <h1>귀하의 위치 근처 호텔</h1>
     <search>
       <h2>결과 필터링</h2>
       ...
     </search>
     <article>
      <!-- 검색 결과 콘텐츠 -->
    </article>
  </main>
</body>

4.4.16 div 요소

Element/div

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
범주:
플로우 콘텐츠.
인식 가능한 콘텐츠.
이 요소가 사용될 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
dl 요소의 자식으로.
콘텐츠 모델:
dl 요소의 자식인 경우: 하나 이상의 dt 요소와 하나 이상의 dd 요소, 스크립트 지원 요소와 혼합될 수 있음.
dl 요소의 자식이 아닌 경우: 플로우 콘텐츠.
텍스트/HTML에서 태그 생략:
태그를 생략할 수 없음.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자를 위한 가이드.
구현자를 위한 가이드.
DOM 인터페이스:
[Exposed=Window]
interface HTMLDivElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 또한 사용되지 않는 멤버 포함
};

div 요소는 특별한 의미가 없습니다. 자식 요소를 나타냅니다. class, lang, title 속성을 사용하여 연속된 요소 그룹에 공통적인 의미를 마크업하는 데 사용할 수 있습니다. 또한 dl 요소 내에서 dtdd 요소 그룹을 감싸는 데 사용할 수 있습니다.

작성자는 div 요소를 최후의 수단으로 생각하고, 다른 적합한 요소가 없을 때만 사용하는 것이 좋습니다. 더 적합한 요소를 사용하면 독자의 접근성이 향상되고 작성자가 더 쉽게 유지 관리할 수 있습니다.

예를 들어, 블로그 게시물은 article 요소로 마크업되고, 장은 section 요소로 마크업되며, 페이지의 내비게이션 도구는 nav 요소로, 양식 컨트롤 그룹은 fieldset 요소로 마크업됩니다.

반면, div 요소는 스타일 목적이나 섹션 내에서 여러 단락을 동일한 방식으로 주석을 달기 위해 유용할 수 있습니다. 다음 예에서는 div 요소를 사용하여 두 단락의 언어를 설정하는 방법을 보여줍니다.

<article lang="en-US">
<h1>나의 언어 사용과 나의 고양이들</h1>
<p>내 고양이의 행동은 그녀의 부재 이후 크게 변하지 않았지만, 그녀는 이웃들에게 종종 새로운 외모를 자랑합니다.</p>
<div lang="en-GB">
<p>내 다른 고양이는 검정색과 흰색으로, 매우 귀엽습니다. 오늘 우리는 그와 함께 도로를 걸어 수영장으로 갔습니다. 어제는 이웃을 방문했다고 합니다. 아마도 우리의 아파트가 그들의 아파트와 거울 이미지라는 것을 인식하고 있는 것 같습니다.</p>
<p>음, 방금 전 단락에서 영국 영어를 사용한 것을 눈치챘습니다. 하지만 저는 미국 영어로 작성해야 합니다. 그래서 "pavement"나 "flat" 또는 "colour"라고 말해서는 안 됩니다...</p>
</div>
<p>"sidewalk", "apartment", "color"라고 말해야겠네요!</p>
</article>

4.5 텍스트 수준의 시맨틱

4.5.1 a 요소

요소/a

현재 모든 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAnchorElement

현재 모든 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
카테고리:
Flow content.
Phrasing content.
요소에 href 속성이 있는 경우: Interactive content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
투명, 그러나 인터랙티브 콘텐츠 하위 요소나 a 요소의 하위 요소, 또는 tabindex 속성이 지정된 하위 요소가 없어야 함.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
href하이퍼링크의 주소
target내비게이블하이퍼링크 내비게이션을 위해
download — 리소스를 탐색 대신 다운로드할 것인지 여부와 이 경우 파일 이름
ping핑할 URL
rel — 문서 내의 하이퍼링크와 목적지 리소스 사이의 관계
hreflang — 링크된 리소스의 언어
type — 참조된 리소스 유형에 대한 힌트
referrerpolicy — 요소가 시작한 가리키는 정책fetches
접근성 고려사항:
요소에 href 속성이 있는 경우: 작성자용; 구현자용.
그 외의 경우: 작성자용; 구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLAnchorElement : HTMLElement {
[HTMLConstructor] constructor();

[CEReactions] attribute DOMString target;
[CEReactions] attribute DOMString download;
[CEReactions] attribute USVString ping;
[CEReactions] attribute DOMString rel;
[SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
[CEReactions] attribute DOMString hreflang;
[CEReactions] attribute DOMString type;

[CEReactions] attribute DOMString text;

[CEReactions] attribute DOMString referrerPolicy;

// obsolete한 멤버도 포함함
};
HTMLAnchorElement includes HTMLHyperlinkElementUtils;

a 요소에 href 속성이 있다면, 이는 다음을 나타냅니다. 하이퍼링크 (하이퍼텍스트 앵커)로, 요소의 내용에 의해 레이블이 지정됩니다.

a 요소에 href 속성이 없다면, 해당 요소는 링크가 있을 경우를 위해 자리 표시자를 나타냅니다. 이 자리 표시자는 요소의 내용으로만 구성됩니다.

target, download, ping, rel, hreflang, type, 및 referrerpolicy 속성은 href 속성이 없는 경우 생략해야 합니다.

itemprop 속성이 a 요소에 지정된 경우, href 속성도 반드시 지정되어야 합니다.

사이트가 모든 페이지에 일관된 탐색 툴바를 사용하는 경우, 해당 페이지로 연결되는 링크는 a 요소를 사용하여 표시할 수 있습니다:

<nav>
<ul>
<li> <a href="/"></a> </li>
<li> <a href="/news">뉴스</a> </li>
<li> <a>예제</a> </li>
<li> <a href="/legal">법률</a> </li>
</ul>
</nav>

href, target, download, ping, 및 referrerpolicy 속성은 사용자가 하이퍼링크를 따라갈 때 또는 하이퍼링크를 다운로드할 때 생성된 a 요소의 동작에 영향을 미칩니다. rel, hreflang, 및 type 속성은 사용자가 링크를 따라가기 전에 대상 리소스의 성격을 사용자에게 나타내는 데 사용할 수 있습니다.

a.text

textContent와 동일.

HTMLAnchorElement/download

현재 모든 엔진에서 지원됨.

Firefox20+Safari10.1+Chrome15+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAnchorElement/rel

현재 모든 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

IDL 속성 download, ping, target, rel, hreflang, 및 type은 해당 이름의 콘텐츠 속성을 반영해야 합니다.

HTMLAnchorElement/relList

현재 모든 엔진에서 지원됨.

Firefox30+Safari9+Chrome65+
Opera?Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

IDL 속성 relListrel 콘텐츠 속성을 반영해야 합니다.

HTMLAnchorElement/referrerPolicy

현재 모든 엔진에서 지원됨.

Firefox50+Safari14+Chrome52+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

IDL 속성 referrerPolicyreferrerpolicy 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

속성 text의 getter는 이 요소의 하위 텍스트 콘텐츠를 반환해야 합니다.

text 속성의 setter는 주어진 값으로 이 요소 내부의 모든 문자열을 교체해야 합니다.

a 요소는 전체 문단, 목록, 표 등으로 감쌀 수 있으며, 다른 링크나 버튼과 같은 인터랙티브 콘텐츠가 없을 경우 전체 섹션을 포함할 수도 있습니다. 이 예제는 광고 블록 전체를 링크로 만들 수 있는 방법을 보여줍니다:

<aside class="광고">
<h1>광고</h1>
<a href="https://ad.example.com/?adid=1929&amp;pubid=1422">
<section>
<h1>Mellblomatic 9000!</h1>
<p>모든 위젯을 멜블롬으로 변환하십시오!</p>
<p>배송비 별도 9.99달러에 구매할 수 있습니다.</p>
</section>
</a>
<a href="https://ad.example.com/?adid=375&amp;pubid=1422">
<section>
<h1>Mellblom 브라우저</h1>
<p>빛의 속도로 웹 브라우징을 즐기세요.</p>
</p>다른 어떤 브라우저도 더 빠르지 않습니다!</p>
</section>
</a>
</aside>

다음 예제는 스크립트를 사용하여 구직 공고 표의 전체 행을 효과적으로 하이퍼링크로 만드는 방법을 보여줍니다:

<table>
<tr>
<th>직위
<th><th>위치
</tr>
<td><a href="/jobs/manager">매니저</a>
<td>원격
<td>원격
</tr>
<td><a href="/jobs/director">디렉터</a>
<td>원격
<td>원격
</tr>
<td><a href="/jobs/astronaut">우주비행사</a>
<td>건축
<td>원격
</table>
<script>
document.querySelector("table").onclick = ({ target }) => {
if (target.parentElement.localName === "tr") {
const link = target.parentElement.querySelector("a");
if (link) {
link.click();
}
}
}
</script>

4.5.2 em 요소

요소/em

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

em 요소는 내용의 강한 강조를 나타냅니다.

특정 내용이 가지는 강도의 수준은 상위 em 요소의 수에 따라 결정됩니다.

강조의 위치는 문장의 의미를 바꿉니다. 따라서 이 요소는 콘텐츠의 중요한 부분을 형성합니다. 이러한 방식으로 강조가 사용되는 정확한 방법은 언어에 따라 다릅니다.

다음 예제는 강조의 위치를 변경하면 의미가 어떻게 달라지는지를 보여줍니다. 먼저, 아무런 강조가 없는 일반적인 사실을 나타내는 문장입니다:

<p>고양이는 귀여운 동물입니다.</p>

첫 단어를 강조함으로써 논의되고 있는 동물의 종류가 의문임을 암시합니다 (아마도 누군가가 개가 귀엽다고 주장하고 있을 때):

<p><em>고양이</em>는 귀여운 동물입니다.</p>

강조를 동사로 옮기면 전체 문장의 진실성이 의문임을 강조합니다 (아마도 누군가가 고양이가 귀엽지 않다고 말하고 있을 때):

<p>고양이는 <em>귀엽습니다</em>.</p>

강조를 형용사로 옮기면 고양이의 정확한 성격이 재확인됩니다 (아마도 누군가가 고양이가 사나운 동물이라고 제안했을 때):

<p>고양이는 <em>귀여운</em> 동물입니다.</p>

마찬가지로, 누군가가 고양이가 채소라고 주장했다면, 이를 수정하려는 사람은 마지막 단어를 강조할 것입니다:

<p>고양이는 귀여운 <em>동물입니다</em>.</p>

문장 전체를 강조함으로써 화자가 주장을 강하게 펼치려는 것이 명확해집니다. 이와 같은 유형의 강조는 일반적으로 구두점에도 영향을 미치며, 여기서도 느낌표를 사용한 이유가 바로 그것입니다.

<p><em>고양이는 귀여운 동물입니다!</em></p>

분노와 함께 귀여움을 강조하려면 다음과 같은 마크업을 사용할 수 있습니다:

<p><em>고양이는 <em>귀여운</em> 동물입니다!</em></p>

em 요소는 일반적인 "이탤릭체" 요소가 아닙니다. 때로는 텍스트가 다른 단락과 차별화되어야 할 때가 있으며, 마치 다른 분위기나 목소리를 가진 것처럼 보이도록 합니다. 이러한 경우 i 요소가 더 적합합니다.

em 요소는 중요성을 전달하려는 것이 아닙니다. 이러한 목적에는 strong 요소가 더 적합합니다.

4.5.3 strong 요소

요소/strong

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

strong 요소는 내용의 강한 중요성, 진지함 또는 긴급성을 나타냅니다.

중요성: strong 요소는 제목, 캡션, 또는 문단에서 다른 부분에 비해 정말로 중요한 부분을 구별하기 위해 사용할 수 있습니다. (이는 hgroup 요소로 마크업할 수 있는 하위 제목과는 다릅니다.)

예를 들어, 이전 문단의 첫 번째 단어는 나머지 세부 내용보다 중요성을 구별하기 위해 strong으로 마크업되어 있습니다.

진지함: strong 요소는 경고나 주의 문구를 마크업하는 데 사용할 수 있습니다.

긴급성: strong 요소는 사용자가 문서의 다른 부분보다 먼저 보아야 하는 내용을 나타내는 데 사용할 수 있습니다.

콘텐츠의 상대적 중요도는 상위 strong 요소의 수에 따라 결정됩니다. 각 strong 요소는 그 내용의 중요성을 증가시킵니다.

strong 요소로 텍스트의 중요성을 변경해도 문장의 의미는 바뀌지 않습니다.

여기서 "장"이라는 단어와 실제 장 번호는 일반적인 텍스트일 뿐이며, 실제 장의 이름은 strong으로 마크업되어 있습니다:

<h1>1장: <strong>프락시스</strong></h1>

다음 예제에서, 캡션에 있는 다이어그램의 이름은 strong으로 마크업되어 있어, 일반 텍스트(이전) 및 설명(이후)과 구별됩니다:

<figcaption>그림 1. <strong>개미 군집의 역학</strong>. 이 군집의 개미들은 열원(왼쪽 상단)과 음식원(오른쪽 하단)에 영향을 받습니다.</figcaption>

이 예제에서, 제목은 실제로 "꽃, 벌, 그리고 꿀"이지만, 저자는 제목에 가벼운 추가 내용을 포함시켰습니다. strong 요소는 따라서 첫 번째 부분을 나머지와 구별하기 위해 사용되었습니다.

<h1><strong>꽃, 벌, 그리고 꿀</strong> 및 이해할 수 없는 다른 것들</h1>

여기 게임에서 경고 문구의 예가 있으며, 각 부분은 중요도에 따라 마크업되어 있습니다:

<p><strong>경고.</strong> 이 던전은 위험합니다.
<strong>오리를 피하세요.</strong> 발견한 금은 가져가세요.
<strong><strong>다이아몬드는 절대 가져가지 마세요</strong>, 
그것들은 폭발하며 <strong>10미터 이내의 모든 것을 파괴할 것입니다.</strong></strong> 경고를 받았습니다.</p>

이 예제에서, strong 요소는 사용자가 먼저 읽어야 할 부분을 나타내기 위해 사용되었습니다.

<p>Remy에 오신 것을 환영합니다, 알림 시스템입니다.</p>
<p>오늘의 작업:</p>
<ul>
<li><p><strong>오븐을 끄세요.</strong></p></li>
<li><p>쓰레기를 내놓으세요.</p></li>
<li><p>세탁을 하세요.</p></li>
</ul>

4.5.4 small 요소

요소/small

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

small 요소는 작은 글씨로 부가 설명을 나타냅니다.

작은 글씨는 일반적으로 면책 조항, 주의사항, 법적 제한 또는 저작권에 사용됩니다. 또한, 저작권 표시나 라이센스 요구사항을 충족시키기 위해 사용되기도 합니다.

small 요소는 em 요소로 강조된 텍스트나 strong 요소로 중요한 것으로 표시된 텍스트의 중요성을 "감소시키지" 않습니다. 강조되지 않거나 중요한 것으로 표시되지 않은 텍스트를 표시하려면 em 또는 strong 요소로 마크업하지 마십시오.

small 요소는 여러 단락, 목록, 또는 텍스트 섹션과 같은 확장된 텍스트에 사용되어서는 안 됩니다. 이 요소는 짧은 텍스트에만 사용하도록 설계되었습니다. 예를 들어, 이용 약관을 나열하는 페이지의 텍스트는 small 요소에 적합하지 않습니다. 이러한 경우, 텍스트는 부가 설명이 아니라 페이지의 주요 내용입니다.

small 요소는 소제목에 사용되어서는 안 됩니다. 소제목에는 hgroup 요소를 사용하십시오.

이 예제에서는 small 요소를 사용하여 호텔 객실의 가격에 부가가치세가 포함되지 않았음을 나타냅니다:

<dl>
 <dt>싱글 룸
 <dd>199 € <small>조식 포함, VAT 미포함</small>
 <dt>더블 룸
 <dd>239 € <small>조식 포함, VAT 미포함</small>
</dl>

두 번째 예제에서는 small 요소가 기사 내의 부가 설명에 사용되었습니다.

<p>Example Corp은 오늘 2분기 실적이 사상 최고치를 기록했다고 발표했습니다 <small>(전체 공시: Foo News는 Example Corp의 자회사입니다)</small>, 이는 3분기 Demo Group과의 합병에 대한 추측을 낳고 있습니다.</p>

이는 사이드바와는 다릅니다. 사이드바는 여러 단락 길이일 수 있으며, 본문 텍스트의 주 흐름에서 벗어난 것입니다. 다음 예제에서는 동일한 기사에서 사이드바를 볼 수 있습니다. 이 사이드바에는 사이드바의 정보 출처를 나타내는 작은 글씨가 포함되어 있습니다.

<aside>
 <h1>Example Corp</h1>
 <p>이 회사는 주로 소프트웨어 및 웹사이트를 만듭니다.</p>
 <p>Example Corp의 회사 미션은 "샘플을 기반으로 한 엔터테인먼트 및 뉴스를 제공하는 것"입니다.</p>
 <p><small>정보는 <a
 href="https://example.com/about.html">example.com</a> 홈페이지에서 얻었습니다.</small></p>
</aside>

마지막 예제에서는 small 요소가 중요한 작은 글씨로 마크업되었습니다.

<p><strong><small>이 서비스를 계속 사용하면 키스가 발생합니다.</small></strong></p>

4.5.5 s 요소

요소/s

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

s 요소는 더 이상 정확하지 않거나 유효하지 않은 내용을 나타냅니다.

s 요소는 문서 편집을 나타낼 때 적절하지 않습니다. 문서에서 텍스트를 삭제된 것으로 표시하려면 del 요소를 사용하십시오.

이 예제에서는 특정 제품의 새로운 판매 가격이 책정되면서 권장 소매 가격이 더 이상 유효하지 않게 표시되었습니다.

<p>우리의 아이스 티와 레모네이드를 구매하세요!</p>
<p><s>권장 소매 가격: 병당 $3.99</s></p>
<p><strong>이제 병당 단 $2.99에 판매 중!</strong></p>

4.5.6 cite 요소

요소/cite

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

cite 요소는 작품의 제목을 나타냅니다(예: 책, 논문, 에세이, 시, 악보, 노래, 대본, 영화, TV 프로그램, 게임, 조각, 회화, 연극 공연, 오페라, 뮤지컬, 전시회, 법적 사건 보고서, 컴퓨터 프로그램 등). 이것은 인용되거나 상세히 참조된 작품일 수도 있고, 혹은 그냥 지나가며 언급된 작품일 수도 있습니다.

사람의 이름은 작품의 제목이 아니며 — 사람을 "작품"이라고 부르는 경우가 있더라도 — 따라서 이 요소를 사람의 이름을 마크업하는 데 사용해서는 안 됩니다. (어떤 경우에는 b 요소가 이름을 마크업하는 데 적합할 수 있습니다; 예를 들어 유명인들의 이름이 키워드로서 스타일을 달리하여 눈에 띄도록 표시되는 가십 기사에서. 다른 경우에는 정말로 요소가 필요하다면 span 요소를 사용할 수 있습니다.)

다음 예제는 cite 요소의 일반적인 사용 예를 보여줍니다:

<p>내가 가장 좋아하는 책은 Peter F. Hamilton의 <cite>The Reality Dysfunction</cite>입니다. 내가 가장 좋아하는 만화는 Stephan Pastis의 <cite>Pearls Before Swine</cite>입니다. 내가 가장 좋아하는 곡은 Cannonball Adderley Sextet의 <cite>Jive Samba</cite>입니다.</p>

이것은 올바른 사용 예입니다:

<p>Wikipedia의 <cite>HTML</cite> 문서에 따르면, 2008년 2월 중순 기준으로, 속성 값을 따옴표 없이 남겨두는 것은 안전하지 않습니다. 이는 분명히 지나치게 단순화된 설명입니다.</p>

그러나 다음은 잘못된 사용 예입니다. 여기서 cite 요소는 작품의 제목보다 훨씬 많은 내용을 포함하고 있습니다:

<!-- 이 예제는 잘못된 사용 예를 보여주는 것으로, 복사하지 마세요! -->
<p>According to <cite>the Wikipedia article on HTML</cite>, as it
stood in mid-February 2008, leaving attribute values unquoted is
unsafe. This is obviously an over-simplification.</p>

cite 요소는 서지 정보의 인용에서 중요한 부분이지만, 제목만을 마크업하는 데 사용됩니다:

<p><cite>Universal Declaration of Human Rights</cite>, United Nations,
1948년 12월. 총회 결의 217 A (III)에서 채택됨.</p>

인용인용문과 다릅니다(인용문에는 q 요소가 적합합니다).

이것은 잘못된 사용 예입니다, 왜냐하면 cite 요소는 인용문을 위한 것이 아니기 때문입니다:

<p><cite>이것은 잘못되었습니다!</cite>, 이안이 말했습니다.</p>

이것도 잘못된 사용 예입니다, 왜냐하면 사람이 작품이 아니기 때문입니다:

<p><q>이것도 잘못되었습니다!</q>, <cite>이안</cite>이 말했습니다.</p>

올바른 사용 예에서는 cite 요소를 사용하지 않습니다:

<p><q>이것이 맞습니다</q>, 이안이 말했습니다.</p>

위에서 언급한 것처럼, b 요소가 특정 유형의 문서에서 이름을 키워드로 표시하는 데 유용할 수 있습니다:

<p>그리고 나서 <b>이안</b><q>이것이 가십 칼럼에서는 맞을 수도 있다고 말했습니다.</q>.</p>

4.5.7 q 요소

요소/q

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
cite — 인용문의 출처나 편집에 대한 추가 정보에 대한 링크
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLQuoteElement를 사용.

q 요소는 다른 출처에서 인용된 phrasing content를 나타냅니다.

요소의 내용을 인용하는 인용 구두점(따옴표 등)은 q 요소 바로 앞, 뒤, 또는 내부에 나타나지 않아야 하며, 사용자 에이전트가 렌더링 시 삽입합니다.

q 요소 내부의 콘텐츠는 다른 출처에서 인용된 것이어야 하며, 그 출처의 주소가 있는 경우 cite 속성에 명시될 수 있습니다. 출처는 소설이나 대본에서 인용된 가상의 것일 수도 있습니다.

cite 속성이 존재하는 경우, 그것은 유효한 URL이어야 합니다. 해당 속성의 값은 요소의 노드 문서에 상대적으로 파싱되어야 합니다. 사용자 에이전트는 사용자가 이러한 인용 링크를 따를 수 있도록 허용할 수 있지만, 이러한 링크는 주로 개인적인 용도(예: 사이트의 인용문 사용 통계를 수집하는 서버 측 스크립트 등)를 위한 것이며, 독자를 위한 것은 아닙니다.

q 요소는 인용문을 나타내지 않는 따옴표 대신 사용되어서는 안 됩니다. 예를 들어, q 요소를 사용하여 비꼬는 말을 마크업하는 것은 부적절합니다.

q 요소를 사용하여 인용문을 마크업하는 것은 전적으로 선택 사항이며, q 요소 없이 명시적인 인용 구두점을 사용하는 것도 마찬가지로 올바릅니다.

다음은 q 요소를 사용한 간단한 예제입니다:

<p>그 남자는 <q>불가능한 일은 시간이 더 걸린다</q>고 말했다. 나는 그와 동의하지 않았다.</p>

다음은 q 요소 내에 명시적 인용 링크와 외부 인용을 모두 포함한 예제입니다:

<p>W3C 페이지 <cite>About W3C</cite>에서는 W3C의
미션이 <q cite="https://www.w3.org/Consortium/">웹의 장기적인 성장을 보장하는 프로토콜과
지침을 개발하여 월드 와이드 웹을 최대한으로 발전시키는 것</q>이라고 말합니다. 나는 이 미션에 동의하지 않습니다.</p>

다음 예제에서는 인용문 자체에 인용문이 포함된 경우를 보여줍니다:

<p><cite>Example One</cite>에서 그는 <q>그 남자는
불가능한 일은 시간이 더 걸린다고 말했다</q>고 썼습니다. 나는 그와 더 동의하지 않았습니다</q>. 음, 나는 더 동의하지 않습니다!</p>

다음 예제에서는 q 요소 대신 따옴표가 사용되었습니다:

<p>그의 가장 좋은 주장은 ❝나는 동의하지 않는다❞였고,
나는 그것이 웃기다고 생각했습니다.</p>

다음 예제에서는 인용문이 없으며, 따옴표는 단어를 지칭하는 데 사용됩니다. 이 경우 q 요소를 사용하는 것은 부적절합니다.

<p>"ineffable"이라는 단어는 그 캠페인의 잘못된 관리로 인한
재난을 묘사하는 데 사용될 수 있었습니다.</p>

4.5.8 dfn 요소

요소/dfn

현재 모든 엔진에서 지원됨.

Firefox1+Safari6+Chrome15+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content, 그러나 하위 요소에 dfn 요소가 없어야 합니다.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
또한, 이 요소에서는 title 속성이 특별한 의미를 가집니다: 약어의 전체 용어 또는 확장
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

dfn 요소는 용어의 정의 인스턴스를 나타냅니다. dfn 요소의 가장 가까운 상위 요소인 단락, 설명 목록 그룹, 또는 섹션dfn 요소에 의해 정의된 용어의 정의를 포함해야 합니다.

정의 용어: dfn 요소에 title 속성이 있으면, 그 속성의 정확한 값이 정의되는 용어입니다. 그렇지 않고 요소에 정확히 하나의 자식 요소 노드만 있고 텍스트 노드가 없으며, 그 자식 요소가 abbr 요소이고 title 속성이 있는 경우, 그 속성의 정확한 값이 정의되는 용어입니다. 그렇지 않으면, dfn 요소의 하위 텍스트 콘텐츠가 정의되는 용어를 제공합니다.

title 속성이 dfn 요소에 존재하는 경우, 그것은 정의되는 용어만을 포함해야 합니다.

title 속성은 상위 요소에서 dfn 요소에 영향을 미치지 않습니다.

a 요소가 dfn 요소로 연결될 때, 그것은 dfn 요소에 의해 정의된 용어의 인스턴스를 나타냅니다.

다음 조각에서는 "Garage Door Opener" 용어가 첫 번째 단락에서 처음 정의된 후, 두 번째 단락에서 사용됩니다. 두 경우 모두 실제로 표시되는 것은 그 약어입니다.

<p>The <dfn><abbr title="Garage Door Opener">GDO</abbr></dfn>
is a device that allows off-world teams to open the iris.</p>
<!-- ... later in the document: -->
<p>Teal'c activated his <abbr title="Garage Door Opener">GDO</abbr>
and so Hammond ordered the iris to be opened.</p>

a 요소를 추가하면, 참조를 명시적으로 할 수 있습니다:

<p>The <dfn id=gdo><abbr title="Garage Door Opener">GDO</abbr></dfn>
is a device that allows off-world teams to open the iris.</p>
<!-- ... later in the document: -->
<p>Teal'c activated his <a href=#gdo><abbr title="Garage Door Opener">GDO</abbr></a>
and so Hammond ordered the iris to be opened.</p>

4.5.9 abbr 요소

요소/abbr

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome2+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer7+
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
phrasing content.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
또한, 이 요소에서는 title 속성이 특별한 의미를 가집니다: 약어의 전체 용어 또는 확장
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

abbr 요소는 약어 또는 두문자어를 나타내며, 선택적으로 그 확장을 포함할 수 있습니다. title 속성은 약어의 확장을 제공하는 데 사용될 수 있습니다. 이 속성이 지정된 경우, 약어의 확장을 포함해야 하며, 다른 내용은 포함할 수 없습니다.

아래 단락에는 abbr 요소로 표시된 약어가 포함되어 있습니다. 이 단락은 "Web Hypertext Application Technology Working Group"이라는 용어를 정의합니다.

<p>The <dfn id=whatwg><abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr></dfn>
is a loose unofficial collaboration of web browser manufacturers and
interested parties who wish to develop new technologies designed to
allow authors to write and deploy Applications over the World Wide
Web.</p>

이를 다르게 작성하는 방법은 다음과 같습니다:

<p>The <dfn id=whatwg>Web Hypertext Application Technology
Working Group</dfn> (<abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr>)
is a loose unofficial collaboration of web browser manufacturers and
interested parties who wish to develop new technologies designed to
allow authors to write and deploy Applications over the World Wide
Web.</p>

이 단락에는 두 개의 약어가 있습니다. 한 개의 약어만 정의되었으며, 확장이 지정되지 않은 다른 약어는 abbr 요소를 사용하지 않았습니다.

<p>The
<abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr>
started working on HTML5 in 2004.</p>

이 단락은 약어를 정의에 연결합니다.

<p>The <a href="#whatwg"><abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr></a>
community does not have much representation from Asia.</p>

이 단락은 확장을 제공하지 않고 약어를 표시하며, 약어에 스타일을 적용하기 위한 후크로 사용될 수 있습니다(예: 소문자 대문자 변환).

<p>Philip` and Dashiva both denied that they were going to
get the issue counts from past revisions of the specification to
backfill the <abbr>WHATWG</abbr> issue graph.</p>

약어가 복수형일 경우, 확장의 문법적 수(복수 vs 단수)는 요소 내용의 문법적 수와 일치해야 합니다.

여기서 복수형은 요소 밖에 있으므로 확장은 단수입니다:

<p>Two <abbr title="Working Group">WG</abbr>s worked on
this specification: the <abbr>WHATWG</abbr> and the
<abbr>HTMLWG</abbr>.</p>

여기서 복수형은 요소 안에 있으므로 확장은 복수형입니다:

<p>Two <abbr title="Working Groups">WGs</abbr> worked on
this specification: the <abbr>WHATWG</abbr> and the
<abbr>HTMLWG</abbr>.</p>

약어는 반드시 이 요소를 사용해 표시할 필요는 없습니다. 다음과 같은 경우에 유용할 것으로 예상됩니다:

한 번 title 속성에 확장을 제공한다고 해서 동일한 내용을 가진 다른 abbr 요소가 동일한 확장을 가진 것처럼 동작하지는 않을 것입니다. 각 abbr 요소는 독립적입니다.

4.5.10 ruby 요소

요소/ruby

현재 모든 엔진에서 지원됨.

Firefox38+Safari5+Chrome5+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 문맥:
phrasing content이 예상되는 곳.
콘텐츠 모델:
설명 참조.
text/html에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용.

ruby 요소는 하나 이상의 phrasing content를 루비 주석과 함께 표시할 수 있도록 합니다. 루비 주석은 주로 동아시아 타이포그래피에서 발음을 안내하거나 다른 주석을 추가하기 위해 기본 텍스트 옆에 표시되는 짧은 텍스트입니다. 일본어에서는 이 형태의 타이포그래피를 후리가나라고도 합니다.

ruby 요소의 콘텐츠 모델은 다음과 같은 시퀀스 중 하나 이상으로 구성됩니다:

  1. 다음 중 하나:

  2. 다음 중 하나:

rubyrt 요소는 다양한 종류의 주석에 사용할 수 있으며, 특히 (하지만 이에 국한되지 않음) 아래에 설명된 주석에 사용됩니다. 일본어 루비에 관한 자세한 내용과 일본어 루비를 렌더링하는 방법은 일본어 텍스트 레이아웃 요구 사항을 참조하세요. [JLREQ]

이 글을 작성할 당시, CSS는 HTML ruby 요소의 렌더링을 완전히 제어할 수 있는 방법을 아직 제공하지 않습니다. CSS가 아래에 설명된 스타일을 지원하도록 확장되기를 기대합니다.

일본어 개별 문자에 대한 단일 루비

하나 이상의 히라가나 또는 가타카나 문자(루비 주석)가 각 한자 문자(기본 텍스트)에 배치됩니다. 이는 한자 문자의 읽는 법을 제공하기 위해 사용됩니다.

<ruby>B<rt>annotation</ruby>

이 예에서, 각 주석이 개별 기본 문자와 어떻게 일치하는지 확인할 수 있습니다.

<ruby><rt>くん</ruby><ruby><rt></ruby><ruby><rt></ruby>して<ruby><rt>どう</ruby>ぜず。

くんしてどうぜず。

이 예는 다음과 같이 쓸 수도 있습니다. 두 개의 기본 텍스트 세그먼트와 두 개의 주석이 포함된 하나의 ruby 요소를 사용하여 각각 하나의 기본 텍스트 세그먼트와 주석을 포함한 두 개의 연속 ruby 요소로 마크업한 것 대신 다음과 같이 쓸 수 있습니다:

<ruby><rt>くん</rt><rt></ruby><ruby><rt></ruby>して<ruby><rt>どう</ruby>ぜず。
복합어에 대한 단일 루비(주쿠고)

이는 이전 사례와 유사합니다. 복합어(기본 텍스트)의 각 한자 문자에는 히라가나 또는 가타카나 문자(루비 주석)가 읽는 법으로 제공됩니다. 차이점은 기본 텍스트 세그먼트가 서로 분리되지 않고 복합어를 형성한다는 것입니다.

<ruby>B<rt>annotation</rt>B<rt>annotation</ruby>

이 예에서, 각 주석이 개별 기본 문자와 다시 일치하는지 확인할 수 있습니다. 이 예에서는 각 복합어(주쿠고)가 단일 ruby 요소에 해당합니다.

여기에서 예상되는 렌더링은 각 주석이 해당하는 기본 문자 위(또는 수직 텍스트의 경우 옆)에 배치되고, 주석이 인접한 문자와 겹치지 않도록 하는 것입니다.

<ruby><rt></rt><rt>もん</rt></ruby><ruby><rt>ほう</rt><rt>がく</rt></ruby><ruby><rt>ぎょう</rt></rt></ruby>する

もんほうがくぎょうする

주쿠고 루비

이는 이전 사례와 의미적으로 동일합니다(기본 복합어의 각 한자 문자에 히라가나 또는 가타카나 문자로 읽는 법을 주석으로 제공). 그러나 렌더링은 더 복잡한 주쿠고 루비 렌더링입니다.

이는 복합어에 대한 단일 루비의 이전 예제와 동일합니다. 다른 렌더링은 다른 스타일링(예: CSS)을 사용하여 달성할 것으로 예상되며, 여기서는 표시되지 않습니다.

<ruby><rt></rt><rt>もん</rt></ruby><ruby><rt>ほう</rt></rt>がく</rt></ruby><ruby><rt>ぎょう</rt></rt></ruby>する

주쿠고 루비 렌더링에 대한 자세한 내용은 Jukugo Ruby 렌더링을 참조하세요. 일본어 텍스트 레이아웃 요구 사항의 부록 F를 참조하세요. [JLREQ]

의미 설명을 위한 그룹 루비

주석은 발음보다는 (또는 발음과 함께) 기본 텍스트의 의미를 설명합니다. 따라서 기본 텍스트와 주석 모두 여러 문자로 구성될 수 있습니다.

<ruby>BASE<rt>annotation</ruby>

여기서 복합 한자 단어는 주석으로 해당 가타카나를 가지고 있습니다.

<ruby>境界面<rt>インターフェース</ruby>

境界面インターフェース

여기서 복합 한자 단어는 주석으로 영어 번역을 가지고 있습니다.

<ruby lang="ja">編集者<rt lang="en">editor</ruby>

編集者editor

주쿠지 발음을 위한 그룹 루비

일대일 대응이 어려운 경우, 여러 기본 문자에 해당하는 발음 읽기가 있습니다. (영어에서는 "Colonel"과 "Lieutenant"라는 단어가 발음과 개별 문자 간의 직접적인 대응이 다소 불분명한 예입니다.)

이 예에서는 꽃 종 이름에 그룹 루비를 사용하여 발음 읽기가 제공됩니다.

<ruby>紫陽花<rt>あじさい</ruby>

紫陽花あじさい

발음 및 의미 주석을 동시에 포함한 텍스트(양면 루비)

때로는 위에서 설명한 루비 스타일이 결합됩니다.

이로 인해 동일한 기본 세그먼트를 커버하는 두 개의 주석이 생성되면, 주석을 연달아 배치할 수 있습니다.

<ruby>BASE<rt>annotation 1</rt>annotation 2</ruby>
<ruby>B<rt>a</rt>a</ruby><ruby>A<rt>a</rt>a</ruby><ruby>S<rt>a</rt>a</ruby><ruby>E<rt>a</rt>a</ruby>

이 예시에서는 몇 가지 기호에 영어와 프랑스어로 이름이 지정되어 있습니다.

<ruby><rt> Heart <rt lang=fr> Cœur </rt><rt> Shamrock <rt lang=fr> Trèfle </rt><rt> Star <rt lang=fr> Étoile </rt>
</ruby>

다음과 같은 더 복잡한 상황에서는, 내부 주석을 제공하기 위해 중첩된 ruby 요소를 사용하고, 그런 다음 전체 ruby에 "외부" 수준에서 주석을 추가합니다.

<ruby><ruby>B<rt>a</rt>A<rt>n</rt>S<rt>t</rt>E</rt>n</rt></ruby><rt>annotation</ruby>

여기서는 발음과 의미가 루비 주석으로 제공됩니다. 중첩된 ruby 요소의 주석은 각 기본 문자를 위한 단일 루비 발음 주석을 제공하며, 외부 ruby 요소의 자식 요소인 rt 요소의 주석은 히라가나로 의미를 제공합니다.

<ruby><ruby><rt>とう</rt><rt>なん</rt></ruby><rt>たつみ</rt></ruby>

とうなん たつみ の方角

이것은 동일한 예이지만, 의미가 일본어 대신 영어로 제공됩니다:

<ruby><ruby><rt>とう</rt><rt>なん</rt></ruby><rt lang=en>Southeast</rt></ruby>

とうなん Southeast の方角


루비 요소 조상이 없는 루비 요소 내에서는 콘텐츠가 세 가지 범주로 분할됩니다: 기본 텍스트 세그먼트, 주석 세그먼트, 무시된 세그먼트. 무시된 세그먼트는 문서의 의미론에 포함되지 않으며, 일부 요소 간 공백rp 요소로 구성됩니다. 후자는 루비를 전혀 지원하지 않는 레거시 사용자 에이전트를 위해 사용됩니다. 기본 텍스트 세그먼트는 중첩될 수 있으며(하나의 위치에서 두 개의 세그먼트만 중첩될 수 있으며, 중첩된 세그먼트는 겹치는 세그먼트보다 시작점이 앞서거나 종료점이 같거나 늦어야 하고, 종료점이 늦어야 하는 세그먼트는 시작점이 같거나 앞서야 합니다). 주석 세그먼트는 rt 요소와 대응됩니다. 각 주석 세그먼트는 기본 텍스트 세그먼트와 연결될 수 있으며, 각 기본 텍스트 세그먼트는 주석 세그먼트와 연결될 수 있습니다. (적합한 문서에서 각 기본 텍스트 세그먼트는 적어도 하나의 주석 세그먼트와 연결되어 있으며, 각 주석 세그먼트는 하나의 기본 텍스트 세그먼트와 연결되어 있습니다.) 루비 요소는 포함된 기본 텍스트 세그먼트의 집합과 그 기본 텍스트 세그먼트와 주석 세그먼트 간의 매핑을 나타냅니다. 세그먼트는 DOM 범위로 설명되며, 주석 세그먼트 범위는 항상 정확히 하나의 요소로 구성됩니다. [DOM]

특정 시점에서 루비 요소의 콘텐츠 분할 및 범주화는 다음 알고리즘을 실행하여 얻은 결과입니다:

  1. 기본 텍스트 세그먼트를 빈 기본 텍스트 세그먼트 목록으로 설정하며, 각 세그먼트는 잠재적으로 기본 텍스트 하위 세그먼트 목록을 가질 수 있습니다.

  2. 주석 세그먼트를 빈 주석 세그먼트 목록으로 설정하며, 각 세그먼트는 잠재적으로 기본 텍스트 세그먼트나 하위 세그먼트와 연결될 수 있습니다.

  3. root를 알고리즘이 실행되는 루비 요소로 설정합니다.

  4. root루비 요소 조상이 있는 경우, end로 레이블된 단계로 건너뜁니다.

  5. current parentroot로 설정합니다.

  6. index를 0으로 설정합니다.

  7. start index를 null로 설정합니다.

  8. parent start index를 null로 설정합니다.

  9. current base text를 null로 설정합니다.

  10. 시작 모드: indexcurrent parent의 자식 노드 수보다 크거나 같은 경우, end mode로 레이블된 단계로 건너뜁니다.

  11. index 번째 노드가 current parent에서 rt 또는 rp 요소인 경우, 주석 모드로 레이블된 단계로 건너뜁니다.

  12. start indexindex 값을 설정합니다.

  13. 기본 모드: index 번째 노드가 current parent에서 루비 요소이며, current parentroot와 동일한 요소인 경우, 루비 레벨을 추가한 후 시작 모드로 레이블된 단계로 건너뜁니다.

  14. index 번째 노드가 current parent에서 rt 또는 rp 요소인 경우, 현재 기본 텍스트를 설정한 후 주석 모드로 레이블된 단계로 건너뜁니다.

  15. index 값을 1 증가시킵니다.

  16. 기본 모드 후 증가: indexcurrent parent의 자식 노드 수보다 크거나 같은 경우, end mode로 레이블된 단계로 건너뜁니다.

  17. 기본 모드로 레이블된 단계로 돌아갑니다.

  18. 주석 모드: index 번째 노드가 current parent에서 rt 요소인 경우, 루비 주석 추가한 후 주석 모드 증가로 레이블된 단계로 건너뜁니다.

  19. index 번째 노드가 current parent에서 rp 요소인 경우, 주석 모드 증가로 레이블된 단계로 건너뜁니다.

  20. index 번째 노드가 current parent에서 Text 노드가 아니거나, Text 노드이지만 요소 간 공백이 아닌 경우, 기본 모드로 레이블된 단계로 건너뜁니다.

  21. 주석 모드 증가: lookahead indexindex 더하기 1의 값을 설정합니다.

  22. 주석 모드 공백 건너뛰기: lookahead indexcurrent parent의 자식 노드 수와 같은 경우, end mode로 레이블된 단계로 건너뜁니다.

  23. lookahead index 번째 노드가 current parent에서 rt 요소 또는 rp 요소인 경우, indexlookahead index 값을 설정한 후 주석 모드로 레이블된 단계로 건너뜁니다.

  24. lookahead index 번째 노드가 current parent에서 Text 노드가 아니거나, Text 노드이지만 요소 간 공백이 아닌 경우, index를 더 이상 증가시키지 않고 기본 모드로 레이블된 단계로 건너뜁니다(지금까지 본 요소 간 공백이 다음 기본 텍스트 세그먼트의 일부가 됩니다).

  25. lookahead index 값을 1 증가시킵니다.

  26. 주석 모드 공백 건너뛰기로 레이블된 단계로 건너뜁니다.

  27. end 모드: current parentroot와 동일한 요소가 아닌 경우, 루비 레벨을 팝한 후 기본 모드 후 증가로 레이블된 단계로 건너뜁니다.

  28. 종료: 기본 텍스트 세그먼트주석 세그먼트를 반환합니다. 루비 요소의 설명되지 않은 콘텐츠는 암묵적으로 무시된 세그먼트에 포함됩니다.

위 단계에서 현재 기본 텍스트를 설정하라는 지시는 알고리즘의 해당 시점에서 다음 단계를 실행함을 의미합니다:

  1. text range시작current parent, start index경계점이고, 종료current parent, index경계점인 DOM 범위입니다.

  2. new text segmentannotation range 범위로 설명된 기본 텍스트 세그먼트입니다.

  3. new text segment기본 텍스트 세그먼트에 추가합니다.

  4. current base textnew text segment로 설정합니다.

  5. start index를 null로 설정합니다.

위 단계에서 루비 레벨을 추가하라는 지시는 알고리즘의 해당 시점에서 다음 단계를 실행함을 의미합니다:

  1. current parentcurrent parentindex 번째 노드로 설정합니다.

  2. index를 0으로 설정합니다.

  3. saved start indexstart index 값을 설정합니다.

  4. start index를 null로 설정합니다.

위 단계에서 루비 레벨을 팝하라는 지시는 알고리즘의 해당 시점에서 다음 단계를 실행함을 의미합니다:

  1. indexcurrent parentroot에서의 위치로 설정합니다.

  2. current parentroot로 설정합니다.

  3. index 값을 1 증가시킵니다.

  4. start indexsaved start index 값을 설정합니다.

  5. saved start index를 null로 설정합니다.

위 단계에서 루비 주석 추가하라는 지시는 알고리즘의 해당 시점에서 다음 단계를 실행함을 의미합니다:

  1. rtcurrent parentindex 번째 노드인 rt 요소로 설정합니다.

  2. annotation rangecurrent parent, index경계점이며, current parent, index 더하기 1의 경계점인 DOM 범위입니다(i.e. rt만 포함합니다).

  3. new annotation segmentannotation range 범위로 설명된 주석 세그먼트입니다.

  4. current base text가 null이 아닌 경우, new annotation segmentcurrent base text와 연결합니다.

  5. new annotation segment주석 세그먼트에 추가합니다.

이 예제에서는 일본어 텍스트 漢字의 각 한자가 히라가나로 읽기가 주석으로 추가됩니다.

...
<ruby><rt>かん</rt><rt></rt></ruby>
...

이는 다음과 같이 렌더링될 수 있습니다:

두 개의 주요 한자가 있으며, 각 한자 위에 더 작은 글꼴로 히라가나 주석이 렌더링되어 있습니다.

이 예제에서는 전통 중국어 텍스트 漢字의 각 한자가 보포모포로 읽기가 주석으로 추가됩니다.

<ruby><rt>ㄏㄢˋ</rt><rt>ㄗˋ</rt></ruby>

이는 다음과 같이 렌더링될 수 있습니다:

두 개의 주요 한자가 있으며, 각 한자 옆에 더 작은 글꼴로 보포모포 주석이 렌더링되어 있습니다.

이 예제에서는 간체 중국어 텍스트 汉字의 각 한자가 병음으로 읽기가 주석으로 추가됩니다.

...<ruby><rt>hàn</rt><rt></rt></ruby>...

이는 다음과 같이 렌더링될 수 있습니다:

두 개의 주요 한자가 있으며, 각 한자 위에 더 작은 글꼴로 병음 주석이 렌더링되어 있습니다.

이 예제에서는 "HTML" 약어에 네 가지 주석이 있습니다: 전체 약어에 대한 주석으로, 그 의미를 간략히 설명한 것입니다. "HT" 문자는 "Hypertext"로 확장되고, "M" 문자는 "Markup"으로, "L" 문자는 "Language"로 확장됩니다.

<ruby>
 <ruby>HT<rt>Hypertext</rt>M<rt>Markup</rt>L<rt>Language</rt></ruby>
 <rt>문서 및 애플리케이션을 설명하는 추상적 언어입니다
</ruby>

4.5.11 rt 요소

요소/rt

모든 최신 엔진에서 지원됨.

Firefox38+Safari5+Chrome5+
Opera?Edge79+
Edge (Legacy)?Internet Explorer5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
범주:
없음.
이 요소가 사용될 수 있는 맥락:
루비 요소의 자식으로.
콘텐츠 모델:
구 조 콘텐츠.
text/html에서의 태그 생략:
rt 요소의 종료 태그rt 요소가 바로 뒤따르거나 rp 요소가 뒤따르거나, 부모 요소에 더 이상 콘텐츠가 없는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용합니다.

rt 요소는 루비 주석의 루비 텍스트 구성 요소를 표시합니다. 루비 요소의 자식인 경우, 루비 요소가 그것을 결정하는 데 사용하는 일부로서만 존재하며, 자체적으로는 아무것도 표현하지 않습니다.

rt 요소가 루비 요소의 자식이 아닌 경우, 자식 요소와 동일한 것을 표현합니다.

4.5.12 rp 요소

요소/rp

모든 최신 엔진에서 지원됨.

Firefox38+Safari5+Chrome5+
Opera?Edge79+
Edge (Legacy)?Internet Explorer5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
범주:
없음.
이 요소가 사용될 수 있는 맥락:
루비 요소의 자식으로, rt 요소 바로 전이나 바로 후에 사용될 수 있습니다.
콘텐츠 모델:
텍스트.
text/html에서의 태그 생략:
rp 요소의 종료 태그rp 요소가 rt 또는 rp 요소 바로 뒤따르거나, 부모 요소에 더 이상 콘텐츠가 없는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용합니다.

rp 요소는 루비 주석의 루비 텍스트 구성 요소 주위에 괄호나 다른 콘텐츠를 제공하여 루비 주석을 지원하지 않는 사용자 에이전트에 표시할 수 있습니다.

rp 요소가 루비 요소의 자식인 경우, 아무것도 표현하지 않습니다. rp 요소의 부모 요소가 루비 요소가 아닌 경우, 자식 요소를 표현합니다.

위의 예제에서 텍스트 漢字의 각 한자에 대해 발음이 주석으로 추가된 경우, rp를 사용하여 레거시 사용자 에이전트에서 괄호 안에 읽기가 표시되도록 확장할 수 있습니다:

...
<ruby><rp></rp><rt>かん</rt><rp></rp><rp></rp><rt></rt><rp></rp></ruby>
...

적합한 사용자 에이전트에서는 렌더링이 위와 같이 되겠지만, 루비를 지원하지 않는 사용자 에이전트에서는 다음과 같이 렌더링됩니다:

... 漢(かん)字(じ)...

세그먼트에 여러 주석이 있는 경우, rp 요소는 주석 사이에 배치될 수도 있습니다. 다음은 이전에 만든 예제를 다시 보여주는 것으로, 영어와 프랑스어로 이름이 주어진 몇 가지 기호를 포함하고 있습니다. 이번에는 rp 요소도 포함되었습니다:

<ruby><rp>: </rp><rt>Heart</rt><rp>, </rp><rt lang=fr>Cœur</rt><rp>.</rp><rp>: </rp><rt>Shamrock</rt><rp>, </rp><rt lang=fr>Trèfle</rt><rp>.</rp><rp>: </rp><rt>Star</rt><rp>, </rp><rt lang=fr>Étoile</rt><rp>.</rp>
</ruby>

이 예제는 루비를 지원하지 않는 사용자 에이전트에서 다음과 같이 렌더링됩니다:

♥: Heart, Cœur. ☘: Shamrock, Trèfle. ✶: Star, Étoile.

4.5.13 data 요소

요소/data

모든 최신 엔진에서 지원됨.

Firefox22+Safari10+Chrome62+
Opera?Edge79+
Edge (Legacy)18Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLDataElement

모든 최신 엔진에서 지원됨.

Firefox22+Safari10+Chrome62+
Opera?Edge79+
Edge (Legacy)14+Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
범주:
플로우 콘텐츠.
구조 콘텐츠.
인식 가능한 콘텐츠.
이 요소가 사용될 수 있는 맥락:
구조 콘텐츠가 기대되는 곳에서 사용될 수 있습니다.
콘텐츠 모델:
구조 콘텐츠.
text/html에서의 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
value — 기계가 읽을 수 있는 값
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLDataElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString value;
};

data 요소는 콘텐츠와 함께 value 속성에 있는 해당 콘텐츠의 기계가 읽을 수 있는 형태를 표현합니다.

value 속성은 반드시 있어야 합니다. 이 속성의 값은 요소의 콘텐츠를 기계가 읽을 수 있는 형식으로 나타내야 합니다.

값이 날짜 또는 시간과 관련된 경우, 더 구체적인 time 요소를 대신 사용할 수 있습니다.

이 요소는 여러 용도로 사용될 수 있습니다.

마이크로포맷 또는 이 명세서에서 정의된 마이크로데이터 속성과 결합된 경우, 이 요소는 데이터 처리기용 기계가 읽을 수 있는 값과 웹 브라우저에서 렌더링하기 위한 사람이 읽을 수 있는 값을 모두 제공합니다. 이 경우 value 속성에 사용할 형식은 사용 중인 마이크로포맷 또는 마이크로데이터 어휘에 의해 결정됩니다.

그러나 이 요소는 페이지의 스크립트와 함께 사용될 수도 있으며, 스크립트가 사람이 읽을 수 있는 값과 함께 저장할 리터럴 값을 가지고 있을 때 유용합니다. 이러한 경우 사용해야 할 형식은 스크립트의 필요에만 따릅니다. (data-* 속성도 이러한 상황에서 유용할 수 있습니다.)

HTMLDataElement/value

모든 최신 엔진에서 지원됨.

Firefox22+Safari10+Chrome62+
Opera?Edge79+
Edge (Legacy)14+Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

value IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

여기에는 짧은 테이블이 있으며, 각 열에 대해 텍스트 형식으로 숫자가 표시되고 다른 열에는 분해된 형식으로 표시되지만, data 요소를 사용하여 테이블 정렬 자바스크립트 라이브러리가 각 열에 대해 정렬 메커니즘을 제공할 수 있도록 숫자 값이 인코딩되었습니다.

<script src="sortable.js"></script>
<table class="sortable">
 <thead> <tr> <th> 게임 <th> 회사 <th> 맵 크기
 <tbody>
  <tr> <td> 1830 <td> <data value="8">여덟</data> <td> <data value="93">19+74 헥스 (총 93개)</data>
  <tr> <td> 1856 <td> <data value="11">열하나</data> <td> <data value="99">12+87 헥스 (총 99개)</data>
  <tr> <td> 1870 <td> <data value="10"></data> <td> <data value="149">4+145 헥스 (총 149개)</data>
</table>

4.5.14 time 요소

요소/time

모든 현재 엔진에서 지원됨.

Firefox22+Safari7+Chrome62+
Opera49+Edge79+
Edge (구버전)18Internet Explorer미지원
Firefox Android?Safari iOS4+Chrome Android?WebView Android?Samsung Internet?Opera Android46+

HTMLTimeElement

모든 현재 엔진에서 지원됨.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (구버전)14+Internet Explorer미지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android46+
카테고리:
흐름 콘텐츠.
구문 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
요소에 datetime 속성이 있는 경우: 구문 콘텐츠.
그 외의 경우: 텍스트, 그러나 아래에 서술된 요구 사항과 일치해야 합니다.
태그 생략 in text/html:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
datetime — 기계가 읽을 수 있는 값
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTimeElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString dateTime;
};

time 요소는 그 내용을 표현하며, datetime 속성에 해당하는 기계가 읽을 수 있는 형식으로 변환된 형태를 포함합니다. 내용의 종류는 아래에 설명된 다양한 날짜, 시간, 시간대 오프셋 및 기간으로 제한됩니다.

datetime 속성은 있을 수 있습니다. 있는 경우, 그 값은 요소 내용의 기계가 읽을 수 있는 형식의 표현이어야 합니다.

time 요소에 datetime 속성이 없으면 어떤 요소 자손도 포함할 수 없습니다.

datetime 값time 요소의 datetime 속성 값이며, 속성이 없는 경우 자식 텍스트 내용을 통해 얻습니다.

datetime 값은 다음 구문 중 하나와 일치해야 합니다.

유효한 월 문자열
<time>2011-11</time>
유효한 날짜 문자열
<time>2011-11-18</time>
유효한 연도 없는 날짜 문자열
<time>11-18</time>
유효한 시간 문자열
<time>14:54</time>
<time>14:54:39</time>
<time>14:54:39.929</time>
유효한 로컬 날짜 및 시간 문자열
<time>2011-11-18T14:54</time>
<time>2011-11-18T14:54:39</time>
<time>2011-11-18T14:54:39.929</time>
<time>2011-11-18 14:54</time>
<time>2011-11-18 14:54:39</time>
<time>2011-11-18 14:54:39.929</time>

날짜는 있으나 시간대 오프셋이 없는 시간은 하루 동안 각 시간대에서 동일한 특정 시간에 관찰되는 이벤트를 지정하는 데 유용합니다. 예를 들어, 2020년 새해는 모든 시간대에서 2020-01-01 00:00에 축하되며, 전 세계 시간대에서 같은 순간에 축하되지 않습니다. 모든 시간대에서 동일한 시간에 발생하는 이벤트의 경우, 예를 들어 화상회의, 유효한 글로벌 날짜 및 시간 문자열이 더 유용할 수 있습니다.

유효한 시간대 오프셋 문자열
<time>Z</time>
<time>+0000</time>
<time>+00:00</time>
<time>-0800</time>
<time>-08:00</time>

날짜가 없는 시간(또는 여러 날짜에 걸쳐 발생하는 이벤트를 나타내는 시간)의 경우 시간대 오프셋을 지정하는 것보다 시간을 제어하는 지리적 위치를 지정하는 것이 더 유용합니다. 이는 지리적 위치가 일광 절약 시간제로 인해 시간대 오프셋을 변경하기 때문입니다. 경우에 따라 지리적 위치가 시간대를 변경하기도 합니다. 예를 들어, 2011년 말 사모아에서 일어난 일과 같이 시간대 경계가 재조정되는 경우가 있습니다. 이러한 시간대의 경계를 설명하고 각 시간대 내에서 적용되는 규칙을 설명하는 데이터베이스가 있으며, 이는 시간대 데이터베이스로 알려져 있습니다. [TZDATABASE] 참조

유효한 글로벌 날짜 및 시간 문자열
<time>2011-11-18T14:54Z</time>
<time>2011-11-18T14:54:39Z</time>
<time>2011-11-18T14:54:39.929Z</time>
<time>2011-11-18T14:54+0000</time>
<time>2011-11-18T14:54:39+0000</time>
<time>2011-11-18T14:54:39.929+0000</time>
<time>2011-11-18T14:54+00:00</time>
<time>2011-11-18T14:54:39+00:00</time>
<time>2011-11-18T14:54:39.929+00:00</time>
<time>2011-11-18T06:54-0800</time>
<time>2011-11-18T06:54:39-0800</time>
<time>2011-11-18T06:54:39.929-0800</time>
<time>2011-11-18T06:54-08:00</time>
<time>2011-11-18T06:54:39-08:00</time>
<time>2011-11-18T06:54:39.929-08:00</time>

날짜 및 시간대 오프셋이 있는 시간은 특정 이벤트나 시간대에 고정되지 않은 반복적인 가상 이벤트를 지정하는 데 유용합니다. 예를 들어 소행성 충돌의 정확한 시간이나 일광 절약 시간제에 관계없이 매일 1400 UTC에 열리는 회의의 특정 시간 등을 지정할 수 있습니다. 시간대 오프셋이 특정 지리적 위치의 현지 시간대 오프셋에 따라 달라지는 이벤트의 경우, 지리적 위치와 결합된 유효한 로컬 날짜 및 시간 문자열이 더 유용할 수 있습니다.

유효한 주 문자열
<time>2011-W47</time>
네 자 이상의 ASCII 숫자, 그중 하나는 U+0030 숫자 0(0)이 아닙니다
<time>2011</time>
<time>0001</time>
유효한 기간 문자열
<time>PT4H18M3S</time>
<time>4h 18m 3s</time>

요소 내용의 기계가 읽을 수 있는 동등 항목은 요소의 datetime 값을 사용하여 다음 알고리즘으로 얻어야 합니다:

  1. 요소의 월 문자열을 파싱하여 datetime 값을 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  2. 요소의 날짜 문자열을 파싱하여 datetime 값날짜를 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  3. 요소의 연도 없는 날짜 문자열을 파싱하여 datetime 값연도 없는 날짜를 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  4. 요소의 시간 문자열을 파싱하여 datetime 값시간을 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  5. 요소의 로컬 날짜 및 시간 문자열을 파싱하여 datetime 값로컬 날짜 및 시간을 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  6. 요소의 시간대 오프셋 문자열을 파싱하여 datetime 값시간대 오프셋을 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  7. 요소의 글로벌 날짜 및 시간 문자열을 파싱하여 datetime 값글로벌 날짜 및 시간을 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  8. 요소의 주 문자열을 파싱하여 datetime 값를 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  9. 요소의 ASCII 숫자만으로 구성되어 있고, 그중 하나가 U+0030 숫자 0(0)이 아닌 경우, 기계가 읽을 수 있는 동등 항목은 이러한 숫자의 십진수 해석으로, 연도를 나타냅니다. 반환하십시오.

  10. 요소의 기간 문자열을 파싱하여 datetime 값기간을 반환하면, 그것이 기계가 읽을 수 있는 동등 항목입니다. 반환하십시오.

  11. 기계가 읽을 수 있는 동등 항목이 없습니다.

위 알고리즘은 임의의 문자열 s에 대해 오직 하나의 알고리즘만이 값을 반환하도록 설계되어야 합니다. 더 효율적인 접근 방식은 이러한 데이터 유형을 한 번에 파싱하는 단일 알고리즘을 만드는 것일 수 있습니다. 그러한 알고리즘 개발은 독자에게 맡겨져 있습니다.

HTMLTimeElement/dateTime

모든 현재 엔진에서 지원됨.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (구버전)14+Internet Explorer미지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android46+

dateTime IDL 속성은 요소의 datetime 콘텐츠 속성을 반영해야 합니다.

time 요소는 예를 들어 마이크로포맷에서 날짜를 인코딩하는 데 사용할 수 있습니다. 아래는 time 요소를 사용하는 hCalendar 변형을 사용하여 이벤트를 인코딩하는 가상의 방법을 보여줍니다:

<div class="vevent">
 <a class="url" href="http://www.web2con.com/">http://www.web2con.com/</a>
 <span class="summary">Web 2.0 Conference</span>:
 <time class="dtstart" datetime="2005-10-05">October 5</time> -
 <time class="dtend" datetime="2005-10-07">7</time>,
 at the <span class="location">Argent Hotel, San Francisco, CA</span>
</div>

여기서는 Atom 어휘를 기반으로 한 가상의 마이크로데이터 어휘가 사용되어 time 요소와 함께 블로그 게시물의 게시 날짜를 표시합니다.

<article itemscope itemtype="https://n.example.org/rfc4287">
 <h1 itemprop="title">Big tasks</h1>
 <footer>Published <time itemprop="published" datetime="2009-08-29">이틀 전</time>.</footer>
 <p itemprop="content">오늘, 나는 내 아이를 위해 자전거를 사러 나갔다.</p>
</article>

이 예제에서는 time 요소를 사용하여 다른 기사 게시 날짜를 schema.org 마이크로데이터 어휘를 사용하여 표시합니다:

<article itemscope itemtype="http://schema.org/BlogPosting">
 <h1 itemprop="headline">Small tasks</h1>
 <footer>Published <time itemprop="datePublished" datetime="2009-08-30">어제</time>.</footer>
 <p itemprop="articleBody">나는 자전거에 자전거 벨을 달았다.</p>
</article>

다음 스니펫에서는 time 요소를 사용하여 ISO8601 형식으로 날짜를 인코딩하여 나중에 스크립트로 처리합니다:

<p>Our first date was <time datetime="2006-09-23">a Saturday</time>.</p>

이 두 번째 스니펫에서는 값에 시간이 포함되어 있습니다:

<p>We stopped talking at <time datetime="2006-09-24T05:00-07:00">5am the next morning</time>.</p>

페이지에 로드된 스크립트(따라서 time 요소를 사용하여 날짜와 시간을 표시하는 페이지의 내부 규칙을 따름)는 페이지를 스캔하여 time 요소를 모두 찾아 날짜와 시간의 인덱스를 생성할 수 있습니다.

예를 들어, 이 요소는 "금요일"이라는 문자열과 함께 2011년 11월 18일이 "금요일"에 해당한다는 추가 의미를 전달합니다:

Today is <time datetime="2011-11-18">금요일</time>.

이 예제에서는 태평양 표준시 시간대를 지정하여 특정 시간을 나타냅니다:

Your next meeting is at <time datetime="2011-11-18T15:00-08:00">3pm</time>.

4.5.15 code 요소

요소/code

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구버전)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
흐름 콘텐츠.
구문 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
태그 생략 in text/html:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

code 요소는 컴퓨터 코드 조각을 나타냅니다. 이는 XML 요소 이름, 파일 이름, 컴퓨터 프로그램 또는 컴퓨터가 인식할 수 있는 기타 문자열일 수 있습니다.

컴퓨터 코드의 언어를 표시하는 공식적인 방법은 없습니다. 문법 강조 스크립트가 올바른 규칙을 사용할 수 있도록 예를 들어 code 요소에 사용된 언어를 표시하고자 하는 저자는 class 속성을 사용할 수 있으며, 예를 들어 요소에 "language-"로 시작하는 클래스를 추가할 수 있습니다.

다음 예제는 요소 이름과 컴퓨터 코드를 포함한 구두점 등을 문단 내에서 마크업하는 방법을 보여줍니다.

<p>The <code>code</code> 요소는 컴퓨터
코드 조각을 나타냅니다.</p>

<p>When you call the <code>activate()</code> 메서드를
<code>robotSnowman</code> 객체에서 호출하면 눈이 빛납니다.</p>

<p>The example below uses the <code>begin</code> 키워드를 사용하여
문장 블록의 시작을 나타냅니다. 이 키워드는 <code>end</code> 키워드와 쌍을 이루며, 그 뒤에는 프로그램의 끝을 나타내는 <code>.</code> 구두점 문자가 옵니다.</p>

다음 예제는 precode 요소를 사용하여 코드 블록을 마크업하는 방법을 보여줍니다.

<pre><code class="language-pascal">var i: Integer;
begin
   i := 1;
end.</code></pre>

이 예제에서는 사용된 언어를 표시하기 위해 클래스를 사용합니다.

자세한 내용은 pre 요소를 참조하십시오.

4.5.16 var 요소

요소/var

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구버전)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
흐름 콘텐츠.
구문 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
태그 생략 in text/html:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

var 요소는 변수를 나타냅니다. 이는 수학적 표현식이나 프로그래밍 문맥에서 실제 변수일 수 있으며, 상수를 나타내는 식별자, 물리적 양을 나타내는 기호, 함수 매개변수, 또는 산문에서 사용되는 대체 용어일 수 있습니다.

아래 문단에서는 문자 "n"이 산문에서 변수로 사용되고 있습니다:

<p>If there are <var>n</var> pipes leading to the ice
cream factory then I expect at <em>least</em> <var>n</var>
flavors of ice cream to be available for purchase!</p>

수학에서는, 특히 가장 간단한 표현식 이상에서는 MathML이 더 적합합니다. 그러나 var 요소는 여전히 MathML 표현식에서 언급된 특정 변수를 참조하는 데 사용할 수 있습니다.

이 예제에서는 방정식과 그 방정식에서 변수들을 참조하는 범례를 보여줍니다. 표현식 자체는 MathML로 마크업되었지만, 변수는 var 요소를 사용하여 그림의 범례에서 언급됩니다.

<figure>
 <math>
  <mi>a</mi>
  <mo>=</mo>
  <msqrt>
   <msup><mi>b</mi><mn>2</mn></msup>
   <mi>+</mi>
   <msup><mi>c</mi><mn>2</mn></msup>
  </msqrt>
 </math>
 <figcaption>
  Using Pythagoras' theorem to solve for the hypotenuse <var>a</var> of
  a triangle with sides <var>b</var> and <var>c</var>
 </figcaption>
</figure>

여기서 질량-에너지 등가를 설명하는 방정식이 문장에서 사용되었으며, 그 방정식의 변수와 상수를 표시하기 위해 var 요소가 사용되었습니다:

<p>Then she turned to the blackboard and picked up the chalk. After a few moment's
thought, she wrote <var>E</var> = <var>m</var> <var>c</var><sup>2</sup>. The teacher
looked pleased.</p>

4.5.17 samp 요소

요소/samp

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구버전)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
흐름 콘텐츠.
구문 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
태그 생략 in text/html:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

samp 요소는 다른 프로그램이나 컴퓨팅 시스템에서의 샘플 또는 인용된 출력을 표현합니다.

prekbd 요소에 대한 자세한 내용은 참고하십시오.

이 요소는 웹 애플리케이션에서 즉시 출력을 제공할 수 있는 output 요소와 대조될 수 있습니다.

이 예제는 samp 요소를 인라인으로 사용하는 것을 보여줍니다:

<p>The computer said <samp>Too much cheese in tray
two</samp> but I didn't know what that meant.</p>

두 번째 예제는 콘솔 프로그램에서 샘플 출력을 보여줍니다. 중첩된 sampkbd 요소는 스타일 시트로 샘플 출력의 특정 요소를 스타일링할 수 있게 합니다. samp의 몇몇 부분은 더욱 정밀한 스타일링을 위해 추가적인 마크업이 되어 있습니다. 이를 위해 span 요소가 사용되었습니다.

<pre><samp><span class="prompt">jdoe@mowmow:~$</span> <kbd>ssh demo.example.com</kbd>
Last login: Tue Apr 12 09:10:17 2005 from mowmow.example.com on pts/1
Linux demo 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189 #1 SMP Tue Feb 1 11:22:36 PST 2005 i686 unknown

<span class="prompt">jdoe@demo:~$</span> <span class="cursor">_</span></samp></pre>

세 번째 예제는 입력과 해당 출력을 보여줍니다. 이 예제에서는 codesamp 요소를 사용합니다.

<pre>
<code class="language-javascript">console.log(2.3 + 2.4)</code>
<samp>4.699999999999999</samp>
</pre>

4.5.18 kbd 요소

요소/kbd

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구버전)12+Internet Explorer지원됨
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
흐름 콘텐츠.
구문 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
태그 생략 in text/html:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

kbd 요소는 사용자 입력을 나타냅니다(일반적으로 키보드 입력이지만 음성 명령과 같은 다른 입력을 나타내는 데에도 사용할 수 있습니다).

kbd 요소가 samp 요소 안에 중첩되어 있는 경우, 시스템에서 반향된 입력을 나타냅니다.

kbd 요소가 samp 요소를 포함할 때, 이는 시스템 출력에 기반한 입력을 나타냅니다. 예를 들어 메뉴 항목을 호출할 때 사용됩니다.

kbd 요소가 다른 kbd 요소 안에 중첩되어 있는 경우, 이는 입력 메커니즘에 적합한 실제 키 또는 기타 단일 입력 단위를 나타냅니다.

여기서 kbd 요소는 눌러야 할 키를 나타내는 데 사용됩니다:

<p>To make George eat an apple, press <kbd><kbd>Shift</kbd> + <kbd>F3</kbd></kbd></p>

두 번째 예제에서는 특정 메뉴 항목을 선택하라고 지시합니다. 외부의 kbd 요소는 입력의 블록을 나타내며, 내부의 kbd 요소는 입력의 각 단계를 나타내고, 그 안에 있는 samp 요소는 이 단계들이 시스템에 의해 표시된 내용을 기반으로 한 것임을 나타냅니다. 이 경우 메뉴 레이블을 나타냅니다:

<p>To make George eat an apple, select
    <kbd><kbd><samp>File</samp></kbd>|<kbd><samp>Eat Apple...</samp></kbd></kbd>
</p>

이러한 정확성은 필수적이지 않으며, 다음과 같이 작성해도 무방합니다:

<p>To make George eat an apple, select <kbd>File | Eat Apple...</kbd></p>

4.5.19 subsup 요소

요소/sub

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구버전)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소/sup

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (구버전)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
흐름 콘텐츠.
구문 콘텐츠.
유형 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
태그 생략 in text/html:
어느 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
sub 요소: 저자를 위한 정보; 구현자를 위한 정보.
sup 요소: 저자를 위한 정보; 구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

sup 요소는 윗첨자를 나타내고, sub 요소는 하첨자를 나타냅니다.

이 요소들은 특정 의미를 가진 타이포그래피적 관례를 마크업하기 위해서만 사용해야 하며, 단순한 타이포그래피적 표현을 위해 사용해서는 안 됩니다. 예를 들어, subsup 요소를 LaTeX 문서 준비 시스템의 이름에 사용하는 것은 부적절합니다. 일반적으로, 이러한 요소들은 이 요소들이 없으면 콘텐츠의 의미가 변하는 경우에만 사용해야 합니다.

특정 언어에서는 윗첨자가 일부 약어의 타이포그래피적 관례의 일부입니다.

<p>그들의 이름은
<span lang="fr"><abbr>M</sup>lle</sup></abbr> Gwendoline</span> 그리고
<span lang="fr"><abbr>M</sup>me</sup></abbr> Denise</span>입니다.</p>

sub 요소는 하첨자가 있는 변수를 나타내기 위해 var 요소 내에서 사용될 수 있습니다.

여기서, sub 요소는 변수의 집합에서 변수를 식별하는 하첨자를 나타내는 데 사용됩니다:

<p>i번째 점의 좌표는
(<var>x</var><sub><var>i</var></sub></var>, <var>y</var><sub><var>i</var></sub></var>).
예를 들어, 10번째 점의 좌표는
(<var>x</sub>10</sub></var>, <var>y</sub>10</sub></var>)입니다.</p>

수학 표현은 종종 하첨자와 윗첨자를 사용합니다. 저자들은 수학을 마크업할 때 MathML을 사용하는 것이 권장되지만, 세부적인 수학적 마크업이 필요하지 않은 경우 subsup을 사용할 수 있습니다. [MATHML]

<var>E</var>=<var>m</var><var>c</var><sup>2</sup>
f(<var>x</var>, <var>n</var>) = log<sub>4</sub><var>x</var></sup><var>n</var></sup>

4.5.20 i 요소

Element/i

모든 최신 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (레거시)12+인터넷 익스플로러지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
만질 수 있는 콘텐츠.
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement 사용.

i 요소는 일반적인 산문에서 벗어난 텍스트 범위를 표현합니다. 이는 대체 목소리 또는 분위기의 텍스트 범위를 나타내거나, 분류학적 명칭, 기술 용어, 다른 언어의 관용구, 음역, 생각 또는 서양 텍스트에서의 선박 이름과 같은 다른 품질의 텍스트를 나타낼 수 있습니다.

주 텍스트와 다른 언어로 된 용어는 lang 속성(또는 XML의 경우 lang 속성, XML 네임스페이스)으로 주석을 달아야 합니다.

아래의 예시는 i 요소의 사용 예를 보여줍니다:

<p>The <i class="taxonomy">Felis silvestris catus</i> is cute.</p>
<p>The term <i>prose content</i> is defined above.</p>
<p>There is a certain <i lang="fr">je ne sais quoi</i> in the air.</p>

다음 예에서는 i 요소를 사용하여 꿈 시퀀스를 표시합니다.

<p>Raymond tried to sleep.</p>
<p><i>The ship sailed away on Thursday</i>, he
dreamt. <i>The ship had many people aboard, including a beautiful
princess called Carey. He watched her, day-in, day-out, hoping she
would notice him, but she never did.</i></p>
<p><i>Finally one night he picked up the courage to speak with
her—</i></p>
<p>Raymond woke with a start as the fire alarm rang out.</p>

저자는 class 속성을 i 요소에 사용하여 요소가 사용된 이유를 식별할 수 있습니다. 이를 통해 나중에 특정 사용 스타일(예: 꿈 시퀀스와 분류학적 용어의 차이)을 변경하려 할 때, 저자는 문서 전체(또는 관련 문서 일련)의 각 사용 예를 주석 처리할 필요가 없습니다.

저자는 i 요소보다 더 적합한 요소가 있을 수 있는지 고려해야 합니다. 예를 들어 강조 표시를 위해 em 요소나 용어의 정의 인스턴스를 마크업하기 위해 dfn 요소를 사용할 수 있습니다.

스타일 시트는 i 요소를 다른 요소와 마찬가지로 재스타일링할 수 있습니다. 따라서 i 요소의 콘텐츠가 반드시 기울임꼴로 표시되는 것은 아닙니다.

4.5.21 b 요소

Element/b

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 맥락:
어디서 phrasing content이 예상됩니다.
콘텐츠 모델:
Phrasing content.
텍스트/html에서 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement을 사용합니다.

b 요소는 추가적인 중요성을 전달하지 않으면서 기능적인 목적을 위해 주의가 필요하다는 텍스트 범위를 나타냅니다. 예를 들어 문서 요약의 주요 단어, 리뷰의 제품 이름, 상호작용하는 텍스트 기반 소프트웨어의 실행 가능한 단어 또는 기사 리드 등이 해당될 수 있습니다.

다음 예제는 중요한 단어를 표시하기 위해 b 요소를 사용하는 방법을 보여줍니다.

<p>The <b>frobonitor</b> and <b>barbinator</b> components are fried.</p>

다음 예제에서는 텍스트 어드벤처에서 b 요소를 사용하여 객체가 특별하다는 것을 강조하는 방법을 보여줍니다.

<p>You enter a small room. Your <b>sword</b> glows brighter. A <b>rat</b> scurries past the corner wall.</p>

b 요소가 적절하게 사용될 수 있는 또 다른 경우는 리드 문장 또는 단락을 표시할 때입니다. 다음 예제는 토끼를 어미로 받아들인 새끼 고양이들에 대한 BBC 기사가 어떻게 표시될 수 있는지를 보여줍니다:

<article>
 <h2>Kittens 'adopted' by pet rabbit</h2>
 <p><b class="lede">Six abandoned kittens have found an unexpected new mother figure — a pet rabbit.</b></p>
 <p>Veterinary nurse Melanie Humble took the three-week-old kittens to her Aberdeen home.</p>
[...]

i 요소와 마찬가지로, 저자는 class 속성을 b 요소에 사용하여 요소의 사용 목적을 식별할 수 있습니다. 이를 통해 특정 사용 스타일을 나중에 변경해야 할 경우, 모든 사용 예를 일일이 주석 달지 않아도 됩니다.

b 요소는 다른 요소가 더 적절하지 않은 경우에만 최후의 수단으로 사용해야 합니다. 특히, 제목은 h1에서 h6 요소를 사용해야 하고, 강조된 부분은 em 요소를 사용하여 강조하고, 중요성은 strong 요소로 표시하며, 표시되거나 강조된 텍스트는 mark 요소를 사용해야 합니다.

다음은 잘못된 사용 사례입니다:

<p><b>WARNING!</b> Do not frob the barbinator!</p>

이전 예에서 올바른 요소는 strong였으며, b가 아닙니다.

스타일 시트를 사용하여 b 요소를 다른 요소처럼 스타일을 변경할 수 있습니다. 따라서 b 요소의 내용이 반드시 굵게 표시되는 것은 아닙니다.

4.5.22 u 요소

Element/u

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 맥락:
어디서 phrasing content이 예상됩니다.
콘텐츠 모델:
Phrasing content.
텍스트/html에서 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement을 사용합니다.

u 요소는 비텍스트 주석이 명시적으로 렌더링되도록 표시되어야 하는 텍스트 범위를 나타냅니다. 예를 들어 중국어 텍스트에서 고유명사로 표시되거나, 철자가 잘못된 단어로 표시됩니다.

대부분의 경우, 다른 요소가 더 적절할 수 있습니다: 강조 표시를 위해 em 요소를 사용해야 하며, 키워드나 구를 표시하기 위해서는 맥락에 따라 b 요소 또는 mark 요소를 사용해야 합니다. 책 제목을 표시하기 위해서는 cite 요소를 사용해야 하며, 텍스트에 명시적인 주석을 표시하기 위해서는 ruby 요소를 사용해야 합니다. 기술 용어, 분류학적 명칭, 음역, 생각, 또는 서양 텍스트에서 배 이름을 표시하기 위해서는 i 요소를 사용해야 합니다.

시각적 프레젠테이션에서 u 요소의 기본 렌더링은 하이퍼링크(밑줄)의 기존 렌더링과 충돌합니다. 저자는 u 요소가 하이퍼링크로 오해될 수 있는 경우 사용을 피하는 것이 좋습니다.

이 예제에서는 u 요소를 사용하여 철자가 잘못된 단어를 표시합니다:

<p>The <u>see</u> is full of fish.</p>

4.5.23 mark 요소

Element/mark

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5.1+Chrome7+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
Flow content.
Phrasing content.
Palpable content.
이 요소가 사용될 수 있는 맥락:
어디서 phrasing content이 예상됩니다.
콘텐츠 모델:
Phrasing content.
텍스트/html에서 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement을 사용합니다.

mark 요소는 하나의 문서에서 참조 목적으로 표시되거나 강조된 텍스트 구간을 나타냅니다. 강조된 구절은 포함된 문맥에서의 관련성 때문에 강조됩니다. 인용문이나 본문의 다른 블록에서 사용될 때, 이는 원래는 강조되지 않았으나 독자의 주의를 끌기 위해 추가된 부분을 나타냅니다. 이는 본문이 처음 작성되었을 때 원저자가 중요하게 여기지 않았을 수도 있는 부분일 수 있으며, 지금은 예상치 못한 관심의 대상이 된 부분일 수 있습니다. 문서의 주요 본문에서 사용될 때, 이는 사용자의 현재 활동과 관련성이 높다고 판단되어 강조된 부분을 나타냅니다.

이 예제는 mark 요소를 사용하여 인용문의 특정 부분에 주의를 환기하는 방법을 보여줍니다:

<p lang="en-US">Consider the following quote:</p>
<blockquote lang="en-GB">
 <p>Look around and you will find, no-one's really
 <mark>colour</mark> blind.</p>
</blockquote>
<p lang="en-US">As we can tell from the <em>spelling</em> of the word,
the person writing this quote is clearly not American.</p>

(만약 단어의 철자가 잘못된 것을 표시하는 것이 목적이라면, u 요소가 클래스와 함께 사용되어야 할 것입니다.)

mark 요소의 또 다른 예는 문서의 일부를 검색 문자열과 일치하는 부분으로 강조하는 것입니다. 예를 들어 사용자가 "kitten"이라는 단어를 검색하고 서버가 그에 맞춰 문서를 반환하면, 서버는 문서의 일부 단락을 다음과 같이 수정할 수 있습니다:

<p>I also have some <mark>kitten</mark>s who are visiting me
these days. They're really cute. I think they like my garden! Maybe I
should adopt a <mark>kitten</mark>.</p>

다음 코드 조각에서는 텍스트 단락이 코드 조각의 특정 부분을 참조합니다.

<p>The highlighted part below is where the error lies:</p>
<pre><code>var i: Integer;
begin
   i := <mark>1.1</mark>;
end.</code></pre>

이는 구문 강조와는 별개의 문제로, 구문 강조를 위해서는 span 요소가 더 적합합니다. 두 가지를 결합하면 다음과 같습니다:

<p>The highlighted part below is where the error lies:</p>
<pre><code><span class=keyword>var</span> <span class=ident>i</span>: <span class=type>Integer</span>;
<span class=keyword>begin</span>
   <span class=ident>i</span> := <span class=literal><mark>1.1</mark></span>;
<span class=keyword>end</span>.</code></pre>

이 예제는 원래 강조되지 않았던 인용문 텍스트의 일부를 강조하기 위해 mark를 사용하는 또 다른 예를 보여줍니다. 이 예에서, 일반적인 타이포그래피 규칙에 따라 저자는 인용문에서 mark 요소를 명시적으로 스타일링하여 이탤릭체로 렌더링하도록 설정했습니다.

<style>
 blockquote mark, q mark {
   font: inherit; font-style: italic;
   text-decoration: none;
   background: transparent; color: inherit;
 }
 .bubble em {
   font: inherit; font-size: larger;
   text-decoration: underline;
 }
</style>
<article>
 <h1>She knew</h1>
 <p>Did you notice the subtle joke in the joke on panel 4?</p>
 <blockquote>
  <p class="bubble">I didn't <em>want</em> to believe. <mark>Of course
  on some level I realized it was a known-plaintext attack.</mark> But I
  couldn't admit it until I saw for myself.</p>
 </blockquote>
 <p>(강조는 저자의 것입니다.) 저는 이 부분이 정말 좋았습니다. 매우 학문적이면서도 모든 것을 깔끔하게 설명해 줍니다.</p>
</article>

이 예에서 em 요소는 인용된 원본 텍스트의 일부로, mark 요소는 주석을 위해 강조된 부분을 나타내는 것입니다.

다음 예제는 텍스트의 중요성을 나타내는 것 (strong 요소)과 텍스트의 관련성을 나타내는 것 (mark 요소)의 차이를 보여줍니다. 이 예제는 교과서에서 발췌한 것으로, 시험과 관련된 부분이 강조되어 있습니다. 안전 경고는 중요할 수 있지만 시험과 관련이 없기 때문에 강조되지 않았습니다.

<h3>웜홀 물리학 소개</h3>

<p><mark>웜홀은 일반적인 조건에서 최대 39분 동안 열려 있을 수 있습니다.</mark> 시간 연장을 위해서는 하나 또는 두 개의 게이트에 강력한 에너지원을 연결하거나, 블랙홀과 같은 큰 중력장을 활용할 수 있습니다.</p>

<p><mark>웜홀을 통해 모멘텀이 보존됩니다. 전자기 방사선은 웜홀을 통해 양방향으로 이동할 수 있지만, 물질은 이동할 수 없습니다.</mark></p>

<p>웜홀이 생성될 때, 일반적으로 소용돌이가 형성됩니다.
<strong>경고: 웜홀이 열릴 때 발생하는 소용돌이는 경로에 있는 모든 것을 파괴합니다.</strong> 소용돌이는 충분히 고급화된 다이얼링 기술을 사용하면 피할 수 있습니다.</p>

<p><mark>게이트에 장애물이 있으면 웜홀 연결을 방해할 수 있습니다.</mark></p>

4.5.24 bdi 요소

Element/bdi

모든 현재 엔진에서 지원됩니다.

Firefox10+Safari6+Chrome16+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
감지 가능한 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
text/html에서 태그 생략:
두 태그 모두 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
또한, 이 요소에서 dir 전역 속성은 특별한 의미를 가집니다.
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

bdi 요소는 양방향 텍스트 서식을 위한 목적으로 주변과 격리된 텍스트 범위를 나타냅니다. [BIDI]

이 요소에서 dir 전역 속성은 auto로 기본 설정되며, 다른 요소처럼 부모 요소로부터 상속되지 않습니다.

이 요소는 양방향 알고리즘과 관련된 렌더링 요구 사항을 가지고 있습니다.

이 요소는 방향성이 알려지지 않은 사용자 생성 콘텐츠를 삽입할 때 특히 유용합니다.

이 예제에서는 사용자 이름과 함께 해당 사용자가 제출한 게시물 수를 표시합니다. bdi 요소를 사용하지 않으면 아랍어 사용자의 사용자 이름이 텍스트를 혼란스럽게 만들 것입니다 (양방향 알고리즘은 콜론과 숫자 "3"을 "User"라는 단어 옆에 배치하는 대신 "posts"라는 단어 옆에 배치할 것입니다).

<ul>
 <li>User <bdi>jcranmer</bdi>: 12 posts.
 <li>User <bdi>hober</bdi>: 5 posts.
 <li>User <bdi>إيان</bdi>: 3 posts.
</ul>
bdi 요소를 사용할 때, 사용자 이름이 예상대로 동작합니다.
bdi 요소를 b 요소로 대체할 경우, 사용자 이름이 양방향 알고리즘을 혼란스럽게 만들어 세 번째 목록 항목이 "User 3 :"라고 표시되고, 그 다음에 아랍어 이름(오른쪽에서 왼쪽)이 오며, 그 뒤에 "posts"와 마침표가 옵니다.

4.5.25 bdo 요소

Element/bdo

모든 현재 엔진에서 지원됩니다.

Firefox10+Safari4+Chrome15+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
감지 가능한 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
text/html에서 태그 생략:
두 태그 모두 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
또한, 이 요소에서 dir 전역 속성은 특별한 의미를 가집니다.
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement를 사용합니다.

bdo 요소는 자식 요소에 대한 명시적 텍스트 방향성 서식 지정을 나타냅니다. 이 요소는 작성자가 명시적으로 방향을 지정하여 Unicode 양방향 알고리즘을 무시할 수 있게 해줍니다. [BIDI]

작성자는 이 요소에서 dir 속성을 지정해야 하며, ltr 값을 사용하여 왼쪽에서 오른쪽으로의 방향을 지정하거나 rtl 값을 사용하여 오른쪽에서 왼쪽으로의 방향을 지정할 수 있습니다. auto 값은 지정할 수 없습니다.

이 요소는 양방향 알고리즘과 관련된 렌더링 요구 사항을 가지고 있습니다.

4.5.26 span 요소

Element/span

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLSpanElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari6+Chrome15+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
감지 가능한 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠.
text/html에서 태그 생략:
두 태그 모두 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLSpanElement : HTMLElement {
  [HTMLConstructor] constructor();
};

span 요소 자체는 아무 의미가 없지만, 전역 속성과 함께 사용하면 유용할 수 있습니다. 예를 들어, class, lang, 또는 dir 속성과 함께 사용될 수 있습니다. 이는 자식 요소를 나타냅니다.

이 예에서는 span 요소와 class 속성을 사용하여 키워드와 식별자를 색상으로 구분할 수 있도록 코드 조각을 마크업합니다:

<pre><code class="lang-c"><span class="keyword">for</span> (<span class="ident">j</span> = 0; <span class="ident">j</span> &lt; 256; <span class="ident">j</span>++) {
  <span class="ident">i_t3</span> = (<span class="ident">i_t3</span> & 0x1ffff) | (<span class="ident">j</span> &lt;&lt; 17);
  <span class="ident">i_t6</span> = (((((((<span class="ident">i_t3</span> >> 3) ^ <span class="ident">i_t3</span>) >> 1) ^ <span class="ident">i_t3</span>) >> 8) ^ <span class="ident">i_t3</span>) >> 5) & 0xff;
  <span class="keyword">if</span> (<span class="ident">i_t6</span> == <span class="ident">i_t1</span>)
    <span class="keyword">break</span>;
}</code></pre>

4.5.27 br 요소

Element/br

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLBRElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그가 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLBRElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 구식 멤버도 있습니다.
};

br 요소는 줄바꿈을 나타냅니다.

줄바꿈은 시각적 매체에서 보통 다음 텍스트를 새로운 줄로 이동시켜 표시되지만, 스타일 시트나 사용자 에이전트는 줄바꿈을 다른 방식으로 렌더링하도록 결정할 수 있습니다. 예를 들어, 녹색 점으로 표시하거나 추가 간격을 줄 수도 있습니다.

br 요소는 시구나 주소 등에서 실제로 콘텐츠의 일부인 줄바꿈에만 사용해야 합니다.

다음 예는 br 요소의 올바른 사용 예입니다:

<p>P. Sherman<br>
42 Wallaby Way<br>
Sydney</p>

br 요소는 단락 내에서 주제별 그룹을 구분하는 데 사용해서는 안 됩니다.

다음 예는 br 요소를 잘못 사용한 비준수 사례입니다:

<p><a ...>34 comments.</a><br>
<a ...>Add a comment.</a></p>
<p><label>Name: <input name="name"></label><br>
<label>Address: <input name="address"></label></p>

다음은 위의 예에 대한 대안으로 올바른 사용법입니다:

<p><a ...>34 comments.</a></p>
<p><a ...>Add a comment.</a></p>
<p><label>Name: <input name="name"></label></p>
<p><label>Address: <input name="address"></label></p>

단락이 br 요소 하나만으로 구성된 경우, 빈 줄(예: 템플릿으로)이 됩니다. 이러한 빈 줄은 프레젠테이션 목적으로 사용해서는 안 됩니다.

모든 콘텐츠는 br 요소 내에서 주변 텍스트의 일부로 간주되어서는 안 됩니다.

이 요소는 양방향 알고리즘과 관련된 렌더링 요구 사항이 있습니다.

4.5.28 wbr 요소

Element/wbr

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)?Internet Explorer5.5–7
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그가 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLElement을 사용합니다.

wbr 요소는 줄바꿈 기회를 나타냅니다.

다음 예에서는, 효과를 위해 한 사람이 말한 내용을 한 단어로 작성한 인용구를 보여줍니다. 그러나 텍스트가 읽기 쉬운 방식으로 줄을 나눌 수 있도록 하기 위해 인용구의 개별 단어는 wbr 요소를 사용하여 구분되었습니다.

<p>So then she pointed at the tiger and screamed 
"there<wbr>is<wbr>no<wbr>way<wbr>you<wbr>are<wbr>ever<wbr>going<wbr>to<wbr>catch<wbr>me"!</p>

wbr 요소 내의 모든 콘텐츠는 주변 텍스트의 일부로 간주되어서는 안 됩니다.

var wbr = document.createElement("wbr");
wbr.textContent = "This is wrong";
document.body.appendChild(wbr);

이 요소는 양방향 알고리즘과 관련된 렌더링 요구 사항이 있습니다.

4.5.29 사용 요약

이 섹션은 비규범적입니다.

요소 목적 예시
a 하이퍼링크
Visit my <a href="drinks.html">drinks</a> page.
em 강조
I must say I <em>adore</em> lemonade.
strong 중요성
This tea is <strong>very hot</strong>.
small 부가 설명
These grapes are made into wine. <small>Alcohol is addictive.</small>
s 부정확한 텍스트
Price: <s>£4.50</s> £2.00!
cite 작품의 제목
The case <cite>Hugo v. Danielle</cite> is relevant here.
q 인용구
The judge said <q>You can drink water from the fish tank</q> but advised against it.
dfn 정의 인스턴스
The term <dfn>organic food</dfn> refers to food produced without synthetic chemicals.
abbr 약어
Organic food in Ireland is certified by the <abbr title="Irish Organic Farmers and Growers Association">IOFGA</abbr>.
ruby, rt, rp 루비 주석
<ruby> OJ <rp>(<rt>Orange Juice</rp>)</ruby>
data 기계 판독 가능한 동등성
Available starting today! <data value="UPC:022014640201">North Coast Organic Apple Cider</data>
time 날짜 또는 시간 관련 데이터의 기계 판독 가능한 동등성
Available starting on <time datetime="2011-11-18">November 18th</time>!
code 컴퓨터 코드
The <code>fruitdb</code> program can be used for tracking fruit production.
var 변수
If there are <var>n</var> fruit in the bowl, at least <var>n</var>÷2 will be ripe.
samp 컴퓨터 출력
The computer said <samp>Unknown error -3</samp>.
kbd 사용자 입력
Hit <kbd>F1</kbd> to continue.
sub 아래 첨자
Water is H<sub>2</sub>O.
sup 위 첨자
The Hydrogen in heavy water is usually <sup>2</sup>H.
i 대체 음성
Lemonade consists primarily of <i>Citrus limon</i>.
b 키워드
Take a <b>lemon</b> and squeeze it with a <b>juicer</b>.
u 주석
The mixture of apple juice and <u class="spelling">eldeflower</u> juice is very pleasant.
mark 하이라이트
Elderflower cordial, with one <mark>part</mark> cordial to ten <mark>part</mark>s water, stands a<mark>part</mark> from the rest.
bdi 텍스트 방향성 격리
The recommended restaurant is <bdi lang="">My Juice Café (At The Beach)</bdi>.
bdo 텍스트 방향성 포맷
The proposal is to write English, but in reverse order. "Juice" would become "<bdo dir=rtl>Juice</bdo>">
span 기타
In French we call it <span lang="fr">sirop de sureau</span>.
br 줄바꿈
Simply Orange Juice Company<br>Apopka, FL 32703<br>U.S.A.
wbr 줄바꿈 기회
www.simply<wbr>orange<wbr>juice.com

4.6.1 소개

링크는 a, area, formlink 요소에 의해 생성된 개념적 구조로, 하나는 현재 document이고 다른 하나는 리소스 간의 연결을 표현합니다. HTML에는 세 가지 종류의 링크가 있습니다:

외부 리소스 링크

이들은 현재 문서를 보완하기 위해 사용될 리소스에 대한 링크로, 일반적으로 사용자 에이전트에 의해 자동으로 처리됩니다. 모든 외부 리소스 링크는 리소스를 가져오는 방법을 설명하는 링크된 리소스를 가져와 처리하는 알고리즘을 가지고 있습니다.

하이퍼링크

이들은 일반적으로 사용자에게 노출되어 사용자가 네비게이트할 수 있는 리소스에 대한 링크입니다. 예를 들어 브라우저에서 방문하거나 다운로드할 수 있습니다.

내부 리소스 링크

이들은 현재 문서 내의 리소스에 대한 링크로, 해당 리소스에 특별한 의미나 동작을 부여하기 위해 사용됩니다.

link 요소가 href 속성과 rel 속성을 가지고 있는 경우, 링크는 링크 유형 섹션에서 정의된 대로 rel 속성의 키워드에 대해 생성되어야 합니다.

유사하게, aarea 요소가 href 속성과 rel 속성을 가지고 있는 경우, 링크 유형 섹션에서 정의된 대로 rel 속성의 키워드에 대해 링크가 생성되어야 합니다. 그러나 link 요소와 달리, aarea 요소가 href 속성을 가지고 있지만 rel 속성이 없거나, rel 속성이 하이퍼링크를 지정하는 키워드를 포함하지 않는 경우에도 하이퍼링크를 생성해야 합니다. 이 암시된 하이퍼링크는 그 이상의 특별한 의미가 없으며(즉, 링크 유형이 없음) 해당 요소의 href 속성에 의해 주어진 리소스와 요소의 노드 문서를 연결합니다.

유사하게, form 요소가 rel 속성을 가지고 있는 경우, 링크 유형 섹션에서 정의된 대로 rel 속성의 키워드에 대해 링크가 생성되어야 합니다. form 요소에 rel 속성이 없거나, rel 속성이 하이퍼링크를 지정하는 키워드를 포함하지 않는 경우에도 하이퍼링크를 생성해야 합니다.

하이퍼링크에는 해당 하이퍼링크의 처리 의미를 수정하는 하나 이상의 하이퍼링크 주석이 있을 수 있습니다.

href 속성이 aarea 요소에 있는 경우, 이 속성의 값은 공백으로 둘러싸일 수 있는 유효한 URL이어야 합니다.

href 속성이 aarea 요소에 없어도 됩니다. 이러한 요소에 href 속성이 없으면 하이퍼링크가 생성되지 않습니다.

target 속성이 있는 경우, 이 속성은 유효한 내비게이션 대상 이름 또는 키워드여야 합니다. 이 속성은 사용될 내비게이션 가능한 객체의 이름을 지정합니다. 사용자 에이전트는 하이퍼링크를 따를 때 이 이름을 사용합니다.

download 속성이 있는 경우, 저자는 이 하이퍼링크가 리소스를 다운로드하는 데 사용되기를 원함을 나타냅니다. 이 속성은 값을 가질 수 있으며, 값이 있는 경우, 이는 저자가 로컬 파일 시스템에서 리소스를 레이블링하는 데 사용할 것을 권장하는 기본 파일 이름을 지정합니다. 허용되는 값에 제한은 없지만, 대부분의 파일 시스템은 파일 이름에 사용할 수 있는 구두점에 제한이 있으므로 저자는 주의해야 하며, 사용자 에이전트는 파일 이름을 적절히 조정할 가능성이 있습니다.

Element/a#attr-ping

모든 최신 엔진에서 지원됩니다.

Firefox🔰 1+Safari6+Chrome12+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android≤37+Samsung Internet?Opera Android?

ping 속성이 있는 경우, 사용자가 하이퍼링크를 따를 때 알림을 받고자 하는 리소스의 URL을 제공합니다. 이 값은 공백으로 구분된 토큰 집합이어야 하며, 각 토큰은 유효한 비어 있지 않은 URL이어야 하며, 이 URL의 스킴HTTP(S) 스킴이어야 합니다. 이 값은 사용자 에이전트에 의해 하이퍼링크 감사에 사용됩니다.

rel 속성이 aarea 요소에 있는 경우, 이 속성은 요소가 생성하는 링크의 종류를 제어합니다. 이 속성의 값은 순서가 없는 고유한 공백으로 구분된 토큰 집합이어야 합니다. 허용된 키워드와 그 의미는 아래에 정의되어 있습니다.

rel지원되는 토큰HTML 링크 유형에서 정의된 키워드로, aarea 요소에 허용되며, 처리 모델에 영향을 미치고 사용자 에이전트에서 지원됩니다. 가능한 지원되는 토큰noreferrer, noopener, 그리고 opener입니다. rel지원되는 토큰은 사용자 에이전트가 처리 모델을 구현하는 이 목록의 토큰만 포함해야 합니다.

rel 속성은 기본값이 없습니다. 속성이 생략되거나 속성의 값이 사용자 에이전트에서 인식되지 않으면 문서와 대상 리소스 간에는 하이퍼링크 외에 특별한 관계가 없습니다.

hreflang 속성이 a 요소에 있는 경우, 이 속성은 연결된 리소스의 언어를 지정합니다. 이 속성은 순수하게 권고 사항입니다. 값은 유효한 BCP 47 언어 태그여야 합니다. 사용자 에이전트는 이 속성을 권위적으로 간주해서는 안 되며, 리소스를 가져온 후에는 리소스의 언어를 결정하기 위해 링크된 리소스의 메타데이터가 아니라 리소스에 연결된 언어 정보를 사용해야 합니다.

type 속성이 있는 경우, 이 속성은 연결된 리소스의 MIME 유형을 제공합니다. 이 속성은 순수하게 권고 사항입니다. 값은 유효한 MIME 유형 문자열이어야 합니다. 사용자 에이전트는 type 속성을 권위적으로 간주해서는 안 되며, 리소스를 가져온 후에는 링크된 리소스의 메타데이터를 사용하여 유형을 결정해서는 안 됩니다.

referrerpolicy 속성은 리퍼러 정책 속성입니다. 이 속성의 목적은 리퍼러 정책을 설정하는 것입니다.


a 또는 area 요소의 활성화 동작이 호출되면 사용자 에이전트는 사용자가 하이퍼링크를 탐색하는 데 사용할지, 아니면 지정된 리소스를 다운로드할지에 대한 선호를 표시하도록 허용할 수 있습니다.

사용자 환경 설정이 없는 경우, 요소에 download 속성이 없으면 기본값은 탐색이어야 하며, 해당 속성이 있으면 지정된 리소스를 다운로드하는 것이어야 합니다.

이벤트 event가 주어진 element에 대해 a 또는 area 요소의 활성화 동작은 다음과 같습니다:

  1. elementhref 속성이 없으면 반환합니다.

  2. hyperlinkSuffix를 null로 설정합니다.

  3. elementa 요소이고 event대상img이며 ismap 속성이 지정된 경우:

    1. xy를 0으로 설정합니다.

    2. eventisTrusted 속성이 true로 초기화된 경우, x를 클릭 위치에서 이미지의 왼쪽 가장자리까지의 거리( CSS 픽셀 단위)로 설정하고, y를 클릭 위치에서 이미지의 위쪽 가장자리까지의 거리( CSS 픽셀 단위)로 설정합니다.

    3. x가 음수인 경우, x를 0으로 설정합니다.

    4. y가 음수인 경우, y를 0으로 설정합니다.

    5. hyperlinkSuffix를 U+003F(?)와 x의 값을 ASCII 숫자를 사용하여 10진수로 표현한 값으로, U+002C(,)와 y의 값을 ASCII 숫자를 사용하여 10진수로 표현한 값으로 설정합니다.

  4. userInvolvementevent사용자 내비게이션 개입으로 설정합니다.

  5. 사용자가 하이퍼링크 다운로드를 선호한다고 표시한 경우, userInvolvement를 "브라우저 UI"로 설정합니다.

    즉, 사용자가 다운로드를 선호한다고 명시적으로 표시한 경우, 이는 더 이상 단순히 "활성화"로 간주되지 않습니다.

  6. elementdownload 속성이 있거나, 사용자가 하이퍼링크 다운로드를 선호한다고 표시한 경우, element에 의해 생성된 하이퍼링크를 hyperlinkSuffixhyperlinkSuffix로 설정하고, userInvolvementuserInvolvement로 설정하여 하이퍼링크를 다운로드합니다.

  7. 그렇지 않은 경우, element에 의해 생성된 하이퍼링크를 hyperlinkSuffixhyperlinkSuffix로 설정하고, userInvolvementuserInvolvement로 설정하여 하이퍼링크를 따릅니다.

4.6.3 aarea 요소를 위한 API

interface mixin HTMLHyperlinkElementUtils {
[CEReactions] stringifier attribute USVString href;
readonly attribute USVString origin;
[CEReactions] attribute USVString protocol;
[CEReactions] attribute USVString username;
[CEReactions] attribute USVString password;
[CEReactions] attribute USVString host;
[CEReactions] attribute USVString hostname;
[CEReactions] attribute USVString port;
[CEReactions] attribute USVString pathname;
[CEReactions] attribute USVString search;
[CEReactions] attribute USVString hash;
};
hyperlink.toString()
hyperlink.href

HTMLAnchorElement/href

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAnchorElement/toString

모든 최신 엔진에서 지원됩니다.

Firefox22+Safari3+Chrome52+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLAreaElement/href

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/toString

모든 최신 엔진에서 지원됩니다.

Firefox22+Safari10.1+Chrome32+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL을 반환합니다.

설정할 수 있으며, 이를 통해 URL을 변경할 수 있습니다.

hyperlink.origin

HTMLAnchorElement/origin

모든 최신 엔진에서 지원됩니다.

Firefox26+Safari5.1+Chrome8+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android?

HTMLAreaElement/origin

모든 최신 엔진에서 지원됩니다.

Firefox26+Safari10+Chrome32+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?

하이퍼링크의 URL 출처를 반환합니다.

hyperlink.protocol

HTMLAnchorElement/protocol

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/protocol

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL 스킴을 반환합니다.

URL 스킴을 변경하려면 설정할 수 있습니다.

hyperlink.username

HTMLAnchorElement/username

모든 최신 엔진에서 지원됩니다.

Firefox26+Safari10+Chrome32+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/username

모든 최신 엔진에서 지원됩니다.

Firefox26+Safari10+Chrome32+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL 사용자 이름을 반환합니다.

URL의 사용자 이름을 변경하려면 설정할 수 있습니다.

hyperlink.password

HTMLAnchorElement/password

모든 최신 엔진에서 지원됩니다.

Firefox26+Safari10+Chrome32+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/password

모든 최신 엔진에서 지원됩니다.

Firefox26+Safari10+Chrome32+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL 비밀번호를 반환합니다.

URL의 비밀번호를 변경하려면 설정할 수 있습니다.

hyperlink.host

HTMLAnchorElement/host

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/host

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL의 호스트와 포트를 반환합니다(스킴의 기본 포트와 다른 경우).

URL의 호스트와 포트를 변경하려면 설정할 수 있습니다.

hyperlink.hostname

HTMLAnchorElement/hostname

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/hostname

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL의 호스트를 반환합니다.

URL의 호스트를 변경하려면 설정할 수 있습니다.

hyperlink.port

HTMLAnchorElement/port

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/port

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL의 포트를 반환합니다.

URL의 포트를 변경하려면 설정할 수 있습니다.

hyperlink.pathname

HTMLAnchorElement/pathname

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/pathname

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL 경로를 반환합니다.

URL 경로를 변경하려면 설정할 수 있습니다.

hyperlink.search

HTMLAnchorElement/search

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/search

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL 매개변수 문자열을 반환합니다(비어 있지 않으면 앞에 "?" 포함).

URL의 매개변수 문자열을 변경하려면 설정할 수 있습니다(앞의 "?"는 무시됨).

hyperlink.hash

HTMLAnchorElement/hash

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement/hash

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

하이퍼링크의 URL의 fragment를 반환합니다(비어 있지 않으면 앞에 "#" 포함).

URL의 fragment를 변경하려면 설정할 수 있습니다(앞의 "#"는 무시됨).

HTMLHyperlinkElementUtils 믹스를 구현하는 요소에는 관련된 url(null 또는 URL)이 있습니다. 이 값은 처음에 null입니다.

HTMLHyperlinkElementUtils 믹스를 구현하는 요소에는 관련된 URL 설정 알고리즘이 있으며, 다음 단계가 실행됩니다:

  1. 이 요소의 url을 null로 설정합니다.

  2. 이 요소의 href 콘텐츠 속성이 없으면, 반환합니다.

  3. 이 요소의 href 콘텐츠 속성 값을 기준으로 URL 인코딩 및 파싱의 결과로 url을 설정합니다.

  4. url이 실패가 아니라면, 이 요소의 urlurl로 설정합니다.

HTMLHyperlinkElementUtils 믹스를 구현하는 요소가 생성될 때 및 이 요소들의 href 콘텐츠 속성이 설정, 변경 또는 제거될 때마다 사용자 에이전트는 URL을 설정해야 합니다.

이는 blob: URL에 대해서만 관찰할 수 있습니다. URL 파싱Blob URL 저장소 조회를 포함하기 때문입니다.

HTMLHyperlinkElementUtils 믹스를 구현하는 요소에는 관련된 URL 재초기화 알고리즘이 있으며, 다음 단계가 실행됩니다:

  1. 요소의 url이 null이 아니고, 스킴이 "blob"이며, 불투명 경로가 있는 경우, 이 단계를 종료합니다.

  2. URL을 설정합니다.

href 업데이트하기 위해, 요소의 href 콘텐츠 속성 값을 요소의 url에 따라 직렬화된 값으로 설정합니다.


href 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이고, thishref 콘텐츠 속성이 없으면, 빈 문자열을 반환합니다.

  4. 그렇지 않고 url이 null이면, thishref 콘텐츠 속성 값을 반환합니다.

  5. url직렬화된 값으로 반환합니다.

href 설정 단계는 다음과 같습니다:

  1. thishref 콘텐츠 속성 값을 주어진 값으로 설정합니다.

origin 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. thisurl이 null이면, 빈 문자열을 반환합니다.

  3. 원본의 ASCII 직렬화를 반환합니다.

protocol 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. thisurl이 null이면, ":"를 반환합니다.

  3. thisurl스킴을 ":"로 반환합니다.

protocol 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. thisurl이 null이면, 반환합니다.

  3. 주어진 값을 ":"로 설정하고, thisurl기본 URL 파서로 파싱합니다.

URL 파서는 연속된 콜론을 무시하기 때문에, "https:" 또는 "https::::" 값을 제공하는 것은 "https" 값을 제공하는 것과 동일합니다.

  1. href 업데이트를 수행합니다.

username 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. thisurl이 null이면, 빈 문자열을 반환합니다.

  3. thisurlusername을 반환합니다.

username 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 urlusername/password/port를 가질 수 없으면, 반환합니다.

  4. 주어진 값에 따라 url의 username을 설정합니다.

  5. href 업데이트를 수행합니다.

password 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이면, 빈 문자열을 반환합니다.

  4. urlpassword를 반환합니다.

password 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 urlusername/password/port를 가질 수 없으면, 반환합니다.

  4. 주어진 값에 따라 url의 password를 설정합니다.

  5. href 업데이트를 수행합니다.

host 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이나 urlhost가 null이면, 빈 문자열을 반환합니다.

  4. urlport가 null이면, urlhost직렬화된 값으로 반환합니다.

  5. urlhost직렬화된 값으로 반환하고, ":" 뒤에 urlport직렬화된 값으로 반환합니다.

host 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 url불투명 경로가 있으면, 반환합니다.

  4. 주어진 값을 기준으로 기본 URL 파싱을 수행하고, urlurl로 설정하며, 호스트 상태상태 재정의로 설정합니다.

  5. href 업데이트를 수행합니다.

hostname 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이나 urlhost가 null이면, 빈 문자열을 반환합니다.

  4. urlhost직렬화된 값으로 반환합니다.

hostname 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 url불투명 경로가 있으면, 반환합니다.

  4. 주어진 값을 기준으로 기본 URL 파싱을 수행하고, urlurl로 설정하며, 호스트 이름 상태상태 재정의로 설정합니다.

  5. href 업데이트를 수행합니다.

port 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이나 urlport가 null이면, 빈 문자열을 반환합니다.

  4. urlport직렬화된 값으로 반환합니다.

port 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 urlusername/password/port를 가질 수 없으면, 반환합니다.

  4. 주어진 값이 빈 문자열이면, urlport를 null로 설정합니다.

  5. 그렇지 않으면, 주어진 값을 기준으로 기본 URL 파싱을 수행하고, urlurl로 설정하며, 포트 상태상태 재정의로 설정합니다.

  6. href 업데이트를 수행합니다.

pathname 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이면, 빈 문자열을 반환합니다.

  4. URL 경로 직렬화 결과를 반환합니다.

pathname 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 url불투명 경로가 있으면, 반환합니다.

  4. url경로를 빈 목록으로 설정합니다.

  5. 주어진 값을 기준으로 기본 URL 파싱을 수행하고, urlurl로 설정하며, 경로 시작 상태상태 재정의로 설정합니다.

  6. href 업데이트를 수행합니다.

search 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 url쿼리가 null 또는 빈 문자열이면, 빈 문자열을 반환합니다.

  4. "?" 뒤에 url쿼리를 반환합니다.

search 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이면, 이 단계를 종료합니다.

  4. 주어진 값이 빈 문자열이면, url쿼리를 null로 설정합니다.

  5. 그렇지 않으면:

    1. 주어진 값에서 단일 선도 "?"를 제거한 값을 input으로 설정합니다.

    2. url쿼리를 빈 문자열로 설정합니다.

    3. 기본 URL 파싱을 수행하고, urlurl로 설정하며, 쿼리 상태상태 재정의로 설정합니다.

  6. href 업데이트를 수행합니다.

hash 가져오기 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이거나 urlfragment가 null이거나 빈 문자열이면, 빈 문자열을 반환합니다.

  4. "#" 뒤에 urlfragment를 반환합니다.

hash 설정 단계는 다음과 같습니다:

  1. URL 재초기화합니다.

  2. urlthisurl로 설정합니다.

  3. url이 null이면, 반환합니다.

  4. 주어진 값이 빈 문자열이면, urlfragment를 null로 설정합니다.

  5. 그렇지 않으면:

    1. 주어진 값에서 단일 선도 "#"를 제거한 값을 input으로 설정합니다.

    2. urlfragment를 빈 문자열로 설정합니다.

    3. 기본 URL 파싱을 수행하고, urlurl로 설정하며, 조각 상태상태 재정의로 설정합니다.

  6. href 업데이트를 수행합니다.

element 요소가 다음 중 하나라도 해당하면 이동할 수 없습니다:

이것은 또한 form 요소의 폼 제출에서도 사용됩니다. a 요소에 대한 예외는 웹 콘텐츠와의 호환성을 위해 존재합니다.

요소의 noopener 얻기 방법은 다음과 같습니다. a, area, 또는 form 요소 element와 문자열 target이 주어진 경우:

  1. element링크 유형noopener 또는 noreferrer 키워드가 포함되어 있으면, true를 반환합니다.

  2. element링크 유형opener 키워드가 포함되어 있지 않으며 target이 "_blank"와 ASCII 대소문자 구분 없이 일치하는 경우, true를 반환합니다.

  3. false를 반환합니다.

하이퍼링크를 따르기 위해 subject 요소가 주어졌을 때, 선택적으로 hyperlinkSuffix (기본값 null)와 userInvolvement (기본값 "none")가 주어질 수 있습니다:

  1. subject이동할 수 없는 경우, 반환합니다.

  2. replace를 false로 설정합니다.

  3. targetAttributeValue를 빈 문자열로 설정합니다.

  4. subjecta 또는 area 요소인 경우, subject를 사용하여 요소의 대상 얻기 결과를 targetAttributeValue로 설정합니다.

  5. 요소의 noopener 얻기 결과를 subjecttargetAttributeValuenoopener에 설정합니다.

  6. targetNavigable탐색 가능한 객체 선택 규칙을 적용하여 targetAttributeValue, subject노드 탐색 가능 객체noopener를 사용하여 첫 번째 반환값으로 설정합니다.

  7. targetNavigable이 null인 경우, 반환합니다.

  8. urlStringsubjecthref 속성 값을 subject노드 문서에 상대적으로 URL 인코딩-파싱-직렬화 결과로 설정합니다.

  9. urlString이 실패인 경우, 반환합니다.

  10. hyperlinkSuffix가 null이 아닌 경우, 이를 urlString에 추가합니다.

  11. referrerPolicysubjectreferrerpolicy 속성의 현재 상태로 설정합니다.

  12. subject링크 유형noreferrer 키워드가 포함된 경우, referrerPolicy를 "no-referrer"로 설정합니다.

  13. 탐색 targetNavigableurlString으로 subject노드 문서를 사용하여 수행하며, referrerPolicyreferrerPolicy로 설정하고, userInvolvementuserInvolvement로 설정합니다.

    다른 유형의 탐색과 달리, 하이퍼링크를 따를 때 문서가 완전히 로드되지 않았을 때 특별한 "대체" 동작이 없습니다. 이는 사용자에 의해 시작된 하이퍼링크 추적뿐만 아니라 aElement.click()와 같은 스크립트로 트리거된 경우에도 동일합니다.

4.6.5 리소스 다운로드

HTMLAnchorElement/download

현재 모든 엔진에서 지원됩니다.

Firefox20+Safari10.1+Chrome15+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

일부 경우 리소스는 즉시 보기보다는 나중에 사용하기 위해 다운로드할 수 있도록 의도됩니다. 리소스가 즉시 사용되는 대신 나중에 사용하기 위해 다운로드하도록 지정하려면, 해당 리소스에 대한 download 속성을 a 또는 area 요소에 지정할 수 있습니다.

속성에는 또한 값이 주어질 수 있으며, 이는 사용자 에이전트가 리소스를 파일 시스템에 저장할 때 사용할 파일 이름을 지정합니다. 이 값은 `Content-Disposition` HTTP 헤더의 파일 이름 매개변수로 재정의될 수 있습니다. [RFC6266]

교차 출처 상황에서는, download 속성을 `Content-Disposition` HTTP 헤더, 특히 attachment 디스포지션 타입과 결합해야 합니다. 이는 사용자가 민감한 개인 정보나 기밀 정보를 충분히 이해하지 못한 상태에서 다운로드하지 않도록 보호하기 위한 것입니다.


요소 subject가 생성한 하이퍼링크를 주어진 선택적 hyperlinkSuffix(기본값 null) 및 선택적 userInvolvement(기본값 "없음")과 함께 다운로드하려면:

  1. subject탐색할 수 없는 경우, 종료합니다.

  2. subject노드 문서활성 샌드박싱 플래그 세트샌드박스화된 다운로드 브라우징 컨텍스트 플래그가 설정되어 있으면, 종료합니다.

  3. urlStringURL 인코딩, 파싱 및 직렬화의 결과로 설정합니다. 이 때 subjecthref 속성 값을 사용하고, subject노드 문서를 기준으로 합니다.

  4. urlString이 실패하면, 종료합니다.

  5. hyperlinkSuffix가 null이 아닌 경우, 이를 urlString에 추가합니다.

  6. userInvolvement가 "브라우저 UI"가 아닌 경우:

    1. 확인: subjectdownload 속성을 가지고 있습니다.

    2. navigationsubject관련 전역 객체탐색 API로 설정합니다.

    3. filenamesubjectdownload 속성의 값으로 설정합니다.

    4. continue다운로드 요청 탐색 이벤트 발사의 결과로 설정하고, 이 때 목적지 URLurlString으로 설정하고, userInvolvementuserInvolvement로 설정하고, filenamefilename으로 설정합니다.

    5. continue가 false이면, 종료합니다.

  7. 다음 단계를 병렬로 실행합니다:

    1. 사용자 에이전트는 사용자를 잠재적으로 위험한 다운로드로부터 보호하기 위해 필요하다고 판단되면 이 단계를 중단할 수 있습니다.

    2. request를 새 요청으로 설정하며, 이 요청의 URLurlString, 클라이언트엔트리 설정 객체, 요청자는 "download", 목적지는 빈 문자열로 설정하며, 동기화 플래그URL 자격 증명 플래그를 설정합니다.

    3. fetch의 결과를 request로 처리하고, 이를 다운로드로 처리합니다.

사용자 에이전트가 fetch로부터 얻은 리소스를 다운로드로 처리해야 하는 경우, 리소스를 성공적으로 얻으면 나중에 사용할 수 있도록 저장하는 방법을 사용자에게 제공해야 합니다. 그렇지 않으면 파일 다운로드 시 발생한 문제를 사용자에게 보고해야 합니다.

사용자 에이전트가 다운로드로 처리 중인 리소스의 파일 이름이 필요할 경우, 다음 알고리즘을 사용하여 선택해야 합니다.

이 알고리즘은 신뢰할 수 없는 사이트에서 파일을 다운로드하는 데 따른 보안 위험을 완화하기 위한 것으로, 사용자 에이전트는 이를 준수할 것을 강력히 권장합니다.

  1. filename을 정의되지 않은 값으로 설정합니다.

  2. 리소스에 `Content-Disposition` 헤더가 있으며, 해당 헤더가 attachment 디스포지션 타입을 지정하고, 헤더에 파일 이름 정보가 포함되어 있으면, filename을 헤더에서 지정한 값으로 설정하고, 아래의 sanitize 단계로 이동합니다. [RFC6266]

  3. interface origin문서출처로 설정합니다. 이 문서는 다운로드 작업이나 다운로드로 이어진 탐색 작업이 시작된 document입니다.

  4. resource origin을 다운로드 중인 리소스의 URL의 스킴data가 아닌 경우 리소스의 출처로 설정합니다. 스킴이 data인 경우, resource origininterface origin과 동일하게 설정합니다.

  5. interface origin이 없으면, trusted operation을 true로 설정합니다. 그렇지 않으면, resource origininterface origin동일 출처인 경우 trusted operation을 true로, 그렇지 않은 경우 false로 설정합니다.

  6. trusted operation이 true이고 리소스에 `Content-Disposition` 헤더가 있으며, 해당 헤더에 파일 이름 정보가 포함되어 있으면, filename을 헤더에서 지정한 값으로 설정하고, 아래의 sanitize 단계로 이동합니다. [RFC6266]

  7. 다운로드가 a 또는 area 요소가 생성한 하이퍼링크에서 시작되지 않았거나, 하이퍼링크가 시작된 하이퍼링크의 요소에 다운로드가 시작될 때 download 속성이 없었거나, 속성이 있었지만 다운로드가 시작될 때 그 값이 빈 문자열이었으면, 아래의 no proposed filename 단계로 이동합니다.

  8. proposed filename을 다운로드가 시작된 시점에서 하이퍼링크의 요소의 download 속성 값으로 설정합니다.

  9. trusted operation이 true이면, filenameproposed filename 값으로 설정하고, 아래의 sanitize 단계로 이동합니다.

  10. 리소스에 `Content-Disposition` 헤더가 있으며, 해당 헤더가 attachment 디스포지션 타입을 지정한 경우, filenameproposed filename 값으로 설정하고, 아래의 sanitize 단계로 이동합니다. [RFC6266]

  11. no proposed filename: trusted operation이 true이거나, 사용자가 해당 리소스를 다운로드하도록 선호했음을 나타내면, filename을 리소스의 URL에서 파생된 값으로 설정하고, 아래의 sanitize 단계로 이동합니다.

  12. filename을 사용자가 선호하는 파일 이름이나 사용자 에이전트가 선택한 파일 이름으로 설정하고, 아래의 sanitize 단계로 이동합니다.

    알고리즘이 이 단계에 도달하면, 다운로드는 다운로드 중인 리소스와 다른 출처에서 시작되었으며, 해당 출처는 파일을 다운로드에 적합하다고 표시하지 않았고, 다운로드는 사용자가 시작하지 않은 것입니다. 이는 download 속성이 다운로드를 트리거하거나, 해당 리소스가 사용자 에이전트가 지원하지 않는 유형일 수 있기 때문일 수 있습니다.

    이로 인해 위험할 수 있습니다. 예를 들어, 적대적인 서버가 사용자가 해당 데이터가 적대적인 서버에서 나온 것이라고 착각하게 만들어 개인 정보를 모르게 다운로드하고 다시 업로드하도록 속일 수 있기 때문입니다.

    따라서, 사용자가 해당 리소스가 매우 다른 출처에서 왔음을 어느 정도 인지하도록 알리고, 혼동을 방지하기 위해 잠재적으로 적대적인 interface origin에서 제안된 파일 이름은 무시하는 것이 사용자에게 유리합니다.

  13. sanitize: 선택적으로, filename에 대해 사용자가 영향을 미칠 수 있게 허용합니다. 예를 들어, 사용자 에이전트는 사용자가 파일 이름을 입력하도록 요청할 수 있으며, 위에서 결정된 filename 값을 기본값으로 제공할 수 있습니다.

  14. filename을 로컬 파일 시스템에 적합하게 조정합니다.

    예를 들어, 이는 파일 이름에 유효하지 않은 문자를 제거하거나, 앞뒤 공백을 제거하는 것일 수 있습니다.

  15. 플랫폼 규칙이 파일 시스템의 파일 유형을 결정하는 데 확장자를 전혀 사용하지 않는 경우, filename을 파일 이름으로 반환합니다.

  16. claimed type을 리소스의 콘텐츠 유형 메타데이터에서 제공되는 유형으로 설정합니다. named typefilename확장자로 설정합니다. 이 단계에서는 유형MIME 유형확장자에 매핑하는 것으로 정의됩니다.

  17. named type이 사용자의 선호와 일치하는 경우(예: filename 값이 사용자에게 묻는 방식으로 결정된 경우), filename을 파일 이름으로 반환합니다.

  18. claimed typenamed type이 동일한 유형인 경우(즉, 리소스의 콘텐츠 유형 메타데이터에서 제공되는 유형이 filename확장자와 일치하는 경우), filename을 파일 이름으로 반환합니다.

  19. claimed type이 알려진 경우, filename을 해당 유형에 해당하는 확장자를 추가하도록 변경합니다.

    그렇지 않으면, named type이 잠재적으로 위험한 것으로 알려진 경우(예: 플랫폼 규칙에 따라 네이티브 실행 파일, 셸 스크립트, HTML 애플리케이션 또는 실행 가능한 매크로 문서로 처리될 수 있음), 선택적으로 filename을 안전한 확장자를 추가하여 변경할 수 있습니다(예: ".txt").

    이 마지막 단계는 실행 파일을 다운로드하는 것을 불가능하게 만들 수 있으며, 이는 바람직하지 않을 수 있습니다. 항상 그렇듯이 구현자는 이 문제에서 보안과 사용성 사이의 균형을 맞춰야 합니다.

  20. filename을 파일 이름으로 반환합니다.

이 알고리즘의 목적을 위해, 파일 확장자는 플랫폼 규칙이 파일의 유형을 식별하는 데 사용하도록 지정한 파일 이름의 모든 부분을 포함합니다. 예를 들어, 많은 운영 체제는 파일 이름의 마지막 점(".") 뒤의 부분을 사용하여 파일의 유형을 결정하고, 이를 바탕으로 파일을 열거나 실행하는 방식을 결정합니다.

사용자 에이전트는 리소스 자체, 해당 URLdownload 속성에서 제공된 디렉토리 또는 경로 정보를 무시하고, 사용자의 파일 시스템에서 결과 파일을 저장할 위치를 결정해야 합니다.

만약 a 또는 area 요소에 의해 생성된 하이퍼링크ping 속성이 있고, 사용자가 하이퍼링크를 따라가며, 해당 요소의 href 속성의 값이 해당 요소의 노드 문서를 기준으로 파싱될 수 있고, 실패 없이 파싱될 수 있다면, 사용자 에이전트는 ping 속성의 값을 가져와 해당 문자열을 ASCII 공백으로 분할하고, 각 결과 토큰을 해당 요소의 노드 문서를 기준으로 파싱한 후, 파싱이 실패한 경우를 무시하고, 각 결과 URL ping URL에 대해 다음 단계를 실행합니다:

  1. ping URL스킴HTTP(S) 스킴이 아니라면, 종료합니다.

  2. 선택적으로, 종료할 수 있습니다. (예를 들어, 사용자 에이전트는 사용자의 명시적인 선호에 따라 모든 ping URL을 무시할 수 있습니다.)

  3. settingsObject를 요소의 노드 문서관련 설정 객체로 설정합니다.

  4. request를 새 요청으로 설정합니다. 이 요청의 URLping URL, 메서드는 `POST`, 헤더 목록은 « (`Content-Type`, `text/ping`) », 본문은 `PING`, 클라이언트settingsObject, 목적지는 빈 문자열로 설정하며, 자격 증명 모드는 "include", 리퍼러는 "no-referrer"로 설정하며, URL 자격 증명 플래그를 설정하고, 요청자 유형은 "ping"로 설정합니다.

  5. target URL을 요소의 href 속성 값을 기준으로 인코딩-파싱-직렬화 URL의 결과로 설정한 후, 다음을 수행합니다:

    하이퍼링크를 포함하는 documentURLping URL동일 출처인지 확인합니다.
    출처가 다르지만, 감사 중인 하이퍼링크를 포함하는 document스킴이 "https"가 아닌 경우
    request에는 `Ping-From` 헤더와 하이퍼링크를 포함하는 문서의 URL이 값으로 포함되어야 하며, `Ping-To` HTTP 헤더와 target URL이 값으로 포함되어야 합니다.
    그렇지 않은 경우
    request에는 target URL이 값으로 포함된 `Ping-To` HTTP 헤더가 포함되어야 합니다. request에는 `Ping-From` 헤더가 포함되지 않습니다.
  6. Fetch request.

이 작업은 기본 fetch와 병렬로 수행될 수 있으며, 해당 fetch의 결과와 독립적입니다.

사용자 에이전트는 예를 들어 HTTP `Referer` (원문) 헤더를 보내는 설정과 함께 이 동작을 조정할 수 있도록 해야 합니다. 사용자의 선호에 따라 UAs는 ping 속성을 완전히 무시하거나 목록의 URL을 선택적으로 무시할 수 있습니다(예: 타사 URL을 무시). 이는 위의 단계에서 명시적으로 고려되었습니다.

사용자 에이전트는 응답에서 반환된 엔터티 본문을 무시해야 합니다. 사용자 에이전트는 응답 본문을 수신하기 시작하면 조기 연결을 종료할 수 있습니다.

ping 속성이 있는 경우, 사용자 에이전트는 하이퍼링크를 따라가는 것이 백그라운드에서 2차 요청을 보내는 것도 포함된다는 사실을 사용자에게 명확히 표시해야 하며, 실제 대상 URL 목록을 포함할 수 있습니다.

예를 들어, 시각적인 사용자 에이전트는 상태 표시줄이나 툴팁에서 하이퍼링크의 실제 URL과 함께 대상 ping URL의 호스트 이름을 포함할 수 있습니다.

ping 속성은 HTTP 리디렉션 및 자바스크립트와 같은 기존 기술과 중복되어 웹 페이지가 가장 인기 있는 외부 링크를 추적하거나 광고주가 클릭률을 추적할 수 있게 합니다.

그러나 ping 속성은 다음과 같은 이점을 사용자에게 제공합니다:

따라서 이 기능 없이도 사용자를 추적할 수 있지만, 작성자들은 사용자 경험을 더욱 투명하게 만들 수 있도록 사용자 에이전트가 ping 속성을 사용하도록 권장됩니다.

4.6.6.1 `Ping-From` 및 `Ping-To` 헤더

`Ping-From` 및 `Ping-To` HTTP 요청 헤더는 하이퍼링크 감사 요청에 포함됩니다. 이들의 값은 URL이며, 직렬화된 값입니다.

4.6.7 링크 유형

링크 유형

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

링크 유형

다음 표는 이 명세서에 정의된 링크 유형을 해당 키워드별로 요약한 것입니다. 이 표는 비규범적입니다. 링크 유형의 실제 정의는 다음 몇 섹션에서 설명합니다.

이 섹션에서는 참조된 문서라는 용어는 링크를 나타내는 요소에 의해 식별된 리소스를 나타내며, 현재 문서라는 용어는 링크를 나타내는 요소가 있는 리소스를 나타냅니다.

link, a, area 또는 form 요소에 적용되는 링크 유형을 결정하려면, 해당 요소의 rel 속성을 ASCII 공백으로 분할해야 합니다. 결과로 나온 토큰이 해당 요소에 적용되는 링크 유형의 키워드입니다.

특별히 명시된 경우를 제외하고, 키워드는 rel 속성당 한 번만 지정할 수 있습니다.

다음 표 아래에 나오는 일부 섹션에서는 특정 키워드의 동의어를 나열합니다. 표시된 동의어는 사용자 에이전트에서 명시된 대로 처리되어야 하지만, 문서에서 사용되어서는 안 됩니다(예: "copyright" 키워드).

키워드는 항상 ASCII 대소문자 구분 없이 비교해야 하며, 반드시 그렇게 비교되어야 합니다.

따라서, rel="next"rel="NEXT"와 동일합니다.

body-ok 키워드는 link 요소가 본문에 허용되는지 여부에 영향을 미칩니다. body-ok 키워드는 dns-prefetch, modulepreload, pingback, preconnect, prefetch, preload, 그리고 stylesheet입니다.

웹 브라우저에 의해 구현될 새로운 링크 유형은 이 표준에 추가되어야 합니다. 나머지는 확장으로 등록될 수 있습니다.

4.6.7.1 Link type "alternate"

Alternative_style_sheets

현재 엔진 하나에서만 지원됩니다.

Firefox3+Safari?Chrome1–48
OperaYesEdgeNo
Edge (Legacy)?Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

alternate 키워드는 link, a, 및 area 요소에서 사용할 수 있습니다.

이 키워드의 의미는 다른 속성의 값에 따라 달라집니다.

요소가 link 요소이고 rel 속성에 stylesheet 키워드도 포함된 경우

alternate 키워드는 stylesheet 키워드의 의미를 해당 키워드에 대해 설명된 방식으로 수정합니다. alternate 키워드는 자체 링크를 생성하지 않습니다.

다음과 같이, link 요소 세트가 스타일 시트를 제공합니다:

<!-- 지속적인 스타일 시트 -->
<link rel="stylesheet" href="default.css">

<!-- 선호하는 대체 스타일 시트 -->
<link rel="stylesheet" href="green.css" title="Green styles">

<!-- 일부 대체 스타일 시트 -->
<link rel="alternate stylesheet" href="contrast.css" title="High contrast">
<link rel="alternate stylesheet" href="big.css" title="Big fonts">
<link rel="alternate stylesheet" href="wide.css" title="Wide screen">
alternate 키워드가 type 속성이 application/rss+xml 값 또는 application/atom+xml 값을 가질 때 사용된 경우

이 키워드는 현재 페이지와 반드시 동일한 콘텐츠를 포함하지는 않지만, syndication 피드를 참조하는 하이퍼링크를 생성합니다.

피드 자동 발견을 위해 사용자 에이전트는 문서 내의 모든 link 요소에서 alternate 키워드가 사용되고 type 속성이 application/rss+xml 또는 application/atom+xml 값으로 설정된 경우 모두 고려해야 합니다. 사용자 에이전트에 기본 syndication 피드 개념이 있는 경우, 첫 번째 요소가 (적용 가능한 경우) 기본으로 사용되어야 합니다.

다음 link 요소들은 블로그의 syndication 피드를 제공합니다:

<link rel="alternate" type="application/atom+xml" href="posts.xml" title="Cool Stuff Blog">
<link rel="alternate" type="application/atom+xml" href="posts.xml?category=robots" title="Cool Stuff Blog: robots category">
<link rel="alternate" type="application/atom+xml" href="comments.xml" title="Cool Stuff Blog: Comments">

이러한 link 요소들은 피드 자동 발견에 사용되며, 첫 번째 요소가 (적용 가능한 경우) 기본으로 사용됩니다.

다음 예제는 a 요소를 사용하여 사용자에게 다양한 syndication 피드를 제공하는 방법을 보여줍니다:

<p>원하는 Atom 피드를 선택하세요:</p>
<ul>
 <li><a href="recently-visited-planets.xml" rel="alternate" type="application/atom+xml">Recently Visited Planets</a></li>
 <li><a href="known-bad-planets.xml" rel="alternate" type="application/atom+xml">Known Bad Planets</a></li>
 <li><a href="unexplored-planets.xml" rel="alternate" type="application/atom+xml">Unexplored Planets</a></li>
</ul>

이러한 링크들은 피드 자동 발견에 사용되지 않습니다.

그 외의 경우

이 키워드는 현재 문서의 대체 표현을 참조하는 하이퍼링크를 생성합니다.

참조된 문서의 성격은 hreflangtype 속성에 의해 결정됩니다.

alternate 키워드가 hreflang 속성과 함께 사용되고, 해당 속성의 값이 문서 요소언어와 다를 경우, 참조된 문서가 번역본임을 나타냅니다.

alternate 키워드가 type 속성과 함께 사용될 경우, 이는 참조된 문서가 지정된 형식으로 현재 문서를 재구성한 것임을 나타냅니다.

hreflangtype 속성은 alternate 키워드와 함께 지정될 때 결합하여 사용할 수 있습니다.

다음 예제는 페이지의 대체 형식을 사용하는 버전, 다른 언어를 대상으로 하는 버전 및 다른 미디어를 대상으로 하는 버전을 지정하는 방법을 보여줍니다:

<link rel=alternate href="/en/html" hreflang=en type=text/html title="English HTML">
<link rel=alternate href="/fr/html" hreflang=fr type=text/html title="French HTML">
<link rel=alternate href="/en/html/print" hreflang=en type=text/html media=print title="English HTML (for printing)">
<link rel=alternate href="/fr/html/print" hreflang=fr type=text/html media=print title="French HTML (for printing)">
<link rel=alternate href="/en/pdf" hreflang=en type=application/pdf title="English PDF">
<link rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF">

이 관계는 전이적입니다 — 즉, 문서가 "alternate" 링크 유형으로 두 다른 문서에 링크를 걸면, 그 문서들이 첫 번째 문서의 대체 표현이라는 것을 암시할 뿐만 아니라, 그 두 문서도 서로의 대체 표현이라는 것을 암시합니다.

author 키워드는 link, aarea 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

aarea 요소의 경우, author 키워드는 참조된 문서가 하이퍼링크를 정의하는 요소의 가장 가까운 article 요소의 작성자에 대한 추가 정보를 제공하거나, 해당 요소가 없을 경우 페이지 전체에 대한 정보를 제공한다는 것을 나타냅니다.

link 요소의 경우, author 키워드는 참조된 문서가 페이지 전체의 작성자에 대한 추가 정보를 제공한다는 것을 나타냅니다.

"참조된 문서"는 mailto: URL을 통해 작성자의 이메일 주소를 제공할 수 있으며, 이는 종종 실제로 그렇습니다. [MAILTO]

동의어: 역사적 이유로, 사용자 에이전트는 link, aarea 요소에 rev 속성이 "made" 값으로 지정된 경우 author 키워드가 링크 관계로 지정된 것으로 처리해야 합니다.

bookmark 키워드는 aarea 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

bookmark 키워드는 링크된 요소의 가장 가까운 상위 article 요소에 대한 고정 링크(permalink)를 제공합니다. 상위 article 요소가 없을 경우, 링크된 요소와 가장 밀접하게 연관된 섹션에 대한 고정 링크를 제공합니다.

다음 코드 조각에는 세 개의 고정 링크가 있습니다. 사용자 에이전트는 고정 링크가 제공되는 위치를 보고 각 부분에 어떤 고정 링크가 적용되는지 결정할 수 있습니다.

 ...
 <body>
  <h1>Example of permalinks</h1>
  <div id="a">
   <h2>First example</h2>
   <p><a href="a.html" rel="bookmark">This permalink applies to
   only the content from the first H2 to the second H2</a>. The DIV isn't
   exactly that section, but it roughly corresponds to it.</p>
  </div>
  <h2>Second example</h2>
  <article id="b">
   <p><a href="b.html" rel="bookmark">This permalink applies to
   the outer ARTICLE element</a> (which could be, e.g., a blog post).</p>
   <article id="c">
    <p><a href="c.html" rel="bookmark">This permalink applies to
    the inner ARTICLE element</a> (which could be, e.g., a blog comment).</p>
   </article>
  </article>
 </body>
 ...

canonical 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

canonical 키워드는 href 속성에 의해 제공되는 URL이 현재 문서의 선호 URL임을 나타냅니다. 이는 The Canonical Link Relation에서 더 자세히 설명된 것처럼 검색 엔진이 중복 콘텐츠를 줄이는 데 도움을 줍니다. [RFC6596]

Link_types/dns-prefetch

Firefox3+Safari?Chrome46+
Opera?Edge79+
Edge (Legacy)NoInternet Explorer?
Firefox Android?Safari iOS?Chrome AndroidYesWebView Android46+Samsung Internet?Opera Android?

dns-prefetch 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 자원 링크를 생성합니다. 이 키워드는 body-ok입니다.

dns-prefetch 키워드는 지정된 자원의 origin에 대해 사전에 DNS 해석을 수행하는 것이 사용자에게 유리할 가능성이 높으며, 사용자가 해당 origin에 위치한 자원을 필요로 할 가능성이 높아 DNS 해석과 관련된 지연 시간을 미리 줄여 사용자 경험을 향상시킬 수 있음을 나타냅니다.

dns-prefetch 키워드에 의해 제공되는 자원의 기본 유형은 없습니다.

이 유형의 링크된 자원을 가져와 처리해야 할 적절한 시기는 다음과 같습니다:

이 유형의 링크된 자원을 가져와 처리하는 단계link 요소 el이 주어질 때 다음과 같습니다:

  1. elhref 속성 값을 기준으로 URL 인코딩-파싱을 수행하여 url을 설정합니다.

  2. 만약 url이 실패라면, 종료합니다.

  3. el노드 문서관련 설정 객체를 기반으로 네트워크 파티션 키 결정의 결과로 partitionKey를 설정합니다.

  4. 사용자 에이전트는 partitionKeyurlorigin을 주어 origin을 해석해야 합니다.

    이 알고리즘의 결과는 캐시될 수 있으므로, 이후의 가져오기가 더 빨라질 수 있습니다.

expect 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 내부 자원 링크를 생성합니다.

expect 키워드로 생성된 내부 자원 링크는 해당 요소가 문서에 연결되고 완전히 구문 분석될 때까지 렌더링을 차단하는 데 사용할 수 있습니다.

expect 키워드로 제공된 자원의 기본 유형은 없습니다.

다음 조건 중 하나라도 link 요소 el에 해당하는 경우:

그런 다음 처리 el을 실행합니다.

link 요소 el이 주어질 때, 내부 자원 링크 처리를 실행하려면 다음 단계를 수행합니다:

  1. el노드 문서doc으로 설정합니다.

  2. elhref 속성 값을 기준으로 URL 인코딩-파싱의 결과를 url로 설정합니다.

  3. 이 작업이 실패하거나, url프래그먼트를 제외한 설정 없이 docURL일치하지 않으면 렌더링을 차단 해제하고 종료합니다.

  4. docurl을 사용하여 지정된 부분 선택의 결과를 indicatedElement로 설정합니다.

  5. 다음 조건이 모두 참이면:

    그런 다음 렌더링을 차단합니다.

  6. 그렇지 않으면 렌더링을 차단 해제합니다.

document doc에 대해 내부 자원 링크 처리를 실행하려면:

  1. expect link 요소 link에 대해 doc렌더링 차단 요소 집합에서, 처리합니다 link.

다음 속성 변경 단계expect link 요소가 동적 idname 변경에 대응하도록 보장하는 데 사용됩니다:

  1. namespace가 null이 아니면 반환합니다.

  2. element열린 요소의 스택에 있으면 반환합니다.

  3. 다음 중 하나가 참이면:

    그런 다음 내부 자원 링크 처리element노드 문서에서 실행합니다.

external 키워드는 a, area, 그리고 form 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성하지 않지만, 요소에 의해 생성된 다른 하이퍼링크(다른 키워드가 생성하지 않는 경우 암시된 하이퍼링크)에 대해 주석을 달아줍니다.

external 키워드는 링크가 현재 문서가 속한 사이트의 일부가 아닌 문서로 연결된다는 것을 나타냅니다.

help 키워드는 link, a, area, 그리고 form 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

a, area, 그리고 form 요소의 경우, help 키워드는 부모 요소와 그 자식 요소에 대한 추가 도움말 정보를 제공하는 문서를 참조한다고 나타냅니다.

다음 예제에서, 폼 컨트롤에는 문맥에 따라 관련된 도움말이 있습니다. 사용자 에이전트는 이 정보를 사용하여, 예를 들어 사용자가 "도움말" 또는 "F1" 키를 누르면 참조된 문서를 표시할 수 있습니다.

 <p><label> Topic: <input name=topic> <a href="help/topic.html" rel="help">(Help)</a></label></p>

link 요소의 경우, help 키워드는 참조된 문서가 페이지 전체에 대한 도움말을 제공한다고 나타냅니다.

aarea 요소의 경우, 일부 브라우저에서는 help 키워드가 링크가 다른 커서를 사용하도록 합니다.

4.6.7.9 링크 유형 "icon"

Link_types#icon

모든 현재 엔진에서 지원.

Firefox2+Safari3.1+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS지원 안됨Chrome Android18+WebView Android38+Samsung Internet4.0+Opera Android지원 안됨
caniuse.com table

icon 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 생성합니다.

지정된 리소스는 페이지 또는 사이트를 나타내는 아이콘이며, 사용자 에이전트가 사용자 인터페이스에서 페이지를 나타낼 때 사용해야 합니다.

아이콘은 청각적 아이콘, 시각적 아이콘 또는 다른 종류의 아이콘일 수 있습니다. 여러 아이콘이 제공되는 경우, 사용자 에이전트는 type, media, sizes 속성에 따라 가장 적합한 아이콘을 선택해야 합니다. 여러 개의 동일하게 적합한 아이콘이 있을 경우, 사용자 에이전트는 사용자가 아이콘 목록을 수집할 당시 트리 순서에서 마지막으로 선언된 아이콘을 사용해야 합니다. 사용자 에이전트가 아이콘을 사용하려 했으나, 실제로는 지원되지 않는 형식을 사용하는 등 부적절한 것으로 판단되면, 사용자 에이전트는 속성에 따라 다음으로 적합한 아이콘을 시도해야 합니다.

사용자 에이전트는 아이콘 목록이 변경될 때 아이콘을 업데이트할 필요는 없지만, 업데이트하는 것이 권장됩니다.

icon 키워드로 제공된 리소스에 대한 기본 유형은 없습니다. 그러나 리소스의 유형을 결정하는 목적을 위해, 사용자 에이전트는 리소스가 이미지일 것으로 예상해야 합니다.

sizes 키워드는 아이콘 크기를 원시 픽셀로 나타냅니다(CSS 픽셀과 대조적으로).

장치 픽셀 밀도가 CSS 픽셀당 두 장치 픽셀(2x, 192dpi)인 디스플레이를 위해 50 CSS 픽셀 너비의 아이콘은 100 원시 픽셀의 너비를 갖게 됩니다. 이 기능은 작은 고해상도 아이콘과 큰 저해상도 아이콘에 대해 다른 리소스를 사용해야 함을 나타내는 것은 지원하지 않습니다(예: 50×50 2x 대 100×100 1x).

속성의 값을 구문 분석하고 처리하기 위해, 사용자 에이전트는 먼저 속성의 값을 ASCII 공백으로 분할한 다음, 각 결과 키워드를 구문 분석하여 그것이 나타내는 바를 결정해야 합니다.

any 키워드는 리소스가 SVG 이미지와 같이 확장 가능한 아이콘을 포함하고 있음을 나타냅니다.

다른 키워드는 다음과 같이 추가로 구문 분석하여 무엇을 나타내는지 결정해야 합니다:

sizes 속성에 지정된 키워드는 링크된 리소스에서 실제로 사용 가능한 아이콘 크기를 나타내지 않아야 합니다.

link 요소 el요청 request이 주어졌을 때, 이 유형의 링크된 리소스에 대한 링크된 리소스 페치 설정 단계는 다음과 같습니다:

  1. request목적지를 "image"로 설정합니다.

  2. true를 반환합니다.

이 유형의 링크된 리소스에 대한 링크 헤더 처리 단계는 아무 것도 하지 않습니다.

만약 link 요소와 icon 키워드가 없는 경우, Document 객체의 URL스킴HTTP(S) 스킴인 경우, 사용자 에이전트는 대신 이러한 단계를 병렬로 실행할 수 있습니다:

  1. request요청이며, URLURL 레코드로, Document 객체의 URL에 대해 "/favicon.ico"를 해결하여 얻은 URL이며, 클라이언트Document 객체의 관련 설정 객체, 목적지는 "image", 동기 플래그가 설정되고, 자격 증명 모드는 "include", URL 자격 증명 사용 플래그가 설정된 새 요청을 만들고.

  2. response페치 request의 결과입니다.

  3. response안전하지 않은 응답을 아이콘으로 사용하며, 마치 icon 키워드를 사용하여 선언된 것처럼 합니다.

다음 스니펫은 여러 아이콘이 있는 애플리케이션의 상단 부분을 보여줍니다.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>lsForums — Inbox</title>
  <link rel=icon href=favicon.png sizes="16x16" type="image/png">
  <link rel=icon href=windows.ico sizes="32x32 48x48" type="image/vnd.microsoft.icon">
  <link rel=icon href=mac.icns sizes="128x128 512x512 8192x8192 32768x32768">
  <link rel=icon href=iphone.png sizes="57x57" type="image/png">
  <link rel=icon href=gnome.svg sizes="any" type="image/svg+xml">
  <link rel=stylesheet href=lsforums.css>
  <script src=lsforums.js></script>
  <meta name=application-name content="lsForums">
 </head>
 <body>
  ...

역사적 이유로, icon 키워드는 "shortcut" 키워드 앞에 있을 수 있습니다. "shortcut" 키워드가 있는 경우, rel 속성의 전체 값은 "shortcut icon" 문자열에 대해 ASCII 대소문자 구분 없이 일치해야 합니다(토큰 사이에 U+0020 공백 문자 하나와 다른 ASCII 공백이 없어야 합니다).

license 키워드는 link, a, areaform 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 만듭니다.

license 키워드는 참조된 문서가 현재 문서의 주요 콘텐츠가 제공되는 저작권 라이선스 조건을 제공함을 나타냅니다.

이 사양은 문서의 주요 콘텐츠와 주요 콘텐츠로 간주되지 않는 콘텐츠를 구분하는 방법을 지정하지 않습니다. 구분은 사용자에게 명확해야 합니다.

사진 공유 사이트를 고려해 보십시오. 해당 사이트의 페이지는 사진을 설명하고 표시할 수 있으며, 페이지는 다음과 같이 마크업될 수 있습니다:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Exampl Pictures: Kissat</title>
  <link rel="stylesheet" href="/style/default">
 </head>
 <body>
  <h1>Kissat</h1>
  <nav>
   <a href="../">Return to photo index</a>
  </nav>
  <figure>
   <img src="/pix/39627052_fd8dcd98b5.jpg">
   <figcaption>Kissat</figcaption>
  </figure>
  <p>One of them has six toes!</p>
  <p><small><a rel="license" href="http://www.opensource.org/licenses/mit-license.php">MIT Licensed</a></small></p>
  <footer>
   <a href="/">Home</a> | <a href="../">Photo index</a>
   <p><small>© copyright 2009 Exampl Pictures. All Rights Reserved.</small></p>
  </footer>
 </body>
</html>

이 경우 license는 문서의 주요 콘텐츠인 사진에만 적용되며, 문서 전체에는 적용되지 않습니다. 특히 문서 하단에 명시된 저작권이 적용되는 페이지 디자인에는 적용되지 않습니다. 이 점은 스타일링을 통해 더 명확하게 할 수 있습니다(예: 라이선스 링크를 사진 근처에 눈에 띄게 배치하고, 페이지 저작권은 페이지 하단에 작은 글씨로 표시).

동의어: 역사적 이유로, 사용자 에이전트는 "copyright" 키워드를 license 키워드처럼 처리해야 합니다.

Link_types/manifest

하나의 엔진에서만 지원됩니다.

Firefox?Safari?Chrome아니오
Opera?Edge아니오
Edge (Legacy)?Internet Explorer?
Firefox Android?Safari iOS?Chrome Android39+WebView Android?Samsung Internet?Opera Android?

manifest 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 만듭니다.

manifest 키워드는 현재 문서와 관련된 메타데이터를 제공하는 매니페스트 파일을 나타냅니다.

manifest 키워드로 제공되는 리소스에 대해 기본 유형이 없습니다.

웹 애플리케이션이 설치된 웹 애플리케이션이 아닌 경우, 이 링크 유형에 대해 링크된 리소스를 가져오고 처리하는 적절한 시기는 사용자 에이전트가 필요하다고 판단할 때입니다. 예를 들어, 사용자가 웹 애플리케이션을 설치하기로 선택했을 때가 적절한 시기가 될 수 있습니다.

설치된 웹 애플리케이션의 경우, 이 링크 유형에 대해 링크된 리소스를 가져오고 처리하는 적절한 시기는 다음과 같습니다:

어떤 경우든, 트리 순서(tree order)에서 rel 속성이 manifest 토큰을 포함하는 첫 번째 link 요소만 사용할 수 있습니다.

사용자 에이전트는 이 링크 유형에 대해 로드 이벤트를 지연시켜서는 안 됩니다.

이 유형의 링크된 리소스에 대해 link 요소 el요청 request를 고려하여 링크된 리소스 가져오기 설정 단계는 다음과 같습니다:

  1. el노드 문서노드 내비게이벌navigable로 설정합니다.

  2. navigable이 null이면 false를 반환합니다.

  3. navigable최상위 탐색 가능이 아니면 false를 반환합니다.

  4. requestinitiator를 "manifest"로 설정합니다.

  5. requestdestination을 "manifest"로 설정합니다.

  6. requestmode를 "cors"로 설정합니다.

  7. requestcredentials modecrossorigin 콘텐츠 속성에 대한 CORS 설정 속성 자격 증명 모드로 설정합니다.

  8. true를 반환합니다.

link 요소 el, boolean success, 응답 response, 및 바이트 시퀀스 bodyBytes를 고려하여 이 유형의 링크된 리소스를 처리하는 방법은 다음과 같습니다:

  1. responseContent-Type 메타데이터JSON MIME 타입이 아닌 경우, success를 false로 설정합니다.

  2. success가 true인 경우:

    1. el노드 문서URLdocument URL로 설정합니다.

    2. responseURLmanifest URL로 설정합니다.

    3. document URL, manifest URL, 및 bodyBytes를 고려하여 매니페스트를 처리합니다. [MANIFEST]

이 유형의 링크된 리소스에 대한 링크 헤더 처리 단계는 아무 작업도 하지 않습니다.

Link_types/modulepreload

Firefox115+Safari?Chrome66+
Opera?Edge79+
Edge (Legacy)아니오Internet Explorer?
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

modulepreload 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 만듭니다. 이 키워드는 body-ok입니다.

modulepreload 키워드는 preload 키워드의 특수화된 대안으로, 모듈 스크립트의 사전 로드에 초점을 맞춘 처리 모델을 사용합니다. 특히, 모듈 스크립트의 특정한 가져오기 동작을 사용하며 (예: crossorigin 속성의 다른 해석 등), 결과를 나중에 평가하기 위해 적절한 모듈 맵에 저장합니다. 반면, preload 키워드를 사용하는 유사한 외부 리소스 링크는 결과를 프리로드 캐시에 저장하며, 문서의 모듈 맵에는 영향을 미치지 않습니다.

또한, 구현체는 모듈 스크립트가 의존성을 선언한다는 사실을 활용하여 지정된 모듈의 의존성을 가져올 수도 있습니다. 이는 최적화 기회로 의도된 것으로, 사용자 에이전트는 그 의존성이 나중에 필요할 가능성이 높다는 것을 알고 있기 때문입니다. 일반적으로는 서비스 워커 같은 기술을 사용하지 않는 한 이를 관찰하기는 어렵습니다. 특히, 적절한 load 또는 error 이벤트는 지정된 모듈이 가져와진 후에 발생하며, 의존성을 기다리지 않습니다.

사용자 에이전트는 이 링크 유형에 대해 로드 이벤트를 지연해서는 안 됩니다.

이 링크 유형에 대해 링크된 리소스를 가져오고 처리하기에 적절한 시기는 다음과 같습니다:

일부 다른 링크 관계와 달리, link 요소의 관련 속성 (예: as, crossorigin, referrerpolicy)을 변경해도 새로운 가져오기를 트리거하지 않습니다. 이는 문서의 모듈 맵이 이미 이전에 가져온 결과로 채워져 있으므로, 다시 가져오는 것이 의미가 없기 때문입니다.

modulepreload 링크에 대한 리소스 가져오기 및 처리 알고리즘은 link 요소 el을 기준으로 다음과 같이 진행됩니다:

  1. 만약 elhref 속성의 값이 빈 문자열이라면, 반환합니다.

  2. elas 속성의 현재 상태를 destination으로 설정합니다 (이는 destination입니다), 또는 상태가 없다면 "script"로 설정합니다.

  3. 만약 destination스크립트와 유사한 목적지가 아니라면, 요소 작업을 대기열에 추가하고 네트워킹 작업 소스를 사용하여 el에서 이벤트를 발생시켜 error를 반환합니다.

  4. elhref 속성의 값을 기준으로 URL 인코딩-파싱의 결과를 url로 설정합니다.

  5. url이 실패인 경우, 반환합니다.

  6. el노드 문서관련 설정 객체settings object로 설정합니다.

  7. elcrossorigin 속성에 대한 CORS 설정 속성 자격 증명 모드credentials mode로 설정합니다.

  8. el[[CryptographicNonce]]cryptographic nonce로 설정합니다.

  9. 속성이 지정된 경우 el무결성 속성 값을 integrity metadata로 설정하고, 그렇지 않은 경우 빈 문자열로 설정합니다.

  10. el무결성 속성을 가지고 있지 않다면, 모듈 무결성 메타데이터를 해결한 결과를 urlsettings object로 설정하여 integrity metadata를 설정합니다.

  11. elreferrerpolicy 속성의 현재 상태를 referrer policy로 설정합니다.

  12. elfetchpriority 속성의 현재 상태를 fetch priority로 설정합니다.

  13. 스크립트 가져오기 옵션cryptographic nonce, integrity metadata, "not-parser-inserted"의 파서 메타데이터, credentials mode, referrer policy, 및 fetch priority로 설정합니다.

  14. url, destination, settings object, options을 기준으로 modulepreload 모듈 스크립트 그래프 가져오기를 실행하고, result를 기준으로 다음 단계를 수행합니다:

    1. result가 null인 경우, 이벤트를 발생시켜 el에서 error를 반환합니다.

    2. 이벤트를 발생시켜 el에서 load를 반환합니다.

이 유형의 링크된 리소스에 대한 링크 헤더 처리 단계는 아무 작업도 하지 않습니다.

다음 스니펫은 여러 모듈이 사전 로드된 애플리케이션의 상단 부분을 보여줍니다:

<!DOCTYPE html>
<html lang="en">
<title>IRCFog</title>

<link rel="modulepreload" href="app.mjs">
<link rel="modulepreload" href="helpers.mjs">
<link rel="modulepreload" href="irc.mjs">
<link rel="modulepreload" href="fog-machine.mjs">

<script type="module" src="app.mjs">
...

애플리케이션의 모듈 그래프가 다음과 같다고 가정합니다:

모듈 그래프는 app.mjs에서 시작되며, irc.mjs와 fog-machine.mjs에 의존합니다. irc.mjs는 helpers.mjs에 의존합니다.

여기에서 애플리케이션 개발자는 모듈 그래프의 모든 모듈을 선언하기 위해 modulepreload를 사용하여 사용자 에이전트가 이를 모두 가져오도록 합니다. 이러한 사전 로드 없이, 사용자 에이전트는 HTTP/2 서버 푸시 같은 기술이 작동하지 않는 경우 helpers.mjs를 찾기 위해 여러 네트워크 라운드 트립을 거쳐야 할 수도 있습니다. 이와 같이, modulepreload link 요소는 애플리케이션의 모듈을 일종의 "매니페스트"처럼 사용할 수 있습니다.

다음 코드는 modulepreload 링크가 import()와 함께 사용되어 네트워크 가져오기를 미리 수행하도록 하고, import()가 호출될 때 모듈이 이미 준비되어 모듈 맵에서 준비된 상태에 있게 하는 방법을 보여줍니다:

<link rel="modulepreload" href="awesome-viewer.mjs">

<button onclick="import('./awesome-viewer.mjs').then(m => m.view())">
  멋진 항목 보기
</button>

nofollow 키워드는 a, areaform 요소와 함께 사용될 수 있습니다. 이 키워드는 하이퍼링크를 생성하지 않지만, 요소에 의해 생성된 다른 하이퍼링크들(다른 키워드가 생성하지 않는 경우 암시적인 하이퍼링크)을 주석으로 달 수 있습니다.

nofollow 키워드는 링크가 페이지의 원래 작성자 또는 발행자에 의해 승인되지 않았거나, 두 페이지에 관련된 사람들 간의 상업적 관계 때문에 주로 포함된 링크임을 나타냅니다.

Link_types/noopener

모든 현재 엔진에서 지원됩니다.

Firefox52+Safari10.1+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Link_types/noopener

모든 현재 엔진에서 지원됩니다.

Firefox52+Safari10.1+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

noopener 키워드는 a, areaform 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성하지 않지만, 요소가 생성하는 하이퍼링크(다른 키워드가 하이퍼링크를 생성하지 않는 경우 내포된 하이퍼링크)를 주석 처리합니다.

이 키워드는 하이퍼링크를 따라 열리는 새 최상위 탐색 가능 항목보조 브라우징 컨텍스트를 포함하지 않음을 나타냅니다. 예를 들어, 생성된 Windowopener 속성의 getter는 null을 반환합니다.

또한 처리 모델도 참조하십시오.

이것은 일반적으로 최상위 탐색 가능 항목보조 브라우징 컨텍스트(기존 탐색 가능 항목대상 이름이 "example"이 아닌 경우)와 함께 생성됩니다:

<a href=help.html target=example>Help!</a>

이것은 동일한 경우에 최상위 탐색 가능 항목과 비보조 브라우징 컨텍스트와 함께 생성됩니다:

<a href=help.html target=example rel=noopener>Help!</a>

이들은 동등하며 오직 부모 탐색 가능 항목만 탐색합니다:

<a href=index.html target=_parent>Home</a>
<a href=index.html target=_parent rel=noopener>Home</a>

Link_types/noreferrer

모든 현재 엔진에서 지원됩니다.

Firefox33+Safari5+Chrome16+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer🔰 11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet1.5+Opera Android?

Link_types/noreferrer

모든 현재 엔진에서 지원됩니다.

Firefox33+Safari5+Chrome16+
Opera?Edge79+
Edge (Legacy)13+🔰 11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet1.5+Opera Android?

noreferrer 키워드는 a, areaform 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성하지 않지만, 요소가 생성하는 하이퍼링크(다른 키워드가 하이퍼링크를 생성하지 않는 경우 내포된 하이퍼링크)를 주석 처리합니다.

이 키워드는 링크를 따를 때 참조자 정보가 유출되지 않음을 나타내며, 또한 동일한 조건에서 noopener 키워드의 동작을 의미합니다.

참조자가 직접 조작되는 처리 모델도 참조하십시오.

<a href="..." rel="noreferrer" target="_blank"><a href="..." rel="noreferrer noopener" target="_blank">와 동일한 동작을 합니다.

opener 키워드는 a, areaform 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성하지 않지만, 요소가 생성하는 다른 모든 하이퍼링크(다른 키워드가 하이퍼링크를 생성하지 않는 경우 내포된 하이퍼링크)를 주석 처리합니다.

이 키워드는 하이퍼링크를 따를 때 생성된 모든 새로운 최상위 탐색 가능 객체보조 브라우징 컨텍스트를 포함하게 됨을 나타냅니다.

처리 모델에 대해서는 처리 모델을 참조하십시오.

다음 예제에서는 사용자가 찾고 있는 내용이 다른 곳에서 발견될 수 있는 경우를 대비하여 도움말 페이지 팝업이 그 오프너를 탐색할 수 있도록 opener가 사용됩니다. 대안으로는 _blank 대신 이름이 지정된 대상을 사용하는 방법이 있을 수 있지만, 이는 기존 이름과 충돌할 가능성이 있습니다.

<a href="..." rel=opener target=_blank>Help!</a>

pingback 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 생성합니다. 이 키워드는 본문-허용입니다.

pingback 키워드의 의미는 Pingback 1.0를 참조하십시오. [PINGBACK]

Link_types/preconnect

모든 현재 엔진에서 지원됩니다.

Firefox39+Safari11.1+Chrome46+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet4.0+Opera Android?

preconnect 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 생성합니다. 이 키워드는 본문-허용입니다.

preconnect 키워드는 특정 리소스의 출처로의 연결을 선제적으로 시작하는 것이 유익할 가능성이 높으며, 사용자가 해당 출처에 있는 리소스를 필요로 할 가능성이 높기 때문에 연결을 설정하는 데 관련된 지연 시간을 미리 해결함으로써 사용자 경험이 향상될 것임을 나타냅니다.

preconnect 키워드로 제공되는 리소스에는 기본 유형이 없습니다.

사용자 에이전트는 이 링크 유형에 대해 로드 이벤트를 지연해서는 안 됩니다.

이 링크 유형에 대해 링크된 리소스를 가져오고 처리할 적절한 시점은 다음과 같습니다:

이 링크 유형에 대해 링크된 리소스를 가져오고 처리하는 단계는 link 요소 el을 사용하여 링크 옵션을 생성하고 해당 결과를 사용하여 preconnect하는 것입니다.

이 링크 유형에 대해 링크 헤더를 처리하는 단계는 링크 처리 옵션 options를 사용하여 preconnect하는 것입니다.

Preconnect 하기 위해 링크 처리 옵션 options를 주어진 경우:

  1. 만약 optionshref가 빈 문자열이면, 반환합니다.

  2. 상대적으로 optionshref를 기준으로 URL을 인코딩-파싱한 결과를 url로 둡니다.

    문서나 환경 대신 기본 URL을 전달하는 문제는 이슈 #9715에 의해 추적됩니다.

  3. 만약 url이 실패라면, 반환합니다.

  4. 만약 url스킴HTTP(S) 스킴이 아니라면, 반환합니다.

  5. options환경을 기준으로 네트워크 파티션 키를 결정한 결과를 partitionKey로 둡니다.

  6. useCredentials를 true로 둡니다.

  7. 만약 optionscrossorigin익명이고 options출처url출처와 동일하지 않다면, useCredentials를 false로 설정합니다.

  8. 사용자 에이전트는 partitionKey, url출처useCredentials를 기준으로 연결을 확보해야 합니다.

    이 연결은 직접적으로 사용되지 않으며, 이후 사용을 위해 연결 풀에 남아 있습니다.

    사용자 에이전트는 가능한 한 선제적으로 preconnect를 시작하고 전체 연결 핸드셰이크(DNS+TCP, HTTPS 출처의 경우 DNS+TCP+TLS)를 수행하려고 해야 합니다. 하지만 자원 제약이나 기타 이유로 인해 부분 핸드셰이크(DNS만, HTTPS 출처의 경우 DNS 또는 DNS+TCP)만 수행하거나 완전히 건너뛸 수 있습니다.

    출처별 최적의 연결 수는 협상된 프로토콜, 사용자의 현재 연결 상태, 사용 가능한 장치 자원, 전역 연결 제한 및 기타 상황에 따라 다릅니다. 따라서 몇 개의 연결을 열어야 할지는 사용자 에이전트에 의해 결정됩니다.

Link_types/prefetch

Firefox2+SafariNoChrome8+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet1.5+Opera Android?

prefetch 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 생성합니다. 이 키워드는 본문-허용입니다.

prefetch 키워드는 지정된 리소스나 동일 사이트 문서를 선제적으로 가져오고 캐시하는 것이 유익할 가능성이 높음을 나타내며, 사용자가 향후 탐색을 위해 이 리소스를 필요로 할 가능성이 높습니다.

prefetch 키워드로 제공되는 리소스에는 기본 유형이 없습니다.

이 링크 유형에 대해 링크된 리소스를 가져오고 처리할 적절한 시점은 다음과 같습니다:

prefetch 링크에 대해 link 요소 el을 사용하여 링크된 리소스를 가져오고 처리하는 알고리즘은 다음과 같습니다:

  1. 만약 elhref 속성 값이 빈 문자열이라면, 반환합니다.

  2. el에서 링크 옵션을 생성한 결과를 options로 둡니다.

  3. options목적지를 빈 문자열로 설정합니다.

  4. options을 기준으로 링크 요청을 생성한 결과를 request로 둡니다.

  5. 만약 request가 null이라면, 반환합니다.

  6. requestinitiator를 "prefetch"로 설정합니다.

  7. 다음 단계에 따라 응답 response와 null, 실패 또는 바이트 시퀀스 bytesOrNull을 지정하여 processPrefetchResponse를 설정합니다:

    1. 만약 response네트워크 오류라면, 이벤트를 발생시켜 el에서 error를 처리합니다.

    2. 그렇지 않으면, 이벤트를 발생시켜 el에서 load를 처리합니다.

  8. 사용자 에이전트는 request를 가져오고, processResponseConsumeBodyprocessPrefetchResponse로 설정합니다. 사용자 에이전트는 현재 문서에 필요한 다른 요청을 우선시하기 위해 request의 가져오기를 지연시킬 수 있습니다.

이 유형의 링크된 리소스에 대해 링크 헤더를 처리하는 단계는 아무 작업도 수행하지 않습니다.

Link_types/preload

한 개의 엔진에서만 지원됩니다.

Firefox85+Safari?Chrome🔰50+
Opera37+Edge🔰79+
Edge (레거시)아니오Internet Explorer?
Firefox Android?Safari iOS?Chrome Android?WebView Android50+Samsung Internet5.0+Opera Android?

preload 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 외부 리소스 링크를 생성합니다. 이 키워드는 body-ok입니다.

preload 키워드는 사용자 에이전트가 사전 fetch하고 캐시된 리소스를 잠재적인 목적지에 따라 캐시할 것을 나타냅니다. 이 목적지는 as 속성과 우선순위에 따라 지정됩니다. 사용자 에이전트는 현재 탐색에 이 리소스가 필요할 가능성이 높습니다.

사용자 에이전트는 리소스를 로드할 때 이미지의 사전 디코딩 또는 스타일시트 생성과 같은 추가 작업을 수행할 수 있습니다. 그러나 이러한 추가 작업은 관찰 가능한 영향을 미치지 않습니다.

preload 키워드에 의해 지정된 리소스에는 기본 유형이 없습니다.

사용자 에이전트는 이 링크 유형에 대해 로드 이벤트를 지연시켜서는 안 됩니다.

이 링크와 관련된 리소스를 fetch 및 처리할 적절한 시점은 다음과 같습니다:

Document에는 사전 로드된 리소스의 맵이 있습니다. 이 맵은 처음에는 비어 있는 순서가 있는 맵입니다.

사전 로드 키구조체입니다. 이 구조체에는 다음과 같은 항목이 포함됩니다:

URL
URL
목적지
문자열
모드
요청 모드, "same-origin", "cors" 또는 "no-cors" 중 하나
자격 증명 모드
자격 증명 모드

사전 로드 항목구조체입니다. 이 구조체에는 다음과 같은 항목이 포함됩니다:

무결성 메타데이터
문자열
응답
널 또는 응답
응답 사용 가능 시
널 또는 응답 또는 널을 허용하는 알고리즘

사전 로드된 리소스 소비Window window에 대해 수행하고, URL url, 문자열 destination, 문자열 mode, 문자열 credentialsMode, 문자열 integrityMetadataonResponseAvailable을 제공합니다. 이때 응답을 받아들이는 알고리즘이 사용됩니다:

  1. key사전 로드 키로 설정합니다. 이 키의 URLurl, 목적지destination, 모드mode, 자격 증명 모드credentialsMode입니다.

  2. preloadswindow관련된 Document사전 로드된 리소스의 맵으로 설정합니다.

  3. keypreloads존재하지 않으면 false를 반환합니다.

  4. entrypreloads[key]으로 설정합니다.

  5. consumerIntegrityMetadataintegrityMetadata구문 분석한 결과로 설정합니다.

  6. preloadIntegrityMetadataentry무결성 메타데이터구문 분석한 결과로 설정합니다.

  7. 다음 조건 중 하나도 적용되지 않으면:

    false를 반환합니다.

    사전 로드와 소비자 간의 무결성 메타데이터 불일치, 설령 데이터가 일치하더라도 추가 네트워크 요청을 초래할 수 있습니다.

    사전 로드 요청이 오류로 인해 실패하는 경우, 잘못된 응답이 나중에 네트워크에서 다시 요청되지 않도록 사전 로드 캐시에 네트워크 오류를 추가하는 것이 중요합니다. 이는 보안 문제와도 관련이 있습니다. 예를 들어, 개발자가 사전 로드 요청에 대해 하위 리소스 무결성 메타데이터를 지정했지만 이후 리소스 요청에서는 이를 지정하지 않은 경우를 고려해보십시오. 사전 로드 요청이 하위 리소스 무결성 검증에서 실패하고 버려지면, 리소스 요청은 네트워크에서 잠재적으로 악의적인 응답을 가져와 무결성 검증 없이 이를 소비할 수 있습니다. [SRI]를 참조하십시오.

  8. preloads[key]을 제거합니다.

  9. entry응답이 null이면, entry응답 사용 가능 시onResponseAvailable로 설정합니다.

  10. 그렇지 않으면, entry응답으로 onResponseAvailable을 호출합니다.

  11. true를 반환합니다.

이 섹션의 목적을 위해 문자열 type이 문자열 destination일치하는지 여부를 다음 알고리즘을 통해 확인할 수 있습니다:

  1. 만약 type이 빈 문자열이라면, true를 반환합니다.

  2. 만약 destination이 "fetch"라면, true를 반환합니다.

  3. mimeTypeRecord구문 분석한 결과로 설정합니다.

  4. mimeTypeRecord가 실패로 설정되면, false를 반환합니다.

  5. mimeTypeRecord가 사용자 에이전트에서 지원되지 않으면, false를 반환합니다.

  6. 다음 중 하나가 true인 경우:

    그러면 true를 반환합니다.

  7. false를 반환합니다.

사전 로드 키 생성요청 request에 대해 수행하고, 새 사전 로드 키를 반환합니다. 이 키의 URLrequestURL, 목적지request목적지, 모드request모드, 자격 증명 모드request자격 증명 모드입니다.

사전 로드 목적지 변환을 문자열 destination을 주어진 상태에서 수행합니다:

  1. destination이 "fetch", "font", "image", "script", "style", 또는 "track"가 아니면 null을 반환합니다.

  2. destination변환한 결과를 반환합니다.

사전 로드링크 처리 옵션 options응답을 허용하는 선택적 processResponse와 함께 수행합니다:

  1. options유형options유형과 일치하지 않으면, 리턴합니다.

  2. options목적지가 "image"이며, options소스 세트가 null이 아닌 경우, optionshref소스 세트에서 이미지 소스를 선택하는 것의 결과로 설정합니다.

  3. request링크 요청 생성의 결과로 설정합니다.

  4. request가 null이면 리턴합니다.

  5. unsafeEndTime을 0으로 설정합니다.

  6. entry를 새 사전 로드 항목으로 설정합니다. 이 항목의 무결성 메타데이터options무결성입니다.

  7. key사전 로드 키 생성의 결과로 설정합니다.

  8. options문서가 "pending"이면, requestinitiator 유형을 "early hint"로 설정합니다.

  9. controller를 null로 설정합니다.

  10. reportTiming타이밍을 보고하기로 설정합니다. 이때 controllerdocument관련된 전역 객체를 기준으로 합니다.

  11. controller요청을 fetch한 결과로 설정합니다. processResponseConsumeBody응답 response 및 null, 실패 또는 바이트 시퀀스 bodyBytes를 받아들이는 알고리즘으로 설정합니다:

    1. bodyBytes바이트 시퀀스인 경우, response바디바디로 설정합니다.

      processResponseConsumeBody를 사용하여 전체 바디를 추출했습니다. 이는 사전 로더가 네트워크에서 전체 바디를 로드하도록 보장하는 데 필요합니다. 사전 로드가 소비될지 여부는 이 시점에서 불확실합니다. 그런 다음, 우리는 이미 한 번 이를 수행했음에도 불구하고, 요청의 바디를 동일한 바이트를 포함하는 새 바디로 재설정하여 다른 명세가 실제 소비 시점에 이를 읽을 수 있도록 합니다.

    2. 그렇지 않으면, response네트워크 오류로 설정합니다.

    3. unsafeEndTimeunsafe shared current time으로 설정합니다.

    4. options문서가 null이 아니면, options문서를 주어진 상태로 reportTiming을 호출합니다.

    5. entry응답 사용 가능 시가 null이면, entry응답response로 설정합니다. 그렇지 않으면, entry응답 사용 가능 시를 주어진 상태로 response로 호출합니다.

    6. processResponse가 주어진 경우, response와 함께 processResponse를 호출합니다.

  12. commitDocument document에 주어진 상태로 다음 단계로 설정합니다:

    1. entry응답이 null이 아니면, document를 주어진 상태로 reportTiming을 호출합니다.

    2. document사전 로드된 리소스의 맵[key]을 entry로 설정합니다.

  13. options문서가 null이면, options문서 준비 시commit으로 설정합니다. 그렇지 않으면, options문서와 함께 commit을 호출합니다.

연결된 리소스를 fetch하고 처리하는 단계는, 주어진 link 요소 el에 대해 수행됩니다:

  1. 소스 세트 업데이트el에 대해 수행합니다.

  2. options요소에서 링크 옵션 생성의 결과로 설정합니다.

  3. 사전 로드options에 대해 수행합니다. 이때, 주어진 응답 response와 함께 다음 단계로 수행됩니다:

    1. response네트워크 오류인 경우, 이벤트 발생el에 대해 수행합니다. 그렇지 않으면, 이벤트 발생el에 대해 수행합니다.

      실제 브라우저의 동작은 이 사양과 다르며, 동작을 변경할 수 있는지 여부는 아직 조사되지 않았습니다. 문제 #1142를 참조하십시오.

링크 헤더를 처리하는 단계는, 주어진 링크 처리 옵션 options에 대해 사전 로드를 수행하는 것입니다.

privacy-policy 키워드는 link, a, 그리고 area 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 만듭니다.

privacy-policy 키워드는 참조된 문서가 현재 문서에 적용되는 데이터 수집 및 사용 관행에 대한 정보를 포함하고 있음을 나타냅니다. 자세한 내용은 추가 링크 관계 유형에서 설명되어 있습니다. 참조된 문서는 독립적인 개인정보 보호 정책이거나, 보다 일반적인 문서의 특정 섹션일 수 있습니다. [RFC6903]

search 키워드는 link, a, area, 그리고 form 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 만듭니다.

search 키워드는 참조된 문서가 문서 및 관련 리소스를 검색하기 위한 인터페이스를 제공함을 나타냅니다.

OpenSearch 설명 문서는 link 요소와 search 링크 유형과 함께 사용하여 사용자 에이전트가 검색 인터페이스를 자동으로 검색할 수 있도록 할 수 있습니다. [OPENSEARCH]

stylesheet 키워드는 link 요소와 함께 사용할 수 있습니다. 이 키워드는 스타일링 처리 모델에 기여하는 외부 리소스 링크를 만듭니다. 이 키워드는 body-ok입니다.

지정된 리소스는 문서의 표현 방법을 설명하는 CSS 스타일 시트입니다.

대체 스타일 시트

하나의 엔진에서만 지원됨.

Firefox3+Safari?Chrome1–48
OperaYesEdgeNo
Edge (Legacy)?Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 대체 키워드가 또한 link 요소에 지정된 경우, 해당 링크는 대체 스타일 시트입니다; 이 경우, title 속성이 link 요소에 비어 있지 않은 값으로 지정되어야 합니다.

stylesheet 키워드에 의해 제공된 리소스의 기본 유형은 text/css입니다.

이 유형의 link 요소는 해당 요소가 노드 문서의 파서에 의해 생성된 경우, 암묵적으로 잠재적으로 렌더링 차단될 수 있습니다.

키워드 비활성화가 있는 link 요소의 stylesheet 키워드가 설정되면, CSS 스타일 시트를 비활성화합니다.

이 유형의 링크를 가져오고 처리하는 적절한 시간은 다음과 같습니다:

특이 사항: 문서가 퀴크 모드로 설정되어 있으며, 외부 리소스의 동일 출처URL이 동일하고, 외부 리소스의 콘텐츠 유형 메타데이터가 지원되는 스타일 시트 유형이 아닌 경우, 사용자 에이전트는 대신 이를 text/css로 가정해야 합니다.

이 유형의 링크된 리소스에 대해 링크된 리소스 가져오기 설정 단계link 요소 el요청 request가 주어진 경우 다음과 같습니다:

  1. 만약 el비활성화 속성이 설정되어 있으면, false를 반환합니다.

  2. 만약 el스크립트 차단 스타일 시트에 기여하는 경우, el 노드 문서스크립트 차단 스타일 시트 세트에 추가합니다.

  3. 만약 el미디어 속성의 값이 환경과 일치하며, el잠재적으로 렌더링을 차단할 수 있는 경우, 렌더링을 차단합니다.

  4. 만약 el이 현재 렌더링 차단 중인 경우, request렌더링 차단을 true로 설정합니다.

  5. true를 반환합니다.

이슈 #968에서는 CSSOM CSS 스타일 시트 가져오기 알고리즘을 사용하여 기본 가져오기 및 처리 알고리즘을 대체할 계획을 설명합니다. 이와 동시에, 중요한 하위 리소스 요청link 요소가 현재 렌더링 차단 중인지 여부에 따라 렌더링 차단으로 설정되어야 합니다.

이 유형의 링크된 리소스를 처리하려면, link 요소 el, boolean success, 응답 response, 그리고 바이트 시퀀스 bodyBytes가 주어집니다.

  1. 리소스의 콘텐츠 유형 메타데이터text/css가 아닌 경우, success를 false로 설정합니다.

  2. 만약 el이 더 이상 스타일링 처리 모델에 기여하는 외부 리소스 링크를 생성하지 않거나, 해당 리소스를 가져온 이후에 해당 리소스를 다시 가져오는 것이 적절해진 경우, 다음 단계를 수행합니다:

    1. 제거 elel노드 문서스크립트 차단 스타일 시트 세트에서 제거합니다.

    2. 반환합니다.

  3. 만약 el연관된 CSS 스타일 시트를 가지고 있다면, CSS 스타일 시트를 제거합니다.

  4. 만약 success가 true인 경우, 다음 단계를 수행합니다:

    1. CSS 스타일 시트를 생성합니다, 다음 속성으로:

      유형

      text/css

      위치

      responseURL 목록[0]

      우리는 w3c/csswg-drafts 이슈 #9316이 해결될 것이라는 가정 하에 URL을 제공합니다.

      소유자 노드

      el

      미디어

      el미디어 속성.

      이것은 현재 속성의 값이 아니라, (이 시점에 있을 수도 있는) 속성에 대한 참조입니다. CSSOM은 속성이 동적으로 설정, 변경 또는 제거될 때 발생하는 일을 정의합니다.

      제목

      el문서 트리 안에 있는 경우에는 eltitle 속성. 그렇지 않으면 빈 문자열.

      이것도 역시 속성의 현재 값이 아닌 속성에 대한 참조입니다.

      대체 플래그

      설정된 경우 링크는 대체 스타일 시트입니다el명시적으로 활성화됨이 false인 경우; 그렇지 않으면 설정되지 않음.

      원본 클린 플래그

      리소스가 CORS-동일 출처인 경우 설정됨; 그렇지 않으면 설정되지 않음.

      부모 CSS 스타일 시트
      소유 CSS 규칙

      null

      비활성화 플래그

      기본값으로 설정됨.

      CSS 규칙

      초기화되지 않음.

      이것은 옳지 않은 것 같습니다. 아마도 bodyBytes를 사용해야 할 것입니다? 이슈 #2997에서 추적됩니다.

      CSS 환경 인코딩은 다음 단계를 수행하여 실행된 결과입니다: [CSSSYNTAX]

      1. 만약 elcharset 속성이 있다면, 해당 속성 값에서 인코딩을 가져옵니다. 만약 성공하면, 해당 결과 인코딩을 반환합니다. [ENCODING]

      2. 그렇지 않으면 문서의 문자 인코딩을 반환합니다. [DOM]

    2. 이벤트를 발생합니다. 이름은 load이며 el에서 발생합니다.

  5. 그렇지 않으면, 이벤트를 발생시킵니다. 이름은 error이며 el에서 발생합니다.

  6. 만약 el스크립트 차단 스타일 시트에 기여하는 경우:

    1. 단언: el노드 문서스크립트 차단 스타일 시트 세트el포함되어 있습니다.

    2. 제거합니다. elel노드 문서스크립트 차단 스타일 시트 세트에서.

  7. 렌더링 차단 해제합니다. el에서.

이 유형의 링크된 리소스에 대한 링크 헤더 처리 단계는 아무 것도 하지 않는 것입니다.

tag 키워드는 aarea 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

tag 키워드는 참조된 문서가 표현하는 tag가 현재 문서에 적용됨을 나타냅니다.

태그가 현재 문서에 적용됨을 나타내기 때문에, 여러 페이지에 걸쳐 인기 태그를 나열하는 tag cloud의 마크업에서는 이 키워드를 사용하는 것이 부적절할 수 있습니다.

이 문서는 보석에 관한 것이므로 "https://en.wikipedia.org/wiki/Gemstone"와 같은 태그로 태그되어 있으며, 이는 이 문서가 미국의 도시들, 루비 패키지 형식, 또는 스위스 기관차 클래스가 아닌 "보석" 종류의 보석에 적용됨을 명확하게 분류합니다.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>My Precious</title>
 </head>
 <body>
  <header><h1>My precious</h1> <p>Summer 2012</p></header>
  <p>Recently I managed to dispose of a red gem that had been
  bothering me. I now have a much nicer blue sapphire.</p>
  <p>The red gem had been found in a bauxite stone while I was digging
  out the office level, but nobody was willing to haul it away. The
  same red gem stayed there for literally years.</p>
  <footer>
   Tags: <a rel=tag href="https://en.wikipedia.org/wiki/Gemstone">Gemstone</a>
  </footer>
 </body>
</html>

문서에는 두 개의 기사(articles)가 있습니다. 그러나 "tag" 링크는 페이지 전체에 적용됩니다 (기사 article 요소 안에 위치하더라도 동일하게 적용됩니다).

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Gem 4/4</title>
 </head>
 <body>
  <article>
   <h1>801: Steinbock</h1>
   <p>The number 801 Gem 4/4 electro-diesel has an ibex and was rebuilt in 2002.</p>
  </article>
  <article>
   <h1>802: Murmeltier</h1>
   <figure>
    <img src="https://upload.wikimedia.org/wikipedia/commons/b/b0/Trains_de_la_Bernina_en_hiver_2.jpg" alt="The 802 was red with pantographs and tall vents on the side.">
    <figcaption>The 802 in the 1980s, above Lago Bianco.</figcaption>
   </figure>
   <p>The number 802 Gem 4/4 electro-diesel has a marmot and was rebuilt in 2003.</p>
  </article>
  </p class="topic"><a rel=tag href="https://en.wikipedia.org/wiki/Rhaetian_Railway_Gem_4/4">Gem 4/4</a></p>
 </body>
</html>

terms-of-service 키워드는 link, a, 및 area 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

terms-of-service 키워드는 참조된 문서에 현재 문서의 제공자와 해당 문서를 사용하려는 사용자 간의 계약에 대한 정보가 포함되어 있음을 나타냅니다. 자세한 내용은 추가 링크 관계 유형에서 설명되어 있습니다. [RFC6903]

일부 문서는 문서 시퀀스의 일부를 형성합니다.

문서 시퀀스는 각 문서가 이전 형제 문서다음 형제 문서를 가질 수 있는 경우입니다. 이전 형제 문서가 없는 문서는 시퀀스의 시작이며, 다음 형제 문서가 없는 문서는 시퀀스의 끝입니다.

문서는 여러 시퀀스의 일부일 수 있습니다.

next 키워드는 link, a, area, 및 form 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

next 키워드는 문서가 시퀀스의 일부이며, 링크가 시퀀스에서 다음 논리적 문서로 연결된다는 것을 나타냅니다.

next 키워드가 link 요소와 함께 사용될 때, 사용자 에이전트는 이러한 링크를 dns-prefetch, preconnect, 또는 prefetch 키워드를 사용하는 것처럼 처리해야 합니다. 사용자 에이전트가 사용할 키워드는 구현에 따라 다릅니다. 예를 들어, 사용자 에이전트는 데이터, 배터리 전력, 또는 처리 능력을 절약하려고 할 때 비용이 적게 드는 preconnect 처리 모델을 사용하려고 하거나, 비슷한 상황에서 과거 사용자 행동에 대한 휴리스틱 분석에 따라 키워드를 선택할 수 있습니다.

prev 키워드는 link, a, area, 및 form 요소와 함께 사용할 수 있습니다. 이 키워드는 하이퍼링크를 생성합니다.

prev 키워드는 문서가 시퀀스의 일부이며, 링크가 시퀀스에서 이전 논리적 문서로 연결된다는 것을 나타냅니다.

동의어: 역사적인 이유로, 사용자 에이전트는 "previous" 키워드를 prev 키워드와 동일하게 처리해야 합니다.

사전 정의된 링크 유형 세트의 확장기존 rel 값에 대한 마이크로포맷 페이지에 등록될 수 있습니다. [MFREL]

누구나 언제든지 기존 rel 값에 대한 마이크로포맷 페이지를 편집하여 유형을 추가할 수 있습니다. 확장 유형은 다음 정보를 포함하여 지정해야 합니다:

키워드

정의된 실제 값. 값은 다른 정의된 값과 혼동되지 않도록 해야 합니다(예: 대소문자만 다른 경우).

값에 U+003A COLON 문자(:)가 포함된 경우, 절대 URL이어야 합니다. 절대 URL을 참조하십시오.

영향 ... link에 미치는 영향

다음 중 하나:

허용되지 않음
키워드는 link 요소에 지정되어서는 안 됩니다.
하이퍼링크
키워드는 link 요소에 지정될 수 있으며, 하이퍼링크를 생성합니다.
외부 리소스
키워드는 link 요소에 지정될 수 있으며, 외부 리소스 링크를 생성합니다.
영향 ... aarea에 미치는 영향

다음 중 하나:

허용되지 않음
키워드는 aarea 요소에 지정되어서는 안 됩니다.
하이퍼링크
키워드는 aarea 요소에 지정될 수 있으며, 하이퍼링크를 생성합니다.
외부 리소스
키워드는 aarea 요소에 지정될 수 있으며, 외부 리소스 링크를 생성합니다.
하이퍼링크 주석
키워드는 aarea 요소에 지정될 수 있으며, 해당 요소에 의해 생성된 다른 하이퍼링크주석으로 추가합니다.
영향 ... form에 미치는 영향

다음 중 하나:

허용되지 않음
키워드는 form 요소에 지정되어서는 안 됩니다.
하이퍼링크
키워드는 form 요소에 지정될 수 있으며, 하이퍼링크를 생성합니다.
외부 리소스
키워드는 form 요소에 지정될 수 있으며, 외부 리소스 링크를 생성합니다.
하이퍼링크 주석
키워드는 form 요소에 지정될 수 있으며, 해당 요소에 의해 생성된 다른 하이퍼링크주석으로 추가합니다.
간단한 설명

키워드의 의미를 비규범적으로 짧게 설명합니다.

명세서

키워드의 의미와 요구사항에 대한 자세한 설명을 링크합니다. 이는 위키의 다른 페이지일 수 있으며, 외부 페이지에 대한 링크일 수 있습니다.

동의어

처리 요구사항이 완전히 동일한 다른 키워드 값의 목록입니다. 작성자는 동의어로 정의된 값을 사용해서는 안 되며, 이는 레거시 콘텐츠 지원을 위해서만 사용됩니다. 실사용되지 않는 동의어는 누구나 제거할 수 있습니다. 레거시 콘텐츠와의 호환성을 위해 동의어로 처리해야 하는 값만 등록되어야 합니다.

상태

다음 중 하나:

제안됨
키워드는 광범위한 동료 검토 및 승인을 받지 않았습니다. 누군가가 제안했으며, 곧 사용하거나 현재 사용 중일 것입니다.
비준됨
키워드는 광범위한 동료 검토 및 승인을 받았습니다. 키워드를 사용하는 페이지를 처리하는 방법에 대한 명확한 정의가 포함된 명세서가 있습니다. 잘못된 방식으로 사용하는 경우도 포함됩니다.
중단됨
키워드는 광범위한 동료 검토를 받았으며, 부족하다고 판단되었습니다. 기존 페이지는 이 키워드를 사용하고 있지만, 새로운 페이지는 사용을 피해야 합니다. "간단한 설명" 및 "명세서" 항목에는 작성자가 대신 사용해야 할 내용을 설명합니다.

키워드가 기존 값과 중복되는 것으로 판단되면 제거하고 기존 값의 동의어로 나열해야 합니다.

키워드가 "제안됨" 상태로 한 달 이상 등록되었지만 사용되지 않거나 명세되지 않은 경우, 레지스트리에서 제거될 수 있습니다.

키워드가 "제안됨" 상태로 추가되었으며 기존 값과 중복되는 것으로 판단되면 제거하고 기존 값의 동의어로 나열해야 합니다. 키워드가 "제안됨" 상태로 추가되었으며 해롭다고 판단되면 "중단됨" 상태로 변경해야 합니다.

누구나 언제든지 상태를 변경할 수 있지만, 위에서 설명한 정의에 따라야 합니다.

적합성 검사 도구는 기존 rel 값에 대한 마이크로포맷 페이지에서 제공된 정보를 사용하여 값이 허용되는지 여부를 판단해야 합니다. 이 명세서에서 정의된 값 또는 "제안됨" 또는 "비준됨"으로 표시된 값은 "Effect on..." 필드에서 설명한 대로 적용할 수 있는 요소에서 사용될 때 수락되어야 하며, "중단됨"으로 표시되거나 이 명세서 또는 위의 페이지에 나열되지 않은 값은 유효하지 않은 것으로 거부되어야 합니다. 적합성 검사 도구는 성능 향상 또는 신뢰할 수 없는 네트워크 연결을 피하기 위해 이 정보를 캐시할 수 있습니다.

작성자가 이 명세서 또는 위키 페이지에서 정의되지 않은 새 유형을 사용하는 경우, 적합성 검사 도구는 위에서 설명한 세부 사항을 포함하여 값을 "제안됨" 상태로 위키에 추가하도록 제안해야 합니다.

"제안됨" 또는 "비준됨" 상태로 "기존 rel 값에 대한 마이크로포맷 페이지"에서 확장으로 정의된 유형은 "Effect on..." 필드에 따라 rel 속성을 사용하여 link, a, 및 area 요소와 함께 사용할 수 있습니다. [MFREL]

4.7 수정

insdel 요소는 문서에 대한 수정을 나타냅니다.

4.7.1 ins 요소

Element/ins

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
프레이징 콘텐츠.
감지 가능한 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
프레이징 콘텐츠가 예상되는 곳.
콘텐츠 모델:
투명.
text/html에서 태그 생략:
둘 다 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
cite — 인용문의 출처 또는 수정에 대한 추가 정보로 연결되는 링크
datetime — 변경의 날짜 및 (선택적) 시간
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLModElement를 사용합니다.

ins 요소는 문서에 대한 추가 사항을 나타냅니다.

다음은 단일 단락의 추가를 나타냅니다:

<aside>
<ins>
 <p> I like fruit. </p>
</ins>
</aside>

다음과 같이 aside 요소 안에 있는 모든 것이 프레이징 콘텐츠로 간주되므로 하나의 단락만 포함됩니다:

<aside>
<ins>
Apples are <em>tasty</em>.
</ins>
<ins>
So are pears.
</ins>
</aside>

ins 요소는 암시된 단락 경계를 넘어서는 안 됩니다.

다음 예는 두 개의 단락 추가를 나타내며, 두 번째 단락은 두 부분으로 삽입되었습니다. 이 예에서 첫 번째 ins 요소는 단락 경계를 넘기 때문에 좋지 않은 형식으로 간주됩니다.

<aside>
<!-- 이렇게 하지 마세요 -->
<ins datetime="2005-03-16 00:00Z">
 <p> I like fruit. </p>
 Apples are <em>tasty</em>.
</ins>
<ins datetime="2007-12-19 00:00Z">
 So are pears.
</ins>
</aside>

여기에서 더 나은 마크업 방식입니다. 더 많은 요소를 사용하지만, 요소가 암시된 단락 경계를 넘지 않습니다.

<aside>
<ins datetime="2005-03-16 00:00Z">
 <p> I like fruit. </p>
</ins>
<ins datetime="2005-03-16 00:00Z">
 Apples are <em>tasty</em>.
</ins>
<ins datetime="2007-12-19 00:00Z">
 So are pears.
</ins>
</aside>

4.7.2 del 요소

Element/del

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
프레이징 콘텐츠.
감지 가능한 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
프레이징 콘텐츠가 예상되는 곳.
콘텐츠 모델:
투명.
text/html에서 태그 생략:
둘 다 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
cite — 인용문의 출처 또는 수정에 대한 추가 정보로 연결되는 링크
datetime — 변경의 날짜 및 (선택적) 시간
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLModElement를 사용합니다.

del 요소는 문서에서 제거된 부분을 나타냅니다.

del 요소는 암시된 단락 경계를 넘어서는 안 됩니다.

다음은 완료된 항목들이 완료 시간과 함께 취소선으로 표시된 '할 일' 목록을 보여줍니다.

<h1>할 일</h1>
<ul>
<li>식기세척기 비우기</li>
<li><del datetime="2009-10-11T01:25-07:00">Walter Lewin의 강의 시청</del></li>
<li><del datetime="2009-10-10T23:38-07:00">더 많은 트랙 다운로드</del></li>
<li>프린터 구매</li>
</ul>

4.7.3 insdel 요소에 공통된 속성

cite 속성은 변경 사항을 설명하는 문서의 URL을 지정하는 데 사용할 수 있습니다. 예를 들어 회의록과 같은 긴 문서일 경우, 저자들은 변경 사항을 논의한 문서의 특정 부분을 가리키는 조각(fragment)을 포함하는 것이 권장됩니다.

cite 속성이 존재하는 경우, 이는 변경 사항을 설명하는 유효한 URL(주변에 공백이 있을 수 있음)이어야 합니다. 해당 속성의 값을 얻으려면, 속성의 값은 요소의 노드 문서에 상대적으로 구문 분석되어야 합니다. 사용자 에이전트는 사용자가 이러한 인용 링크를 따를 수 있도록 허용할 수 있지만, 주로 개인적인 용도(예: 사이트 수정 사항에 대한 통계를 수집하는 서버 측 스크립트 등)를 위한 것이지, 독자를 위한 것이 아닙니다.

datetime 속성은 변경의 날짜와 시간을 지정하는 데 사용할 수 있습니다.

존재하는 경우, datetime 속성의 값은 선택적으로 시간이 포함된 유효한 날짜 문자열이어야 합니다.

사용자 에이전트는 datetime 속성을 날짜 또는 시간 문자열을 구문 분석 알고리즘에 따라 구문 분석해야 합니다. 만약 이 알고리즘이 날짜 또는 전역 날짜와 시간을 반환하지 않으면, 해당 수정에는 관련된 타임스탬프가 없는 것으로 간주됩니다(값이 비표준적임; 유효한 날짜 문자열이 아님). 그렇지 않으면, 수정이 주어진 날짜 또는 전역 날짜와 시간에 이루어진 것으로 표시됩니다. 만약 주어진 값이 전역 날짜와 시간이라면, 사용자 에이전트는 주어진 datetime을 표시할 시간대를 결정하기 위해 관련된 시간대 오프셋 정보를 사용해야 합니다.

이 값은 사용자에게 표시될 수 있지만, 주로 개인적인 용도를 위한 것입니다.

insdel 요소는 HTMLModElement 인터페이스를 구현해야 합니다:

HTMLModElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface HTMLModElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString cite;
  [CEReactions] attribute DOMString dateTime;
};

cite IDL 속성은 요소의 cite 콘텐츠 속성을 반영해야 합니다. dateTime IDL 속성은 요소의 datetime 콘텐츠 속성을 반영해야 합니다.

4.7.4 수정과 단락

이 섹션은 비규범적입니다.

insdel 요소는 단락에 영향을 미치지 않으므로, p 요소 없이 암시된 단락이 있는 경우, ins 또는 del 요소가 전체 단락 또는 다른 프레이징 콘텐츠 요소와 다른 단락의 일부를 포함할 수 있습니다. 예를 들어:

<section>
<ins>
 <p>
  This is a paragraph that was inserted.
 </p>
 This is another paragraph whose first sentence was inserted
 at the same time as the paragraph above.
</ins>
This is a second sentence, which was there all along.
</section>

일부 단락만 p 요소로 감싸면, 동일한 ins 또는 del 요소로 첫 번째 단락의 끝, 전체 두 번째 단락, 세 번째 단락의 시작을 포함할 수도 있습니다(그러나 이는 매우 혼란스러우며, 좋은 관행으로 간주되지 않습니다):

<section>
This is the first paragraph. <ins>This sentence was inserted.
<p>This second paragraph was inserted.</p>
This sentence was inserted too.</ins> This is the
third paragraph in this example.
<!-- (이렇게 하지 마세요) -->
</section>

그러나 암시된 단락이 정의되는 방식 때문에, 동일한 ins 또는 del 요소를 사용하여 한 단락의 끝과 다음 단락의 시작을 동시에 표시하는 것은 불가능합니다. 대신에, p 요소 하나(또는 두 개)와 ins 또는 del 요소 두 개를 사용해야 합니다. 예를 들어:

<section>
<p>This is the first paragraph. <del>This sentence was deleted.</del></p>
<p><del>This sentence was deleted too.</del> That
sentence needed a separate &lt;del&gt; element.</p>
</section>

위에서 설명한 혼란스러움 때문에, 저자들은 모든 단락을 암시된 단락 경계를 넘지 않는 p 요소로 항상 마크업할 것을 강력히 권장합니다.

4.7.5 수정과 목록

이 섹션은 비규범적입니다.

olul 요소의 콘텐츠 모델은 insdel 요소를 자식 요소로 허용하지 않습니다. 목록은 삭제된 것으로 표시될 항목을 포함하여 모든 항목을 항상 나타냅니다.

항목이 삽입되었거나 삭제되었음을 나타내기 위해 ins 또는 del 요소를 li 요소의 내용 주위에 감쌀 수 있습니다. 항목이 다른 항목으로 교체되었음을 나타내기 위해 단일 li 요소에 하나 이상의 del 요소와 하나 이상의 ins 요소를 사용할 수 있습니다.

다음 예에서, 처음에는 비어 있던 목록에 시간이 지남에 따라 항목이 추가되고 제거되었습니다. 강조된 예제의 부분들은 목록의 '현재' 상태를 보여줍니다. 그러나 목록 항목 번호는 수정 사항을 고려하지 않습니다.

<h1>출하 정지 버그</h1>
<ol>
 <li><ins datetime="2008-02-12T15:20Z">버그 225: 눈이 올 때 우비 감지기가 작동하지 않음</ins></li>
 <li><del datetime="2008-03-01T20:22Z"><ins datetime="2008-02-14T12:02Z">버그 228: 4월에 물 버퍼 오버플로우 발생</ins></del></li>
 <li><ins datetime="2008-02-16T13:50Z">버그 230: 온수기가 재생 가능한 연료를 사용하지 않음</ins></li>
 <li><del datetime="2008-02-20T21:15Z"><ins datetime="2008-02-16T14:25Z">버그 232: 시동 후 이산화탄소 배출 감지됨</ins></del></li>
</ol>

다음 예에서, 처음에는 과일만 있던 목록이 색상만 있는 목록으로 교체되었습니다.

<h1>List of <del>fruits</del><ins>colors</ins></h1>
<ul>
 <li><del>Lime</del><ins>Green</ins></li>
 <li><del>Apple</del></li>
 <li>Orange</li>
 <li><del>Pear</del></li>
 <li><ins>Teal</ins></li>
 <li><del>Lemon</del><ins>Yellow</ins></li>
 <li>Olive</li>
 <li><ins>Purple</ins></li>
</ul>

4.7.6 수정과 표

이 섹션은 비규범적입니다.

표 모델의 일부를 구성하는 요소들은 복잡한 콘텐츠 모델 요구 사항을 가지고 있어 insdel 요소를 허용하지 않으므로 표에 대한 수정을 나타내는 것이 어려울 수 있습니다.

전체 행이나 열이 추가되거나 제거되었음을 나타내기 위해 해당 행이나 열의 각 셀의 내용을 ins 또는 del 요소로 감쌀 수 있습니다.

여기에서 표의 행이 추가되었습니다:

<table>
 <thead>
  <tr> <th> 게임 이름           <th> 게임 배급사   <th> 평가
 </thead>
 <tbody>
  <tr> <td> 디아블로 2            <td> 블리자드         <td> 8/10
  </tr> <td> 포탈              <td> 밸브            <td> 10/10
  <tr> <td> <ins>포탈 2</ins> <td> <ins>밸브</ins> <td> <ins>10/10</ins>
</tbody> 
</table>

여기에서 열이 제거되었습니다 (제거된 시간과 이유를 설명하는 페이지에 대한 링크도 포함되어 있습니다):

<table> 
 <thead> 
  <tr> <th> 게임 이름           <th> 게임 배급사   <th> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">평가</del> 
 </thead> 
 <tbody> 
  <tr> <td> 디아블로 2            <td> 블리자드         <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">8/10</del> 
  </tr> <td> 포탈              <td> 밸브            <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">10/10</del> 
  </tr> <td> 포탈 2            <td> 밸브            <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">10/10</del> 
</tbody> 
</table>

일반적으로 말해서, 더 복잡한 수정을 나타내는 좋은 방법은 없습니다 (예: 셀이 제거되고 모든 후속 셀이 위로 또는 왼쪽으로 이동하는 경우).

4.8 임베디드 콘텐츠

4.8.1 picture 요소

Element/picture

모든 최신 엔진에서 지원됩니다.

Firefox38+Safari9.1+Chrome38+
Opera?Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLPictureElement

모든 최신 엔진에서 지원됩니다.

Firefox38+Safari9.1+Chrome38+
Opera?Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
프레이징 콘텐츠.
임베디드 콘텐츠.
감지 가능한 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
임베디드 콘텐츠가 예상되는 곳.
콘텐츠 모델:
0개 이상의 source 요소, 그 뒤에 1개의 img 요소가 옵니다. 선택적으로 스크립트 지원 요소와 혼합될 수 있습니다.
text/html에서 태그 생략:
둘 다 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLPictureElement : HTMLElement {
  [HTMLConstructor] constructor();
};

picture 요소는 그 안에 포함된 img 요소에 여러 소스를 제공하는 컨테이너로, 화면의 픽셀 밀도, 뷰포트 크기, 이미지 형식, 기타 요인에 따라 어떤 이미지 리소스를 사용할지 사용자 에이전트에 힌트를 주거나 선언적으로 제어할 수 있도록 해줍니다. 이 요소는 그 자식을 나타냅니다.

picture 요소는 비슷해 보이는 videoaudio 요소와는 다소 다릅니다. 이들 모두 source 요소를 포함하지만, source 요소의 src 속성은 picture 요소 내에 중첩될 때 의미가 없으며, 리소스 선택 알고리즘도 다릅니다. 또한, picture 요소 자체는 아무것도 표시하지 않으며, 단지 포함된 img 요소가 여러 URL 중에서 선택할 수 있는 컨텍스트를 제공합니다.

4.8.2 source 요소

Element/source

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLSourceElement

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 컨텍스트:
picture 요소의 자식으로, img 요소 앞에 사용됩니다.
미디어 요소의 자식으로, 플로우 콘텐츠 또는 track 요소 앞에 사용됩니다.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그가 없습니다.
콘텐츠 속성:
전역 속성
type — 임베디드 리소스의 유형
media — 적용 가능한 미디어
src (audio 또는 video에서) — 리소스의 주소
srcset (picture에서) — 고해상도 디스플레이, 작은 모니터 등 다양한 상황에서 사용할 이미지
sizes (picture에서) — 다양한 페이지 레이아웃에 맞는 이미지 크기
width (picture에서) — 가로 크기
height (picture에서) — 세로 크기
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLSourceElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute USVString srcset;
  [CEReactions] attribute DOMString sizes;
  [CEReactions] attribute DOMString media;
  [CEReactions] attribute unsigned long width;
  [CEReactions] attribute unsigned long height;
};

source 요소는 img 요소를 위해 여러 개의 대체 소스 세트를 지정하거나 미디어 요소를 위해 여러 개의 대체 미디어 리소스를 지정할 수 있도록 합니다. 이 요소는 자체적으로는 어떠한 것도 나타내지 않습니다.

type 속성은 선택적으로 포함될 수 있습니다. 포함된 경우 값은 유효한 MIME 유형 문자열이어야 합니다.

media 속성도 포함될 수 있습니다. 포함된 경우 값은 유효한 미디어 쿼리 목록을 포함해야 합니다. 사용자는 이 값이 환경과 일치하지 않으면 다음 source 요소로 건너뜁니다.

media 속성은 리소스 선택 알고리즘 동안 한 번만 평가됩니다. 미디어 요소에 대해서는 다르게 평가되지만, picture 요소를 사용하는 경우, 사용자 에이전트는 환경의 변화에 따라 반응합니다.

나머지 요구 사항은 부모 요소가 picture 요소인지, 미디어 요소인지에 따라 달라집니다:

source 요소의 부모가 picture 요소인 경우

srcset 속성이 반드시 포함되어야 하며, 이는 srcset 속성입니다.

srcset 속성은 이미지 소스소스 세트에 기여하며, source 요소가 선택되면 해당 속성이 기여합니다.

만약 srcset 속성이 이미지 후보 문자열을 포함하고 있으며, 이 문자열이 너비 설명자를 사용하는 경우, sizes 속성이 포함될 수 있습니다. 또한, img 요소가 자동 크기 조정을 허용하지 않으면, sizes 속성이 반드시 포함되어야 합니다. sizes 속성은 sizes 속성으로, source 요소가 선택되면 소스 크기에 기여합니다.

만약 img 요소가 자동 크기 조정을 허용하는 경우, 이전 형제 source 요소에서는 sizes 속성을 생략할 수 있습니다. 이 경우, 이는 auto를 지정하는 것과 동일합니다.

source 요소는 크기 속성을 지원합니다. img 요소는 widthheight 속성을 source 요소에서 사용할 수 있으며, 해당 요소를 사용하여 렌더링 크기와 종횡비를 결정합니다. 이는 렌더링 섹션에 정의된 대로입니다.

type 속성은 이미지 유형을 제공하며, 사용자 에이전트가 이 유형을 지원하지 않는 경우 다음 source 요소로 건너뛸 수 있습니다.

만약 type 속성이 지정되지 않은 경우, 사용자 에이전트는 해당 이미지를 가져온 후에 이미지 형식을 지원하지 않는 것을 발견하더라도 다른 source 요소를 선택하지 않습니다.

만약 source 요소가 다음 형제 source 요소 또는 img 요소를 가지며, srcset 속성이 지정된 경우, 다음 중 하나 이상을 포함해야 합니다:

src 속성은 포함되지 않아야 합니다.

source 요소의 부모가 미디어 요소인 경우

src 속성은 URL을 지정하며, 이 값은 유효한 비어 있지 않은 URL이어야 합니다. 이 속성은 반드시 포함되어야 합니다.

type 속성은 미디어 리소스의 유형을 제공하며, 사용자 에이전트가 이 미디어 리소스를 가져오기 전에 재생할 수 있는지 확인하는 데 도움이 됩니다. 특정 MIME 유형이 정의한 코덱 매개변수가 리소스의 인코딩 방식을 정확히 지정해야 할 수도 있습니다. [RFC6381]

source 요소의 src 또는 type 속성을 요소가 이미 video 또는 audio 요소에 삽입된 상태에서 동적으로 수정해도 효과가 없습니다. 재생 중인 내용을 변경하려면 해당 미디어 요소src 속성을 직접 사용하십시오. 이때 사용할 수 있는 리소스를 선택하기 위해 canPlayType() 메서드를 사용할 수 있습니다. 일반적으로 source 요소를 문서가 구문 분석된 후 수동으로 조작하는 것은 불필요하게 복잡한 접근 방식입니다.

다음 목록은 codecs= MIME 매개변수를 type 속성에서 사용하는 방법의 예를 보여줍니다.

H.264 제한된 기본 프로필 비디오(기본 및 확장 비디오 호환) 레벨 3 및 MP4 컨테이너의 저복잡도 AAC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
H.264 확장 프로필 비디오(기본 프로필 호환) 레벨 3 및 MP4 컨테이너의 저복잡도 AAC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.58A01E, mp4a.40.2"'>
H.264 메인 프로필 비디오 레벨 3 및 MP4 컨테이너의 저복잡도 AAC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
H.264 '하이' 프로필 비디오(메인, 기본 또는 확장 프로필과 호환되지 않음) 레벨 3 및 MP4 컨테이너의 저복잡도 AAC 오디오
<source src='video.mp4' type='video/mp4; codecs="avc1.64001E, mp4a.40.2"'>
MPEG-4 비주얼 심플 프로필 레벨 0 비디오 및 MP4 컨테이너의 저복잡도 AAC 오디오
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.8, mp4a.40.2"'>
MPEG-4 고급 심플 프로필 레벨 0 비디오 및 MP4 컨테이너의 저복잡도 AAC 오디오
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.240, mp4a.40.2"'>
MPEG-4 비주얼 심플 프로필 레벨 0 비디오 및 3GPP 컨테이너의 AMR 오디오
<source src='video.3gp' type='video/3gpp; codecs="mp4v.20.8, samr"'>
Theora 비디오 및 Ogg 컨테이너의 Vorbis 오디오
<source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'>
Theora 비디오 및 Ogg 컨테이너의 Speex 오디오
<source src='video.ogv' type='video/ogg; codecs="theora, speex"'>
Ogg 컨테이너의 Vorbis 오디오
<source src='audio.ogg' type='audio/ogg; codecs=vorbis"'>
Ogg 컨테이너의 Speex 오디오
<source src='audio.spx' type='audio/ogg; codecs=speex"'>
Ogg 컨테이너의 FLAC 오디오
<source src='audio.oga' type='audio/ogg; codecs=flac"'>
Dirac 비디오 및 Ogg 컨테이너의 Vorbis 오디오
<source src='video.ogv' type='video/ogg; codecs="dirac, vorbis"'>

srcsetsizes 속성은 포함되지 않아야 합니다.

source HTML 요소 삽입 단계insertedNode가 주어졌을 때 다음과 같습니다:

  1. insertedNode의 부모가 미디어 요소이고, 해당 요소에 src 속성이 없으며 networkStateNETWORK_EMPTY 값을 가지고 있는 경우, 해당 미디어 요소리소스 선택 알고리즘을 호출합니다.

  2. insertedNode의 다음 형제가 img 요소이고, 부모 요소가 picture 요소인 경우, 이를 관련 변형으로 간주하여 img 요소에 적용합니다.

source HTML 요소 제거 단계removedNodeoldParent가 주어졌을 때 다음과 같습니다:

  1. 만약 removedNode의 다음 형제가 img 요소이고, oldParentpicture 요소인 경우, 이를 관련 변형으로 간주하여 img 요소에 적용합니다.

src, type, srcset, sizes, 그리고 media와 같은 IDL 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다.

저자가 제공한 미디어 리소스를 모든 사용자 에이전트가 렌더링할 수 있는지 확신하지 못할 경우, 저자는 마지막 source 요소에서 error 이벤트를 수신하고 대체 동작을 트리거할 수 있습니다:

<script>
 function fallback(video) {
   // <video> 요소를 그 내용으로 대체
   while (video.hasChildNodes()) {
     if (video.firstChild instanceof HTMLSourceElement)
       video.removeChild(video.firstChild);
     else
       video.parentNode.insertBefore(video.firstChild, video);
   }
   video.parentNode.removeChild(video);
 }
</script>
<video controls autoplay>
 <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
 <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"' onerror="fallback(parentNode)">
 ...
</video>

4.8.3 img 요소

요소/img

모든 최신 엔진에서 지원됨.

Firefox1+ Safari1+ Chrome1+
Opera? Edge79+
Edge (Legacy)12+ Internet ExplorerYes
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

HTMLImageElement

모든 최신 엔진에서 지원됨.

Firefox1+ Safari1+ Chrome1+
Opera8+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+
카테고리:
Flow content.
Phrasing content.
Embedded content.
Form-associated element.
요소에 usemap 속성이 있는 경우: Interactive content.
Palpable content.
이 요소를 사용할 수 있는 컨텍스트:
임베디드 콘텐츠가 예상되는 곳.
picture 요소의 자식으로, 모든 source 요소 뒤에.
내용 모델:
없음.
text/html에서 태그 생략:
끝 태그 없음.
내용 속성:
글로벌 속성
alt — 이미지가 사용 불가능할 때 사용할 대체 텍스트
src — 리소스의 주소
srcset — 다른 상황에서 사용할 이미지, 예를 들어 고해상도 디스플레이, 작은 모니터 등
sizes — 다양한 페이지 레이아웃에 대한 이미지 크기
crossorigin — 요소가 교차 출처 요청을 처리하는 방법
usemap — 사용할 이미지 맵의 이름
ismap — 이미지가 서버 측 이미지 맵인지 여부
width — 가로 치수
height — 세로 치수
referrerpolicy — 요소가 시작한 리퍼러 정책 페치를 위해
decoding — 이 이미지를 프레젠테이션에 처리할 때 사용할 디코딩 힌트
loading — 로딩 지연을 결정할 때 사용됨
fetchpriority — 요소가 시작한 우선 순위를 설정함 페치.
접근성 고려 사항:
요소에 비어 있지 않은 alt 속성이 있는 경우: 작성자용; 구현자용.
그 외: 작성자용; 구현자용.
DOM 인터페이스:
[Exposed=Window,
LegacyFactoryFunction=Image(optional unsigned long width, optional unsigned long height)]
interface HTMLImageElement : HTMLElement {
[HTMLConstructor] constructor();

[CEReactions] attribute DOMString alt;
[CEReactions] attribute USVString src;
[CEReactions] attribute USVString srcset;
[CEReactions] attribute DOMString sizes;
[CEReactions] attribute DOMString? crossOrigin;
[CEReactions] attribute DOMString useMap;
[CEReactions] attribute boolean isMap;
[CEReactions] attribute unsigned long width;
[CEReactions] attribute unsigned long height;
readonly attribute unsigned long naturalWidth;
readonly attribute unsigned long naturalHeight;
readonly attribute boolean complete;
readonly attribute USVString currentSrc;
[CEReactions] attribute DOMString referrerPolicy;
[CEReactions] attribute DOMString decoding;
[CEReactions] attribute DOMString loading;
[CEReactions] attribute DOMString fetchPriority;

Promise<undefined> decode();

// 또한 폐기된 멤버도 포함되어 있습니다
};

img 요소는 이미지를 나타냅니다.

img 요소는 크기 속성 소스를 가지며, 초기에는 요소 자체로 설정됩니다.

HTMLImageElement/src

모든 최신 엔진에서 지원됨.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

요소/img#attr-srcset

모든 최신 엔진에서 지원됨.

Firefox38+ Safari8+ Chrome34+
Opera? Edge79+
Edge (Legacy)≤18+ Internet ExplorerNo
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

srcsrcset 속성과, 부모가 picture 요소인 경우, 이전 형제 source 요소의 srcset 속성에서 주어진 이미지는 포함된 콘텐츠입니다. alt 속성의 값은 이미지를 처리할 수 없거나 이미지 로딩이 비활성화된 사람들을 위한 대체 콘텐츠를 제공합니다 (즉, img 요소의 폴백 콘텐츠입니다).

alt 속성 값에 대한 요구 사항은 별도의 섹션에서 설명됩니다.

src 속성은 반드시 존재해야 하며, 비상호작용적이고, 선택적으로 애니메이션된 이미지 리소스를 참조하는 유효한 비어 있지 않은 URL을 포함해야 합니다.

위의 요구 사항은 이미지가 정적 비트맵 (예: PNG, GIF, JPEG), 단일 페이지 벡터 문서 (단일 페이지 PDF, SVG 문서 요소가 있는 XML 파일), 애니메이션 비트맵 (APNG, 애니메이션 GIF), 애니메이션 벡터 그래픽 (선언적 SMIL 애니메이션을 사용하는 SVG 문서 요소가 있는 XML 파일) 등을 의미합니다. 그러나 이러한 정의는 스크립트가 포함된 SVG 파일, 다중 페이지 PDF 파일, 상호작용 MNG 파일, HTML 문서, 일반 텍스트 문서 등을 제외합니다. [PNG] [GIF] [JPEG] [PDF] [XML] [APNG] [SVG] [MNG]

srcset 속성도 존재할 수 있으며, 이는 srcset 속성입니다.

srcset 속성과 src 속성은 (만약 너비 설명자가 사용되지 않은 경우) 이미지 소스소스 세트에 기여합니다 (선택된 source 요소가 없는 경우).

srcset 속성이 존재하고 이미지 후보 문자열너비 설명자를 사용하는 경우, sizes 속성도 반드시 존재해야 합니다. srcset 속성이 지정되지 않았고, loading 속성이 지연 상태에 있는 경우, sizes 속성은 "auto" 값을 가질 수 있습니다 (ASCII 대소문자 구분 없음). sizes 속성은 sizes 속성이며, 이는 소스 크기소스 세트에 기여합니다 (선택된 source 요소가 없는 경우).

img 요소는 다음 조건을 만족할 경우 자동 크기 조정을 허용합니다:

Attributes/crossorigin

모든 최신 엔진에서 지원됨.

Firefox8+ Safari6+ Chrome13+
Opera? Edge79+
Edge (Legacy)12+ Internet ExplorerYes
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

crossorigin 속성은 CORS 설정 속성입니다. 이 속성의 목적은 교차 출처 액세스를 허용하는 타사 사이트의 이미지를 캔버스에서 사용할 수 있도록 하는 것입니다.

referrerpolicy 속성은 참조 정책 속성입니다. 이 속성의 목적은 이미지를 가져올 때 사용되는 참조 정책을 설정하는 것입니다. [REFERRERPOLICY]

decoding 속성은 이 이미지를 디코딩하는 데 선호되는 방법을 나타냅니다. 이 속성이 존재할 경우, 이는 이미지 디코딩 힌트여야 합니다. 이 속성의 값 누락 기본값잘못된 값 기본값은 모두 자동 상태입니다.

HTMLImageElement/fetchPriority

FirefoxNo 🔰 미리보기+ Chrome102+
Opera? Edge102+
Edge (Legacy)? Internet ExplorerNo
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

fetchpriority 속성은 가져오기 우선 순위 속성입니다. 이 속성의 목적은 이미지를 가져올 때 사용되는 우선 순위를 설정하는 것입니다.

loading 속성은 지연 로딩 속성입니다. 이 속성의 목적은 뷰포트 외부에 있는 이미지의 로딩 정책을 나타내는 것입니다.

loading 속성의 상태가 즉시 상태로 변경되면, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. resumptionStepsimg 요소의 지연 로드 재개 단계로 설정합니다.

  2. resumptionSteps이 null이면, 반환합니다.

  3. img지연 로드 재개 단계를 null로 설정합니다.

  4. resumptionSteps을 호출합니다.

<img src="1.jpeg" alt="1">
    <img src="2.jpeg" loading=eager alt="2">
    <img src="3.jpeg" loading=lazy alt="3">
    <div id=very-large></div> <!-- 이 div 이후의 모든 내용은 뷰포트 아래에 있습니다 -->
    <img src="4.jpeg" alt="4">
    <img src="5.jpeg" loading=lazy alt="5">

위 예시에서, 이미지는 다음과 같이 로드됩니다:

1.jpeg, 2.jpeg, 4.jpeg

이미지는 즉시 로드되며, 창의 로드 이벤트를 지연시킵니다.

3.jpeg

이미지는 뷰포트 내에 있어 레이아웃이 알려질 때 로드되지만, 창의 로드 이벤트를 지연시키지 않습니다.

5.jpeg

이미지는 뷰포트로 스크롤될 때만 로드되며, 창의 로드 이벤트를 지연시키지 않습니다.

개발자는 CSS가 이미지의 너비와 높이 속성을 설정하더라도 페이지 레이아웃이 이미지 로드 후 이동하지 않도록 지연 로드된 이미지에 widthheight 속성을 통해 선호하는 종횡비를 지정하는 것이 권장됩니다.

img HTML 요소 삽입 단계insertedNode가 주어졌을 때 다음과 같습니다:

  1. insertedNode의 부모가 picture 요소라면, 이를 insertedNode관련 돌연변이로 간주합니다.

img HTML 요소 제거 단계removedNodeoldParent가 주어졌을 때 다음과 같습니다:

  1. oldParentpicture 요소라면, 이를 removedNode관련 돌연변이로 간주합니다.


img 요소는 레이아웃 도구로 사용되어서는 안 됩니다. 특히, img 요소는 투명 이미지를 표시하는 데 사용되어서는 안 됩니다. 그러한 이미지는 의미를 전달하는 경우가 드물며, 문서에 유용한 정보를 추가하는 경우가 거의 없습니다.


img 요소가 무엇을 나타내는지는 src 속성과 alt 속성에 따라 다릅니다.

만약 src 속성이 설정되어 있고, alt 속성이 빈 문자열로 설정되어 있다면,

이미지는 장식적이거나 나머지 콘텐츠의 보조적 역할을 하며, 문서의 다른 정보와 중복됩니다.

이미지가 사용 가능하고, 사용자 에이전트가 해당 이미지를 표시하도록 설정되어 있다면, 해당 요소는 요소의 이미지 데이터를 나타냅니다.

그렇지 않으면, 해당 요소는 아무것도 나타내지 않으며, 렌더링에서 완전히 생략될 수 있습니다. 사용자 에이전트는 이미지가 존재하지만 렌더링에서 생략되었다는 알림을 사용자에게 제공할 수 있습니다.

만약 src 속성이 설정되어 있고, alt 속성이 빈 문자열이 아닌 값으로 설정되어 있다면,

이미지는 콘텐츠의 중요한 부분이며, alt 속성은 이미지의 텍스트적 등가물이나 대체물을 제공합니다.

이미지가 사용 가능하고, 사용자 에이전트가 해당 이미지를 표시하도록 설정되어 있다면, 해당 요소는 요소의 이미지 데이터를 나타냅니다.

그렇지 않으면, 해당 요소는 alt 속성에 지정된 텍스트를 나타냅니다. 사용자 에이전트는 이미지가 존재하지만 렌더링에서 생략되었다는 알림을 사용자에게 제공할 수 있습니다.

만약 src 속성이 설정되어 있고, alt 속성이 설정되어 있지 않다면,

이미지는 콘텐츠의 중요한 부분일 수 있으며, 해당 이미지의 텍스트적 등가물이 존재하지 않습니다.

적합한 문서에서, alt 속성이 없는 것은 이미지가 콘텐츠의 중요한 부분이지만 이미지 생성 시 텍스트 대체물이 제공되지 않았음을 나타냅니다.

이미지가 사용 가능하고, 사용자 에이전트가 해당 이미지를 표시하도록 설정되어 있다면, 해당 요소는 요소의 이미지 데이터를 나타냅니다.

만약 src 속성의 값이 빈 문자열이라면, 해당 요소는 아무것도 나타내지 않습니다.

그렇지 않으면, 사용자 에이전트는 렌더링되지 않은 이미지가 있음을 나타내는 어떤 표시를 제공해야 하며, 사용자가 요청하거나, 그렇게 구성되었거나, 탐색 시 상황 정보를 제공하기 위해 필요한 경우, 다음과 같이 이미지에 대한 캡션 정보를 제공할 수 있습니다:

  1. 이미지가 빈 문자열이 아닌 title 속성을 가지고 있다면, 해당 속성의 값을 반환합니다.

  2. 이미지가 figure 요소의 자손이고, 해당 요소가 자식 figcaption 요소를 포함하며, figcaption 요소와 그 자손들을 무시했을 때, figure 요소가 플로우 콘텐츠 자손을 가지지 않고 요소 간 공백img 요소만 있는 경우, 첫 번째 figcaption 요소의 내용을 반환합니다.

  3. 아무것도 반환하지 않습니다. (캡션 정보가 없습니다.)

만약 src 속성이 설정되지 않았고, alt 속성이 빈 문자열로 설정되어 있거나, alt 속성이 전혀 설정되지 않은 경우,

해당 요소는 아무것도 나타내지 않습니다.

그 외의 경우

해당 요소는 alt 속성에 지정된 텍스트를 나타냅니다.

alt 속성은 조언 정보를 나타내지 않습니다. 사용자 에이전트는 alt 속성의 내용을 title 속성의 내용과 동일하게 표시해서는 안 됩니다.

사용자 에이전트는 언제나 사용자가 모든 이미지를 표시하거나 표시하지 않도록 선택할 수 있는 옵션을 제공할 수 있습니다. 또한, 시각 장애로 인해 이미지가 보이지 않거나 그래픽 기능이 없는 텍스트 터미널을 사용하는 경우와 같이, 사용자가 이미지를 볼 수 없을 때 이미지를 활용할 수 있도록 돕는 휴리스틱을 적용할 수 있습니다. 예를 들어, 이미지 내에서 발견된 텍스트의 광학 문자 인식(OCR)과 같은 기술이 포함될 수 있습니다.

사용자 에이전트가 누락된 alt 속성을 수정하는 것을 권장하지만, 작성자는 이러한 동작에 의존해서는 안 됩니다. 이미지에 대한 대체 텍스트를 제공하기 위한 요구 사항은 아래에서 자세히 설명됩니다. 이미지의 대체 텍스트 제공 요구 사항

img 요소의 내용이 있다면, 렌더링을 위한 목적으로는 무시됩니다.


usemap 속성은 존재하는 경우 이미지에 관련된 이미지 맵이 있음을 나타낼 수 있습니다.

ismap 속성은 a 요소의 하위 요소이며, href 속성을 가진 요소에서 사용될 때, 해당 요소가 서버 측 이미지 맵에 접근할 수 있음을 나타냅니다. 이는 해당 a 요소에서 이벤트를 처리하는 방법에 영향을 줍니다.

ismap 속성은 부울 속성입니다. 이 속성은 a 요소의 상위 요소가 href 속성을 가지고 있지 않은 경우에는 지정할 수 없습니다.

usemapismap 속성은 source 요소와 media 속성이 지정된 picture 요소와 함께 사용될 때 혼란스러운 동작을 초래할 수 있습니다.

img 요소는 차원 속성을 지원합니다.

HTMLImageElement/alt

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLImageElement/srcset

현재 모든 엔진에서 지원됩니다.

Firefox38+Safari8+Chrome34+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLImageElement/sizes

현재 모든 엔진에서 지원됩니다.

Firefox38+Safari9.1+Chrome38+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

alt, src, srcsetsizes IDL 속성은 각각 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

HTMLImageElement/crossOrigin

현재 모든 엔진에서 지원됩니다.

Firefox8+Safari6+Chrome13+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

crossOrigin IDL 속성은 crossorigin 콘텐츠 속성을 반영해야 하며, 알려진 값만 제한적으로 허용됩니다.

HTMLImageElement/useMap

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

useMap IDL 속성은 usemap 콘텐츠 속성을 반영해야 합니다.

HTMLImageElement/isMap

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

isMap IDL 속성은 ismap 콘텐츠 속성을 반영해야 합니다.

HTMLImageElement/referrerPolicy

현재 모든 엔진에서 지원됩니다.

Firefox50+Safari14+Chrome52+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

referrerPolicy IDL 속성은 referrerpolicy 콘텐츠 속성을 반영해야 하며, 알려진 값만 제한적으로 허용됩니다.

HTMLImageElement/decoding

현재 모든 엔진에서 지원됩니다.

Firefox63+Safari11.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

SVGImageElement/decoding

Firefox63+Safari아니요Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

decoding IDL 속성은 decoding 콘텐츠 속성을 반영해야 하며, 알려진 값만 제한적으로 허용됩니다.

HTMLImageElement/loading

현재 모든 엔진에서 지원됩니다.

Firefox75+Safari15.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

loading IDL 속성은 loading 콘텐츠 속성을 반영해야 하며, 알려진 값만 제한적으로 허용됩니다.

fetchPriority IDL 속성은 fetchpriority 콘텐츠 속성을 반영해야 하며, 알려진 값만 제한적으로 허용됩니다.

image.width [ = value ]

HTMLImageElement/width

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
image.height [ = value ]

HTMLImageElement/height

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이 속성들은 이미지의 실제 렌더링된 크기를 반환하거나 크기가 알려지지 않은 경우 0을 반환합니다.

이 속성들을 설정하면 해당 콘텐츠 속성을 변경할 수 있습니다.

image.naturalWidth

HTMLImageElement/naturalWidth

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
image.naturalHeight

HTMLImageElement/naturalHeight

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이 속성들은 이미지의 고유 크기(자연 크기)를 반환하거나 크기가 알려지지 않은 경우 0을 반환합니다.

image.complete

HTMLImageElement/complete

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이미지가 완전히 다운로드되었거나 이미지가 지정되지 않은 경우 true를 반환합니다. 그렇지 않으면 false를 반환합니다.

image.currentSrc

HTMLImageElement/currentSrc

모든 현재 엔진에서 지원합니다.

Firefox38+Safari9.1+Chrome38+
Opera?Edge79+
Edge (구버전)13+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

이미지의 절대 URL을 반환합니다.

image.decode()

HTMLImageElement/decode

모든 현재 엔진에서 지원합니다.

Firefox68+Safari11.1+Chrome64+
Opera?Edge79+
Edge (구버전)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

SVGImageElement/decode

Firefox68+Safari아니요Chrome64+
Opera?Edge79+
Edge (구버전)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

이 메서드는 사용자 에이전트가 이미지를 병렬로 디코딩하게 하여 디코딩이 완료되면 이행되는 프라미스를 반환합니다.

이미지를 디코딩할 수 없는 경우 이 프라미스는 "EncodingError" DOMException으로 거부됩니다.

image = new Image([ width [, height ] ])

HTMLImageElement/Image

모든 현재 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

새로운 img 요소를 반환하며, 관련 인수에 값이 적용되는 경우 widthheight 속성이 설정됩니다.

IDL 속성 widthheight는 이미지가 렌더링되는 경우 CSS 픽셀 단위로 렌더링된 너비와 높이를 반환해야 합니다. 그렇지 않으면 이미지가 밀도 보정 자연 너비 및 높이를 가지고 있고 사용 가능하지만 렌더링되지 않은 경우 CSS 픽셀 단위로 밀도 보정 자연 너비와 높이를 반환하거나, 이미지가 사용 가능하지 않거나 밀도 보정 자연 너비와 높이를 가지지 않은 경우 0을 반환해야 합니다. [CSS]

설정할 때, 이들은 동일한 이름의 해당 콘텐츠 속성을 반영하는 것처럼 작동해야 합니다.

IDL 속성 naturalWidthnaturalHeight는 이미지가 밀도 보정 자연 너비와 높이를 가지고 있고 사용 가능한 경우 CSS 픽셀 단위로 밀도 보정 자연 너비와 높이를 반환해야 하며, 그렇지 않으면 0을 반환해야 합니다. [CSS]

이미지의 밀도 보정 자연 너비와 높이는 메타데이터에 지정된 방향을 고려하기 때문에, naturalWidthnaturalHeight는 이미지 방향을 올바르게 맞추기 위해 필요한 회전을 적용한 후의 크기를 반영하며, 'image-orientation' 속성의 값에 상관없이 반영됩니다.

complete 속성의 getter 단계는 다음과 같습니다:

  1. 다음 중 하나라도 true인 경우:

    그러면 true를 반환합니다.

  2. false를 반환합니다.

currentSrc IDL 속성은 img 요소의 현재 요청현재 URL을 반환해야 합니다.

decode() 메서드는 호출될 때 다음 단계를 수행해야 합니다:

  1. promise를 새 프라미스로 설정합니다.

  2. 다음 단계를 수행하기 위해 마이크로 태스크를 대기열에 추가합니다:

    이 작업은 이미지 데이터를 업데이트하는 것도 마이크로 태스크에서 수행되기 때문에 수행됩니다. 따라서 다음과 같은 코드를 작성하려면

    img.src = "stars.jpg";
    img.decode();

    stars.jpg를 적절히 디코딩하려면 처리를 한 마이크로 태스크만큼 지연해야 합니다.

    1. 다음 중 하나라도 true인 경우:

      그러면 promise"EncodingError" DOMException으로 거부합니다.

    2. 그렇지 않으면 병렬로 대기하여 다음 중 하나가 발생하고 해당 작업을 수행할 때까지 기다립니다:

      img 요소의 노드 문서완전히 활성화되지 않음
      img 요소의 현재 요청이 변경되거나 변형됨
      img 요소의 현재 요청상태손상됨으로 변경됨

      promise"EncodingError" DOMException으로 거부합니다.

      img 요소의 현재 요청상태완전히 사용 가능으로 변경됨

      이미지를 디코딩합니다.

      이 이미지에 대해 디코딩을 수행할 필요가 없는 경우(예: 벡터 그래픽이기 때문에) promise를 undefined로 해결합니다.

      디코딩이 실패한 경우(예: 잘못된 이미지 데이터 때문에) promise"EncodingError" DOMException으로 거부합니다.

      디코딩 프로세스가 성공적으로 완료되면 promise를 undefined로 해결합니다.

      사용자 에이전트는 디코딩된 미디어 데이터가 다음 성공적인 렌더링 업데이트 단계가 완료될 때까지 쉽게 접근할 수 있도록 보장해야 합니다. 이것은 API 계약의 중요한 부분이며, 가능한 한 위반되어서는 안 됩니다. (일반적으로 이는 메모리가 부족하여 디코딩된 이미지 데이터를 삭제해야 하는 상황이나 이미지가 너무 커서 이 기간 동안 디코딩된 상태로 유지할 수 없는 경우에만 위반될 수 있습니다.)

      애니메이션 이미지는 모든 프레임이 로드된 후에만 완전히 사용 가능 상태가 됩니다. 따라서 구현이 첫 번째 프레임을 그 시점 이전에 디코딩할 수 있지만 위의 단계는 그렇게 하지 않고 모든 프레임이 사용 가능해질 때까지 기다립니다.

  3. promise를 반환합니다.

decode() 메서드가 없는 경우, img 요소를 로드한 다음 표시하는 과정은 다음과 같이 나타날 수 있습니다:

const img = new Image();
img.src = "nebula.jpg";
img.onload = () => {
    document.body.appendChild(img);
};
img.onerror = () => {
    document.body.appendChild(new Text("Could not load the nebula :("));
};

그러나 이렇게 하면 이미지를 DOM에 삽입한 후 발생하는 페인트가 메인 스레드에서 동기 디코드를 유발하기 때문에 눈에 띄는 프레임 손실이 발생할 수 있습니다.

이것은 decode() 메서드를 사용하여 다음과 같이 다시 작성할 수 있습니다:

const img = new Image();
img.src = "nebula.jpg";
img.decode().then(() => {
    document.body.appendChild(img);
}).catch(() => {
    document.body.appendChild(new Text("Could not load the nebula :("));
});

이 후자의 형태는 사용자 에이전트가 이미지를 병렬로 디코딩하고 디코딩 과정이 완료된 후에만 DOM에 삽입하여(따라서 페인트가 발생하게 함으로써) 원본의 프레임 손실을 피할 수 있습니다.

decode() 메서드는 디코딩된 이미지 데이터를 최소한 한 프레임 동안 사용할 수 있도록 보장하려고 시도하므로, requestAnimationFrame() API와 결합될 수 있습니다. 이는 모든 DOM 수정을 애니메이션 프레임 콜백으로 일괄 처리하도록 보장하는 코딩 스타일이나 프레임워크와 함께 사용할 수 있음을 의미합니다:

const container = document.querySelector("#container");

const { containerWidth, containerHeight } = computeDesiredSize();
requestAnimationFrame(() => {
 container.style.width = containerWidth;
 container.style.height = containerHeight;
});

// ...

const img = new Image();
img.src = "supernova.jpg";
img.decode().then(() => {
    requestAnimationFrame(() => container.appendChild(img));
});

구식 팩토리 함수는 HTMLImageElement 객체를 생성하기 위해 제공됩니다 (DOM의 createElement()과 같은 팩토리 메서드 외에도): Image(width, height). 이 구식 팩토리 함수가 호출되면, 다음 단계를 수행해야 합니다:

  1. document현재 전역 객체관련된 Document로 설정합니다.

  2. imgdocument, img, 그리고 HTML 네임스페이스를 사용하여 요소를 생성한 결과로 설정합니다.

  3. width가 주어진 경우, 속성 값을 설정하여 img에 대해 "width" 와 width를 사용합니다.

  4. height가 주어진 경우, 속성 값을 설정하여 img에 대해 "height" 와 height를 사용합니다.

  5. img를 반환합니다.

단일 이미지는 상황에 따라 다른 적절한 대체 텍스트를 가질 수 있습니다.

다음 각 예에서는 동일한 이미지가 사용되지만, 매번 alt 텍스트가 다릅니다. 이 이미지는 스위스 제네바 주의 카루즈 시의 문장입니다.

여기에서는 보조 아이콘으로 사용됩니다:

<p>나는 <img src="carouge.svg" alt=""> 카루즈에서 살았습니다.</p>

여기에서는 도시를 나타내는 아이콘으로 사용됩니다:

<p>고향: <img src="carouge.svg" alt="카루즈"></p>

여기에서는 도시에 관한 텍스트의 일부로 사용됩니다:

<p>카루즈에는 문장이 있습니다.</p>
<p><img src="carouge.svg" alt="문장에는 사자가 나무 앞에 앉아 있는 모습이 그려져 있습니다."></p>
<p>이 문장은 도시 곳곳에서 장식으로 사용됩니다.</p>

여기에서는 이미지에 대한 대안이 아닌 설명을 제공하는 유사한 텍스트를 지원하는 방법으로 사용됩니다:

<p>카루즈에는 문장이 있습니다.</p>
<p><img src="carouge.svg" alt=""></p>
<p>문장에는 사자가 나무 앞에 앉아 있는 모습이 그려져 있습니다.
이 문장은 도시 곳곳에서 장식으로 사용됩니다.</p>

여기에서는 이야기의 일부로 사용됩니다:

<p>그녀는 폴더를 집어들고 종이 한 장이 떨어졌습니다.</p>
<p><img src="carouge.svg" alt="방패 모양의 종이는
빨간 배경에, 초록색 나무, 그리고 혀를 내민
황색 사자가 그려져 있으며, 꼬리가 S자 모양으로 되어 있었습니다."></p>
<p>그녀는 폴더를 응시했습니다. S! 그녀가 그토록 찾고 있던 해답은 단순히 S라는 글자였습니다! 그녀는 왜 그동안 그것을 알아차리지 못했을까요? 이제 모든 것이 맞아떨어졌습니다. 헥터가 사자의 꼬리를 언급했던 전화 통화, 마리아가 혀를 내밀었던 그 순간...</p>

여기에서는 출판 당시 이미지가 무엇인지 알 수 없었고, 단지 문장 이미지일 뿐이라는 것만 알았기 때문에 대체 텍스트를 제공할 수 없었고, 대신 title 속성에 이미지에 대한 간단한 캡션만 제공되었습니다:

<p>마지막으로 문장을 업로드한 사용자가 이 문장을 업로드했습니다:</p>
<p><img src="last-uploaded-coat-of-arms.cgi" title="사용자 업로드 문장."></p>

이 경우에도 저자가 실제 대체 텍스트를 제공할 수 있는 방법을 찾는 것이 이상적입니다. 예를 들어 이전 사용자에게 요청하는 방법이 있습니다. 대체 텍스트를 제공하지 않으면 이미지 보기 불가능한 사람들, 예를 들어 시각 장애인 사용자, 매우 낮은 대역폭 연결을 사용하는 사용자, 또는 바이트 단위로 요금이 부과되는 사용자, 또는 텍스트 전용 웹 브라우저를 사용해야 하는 사용자에게 문서 사용이 더 어려워집니다.

여기에는 동일한 이미지가 다양한 상황에서 사용되며, 매번 다른 적절한 대체 텍스트가 제공되는 몇 가지 추가 예가 있습니다.

<article>
 <h1>나의 고양이들</h1>
 <h2>플러피</h2>
 <p>플러피는 내가 가장 좋아하는 고양이입니다.</p>
 <img src="fluffy.jpg" alt="그녀는 실타래와 노는 것을 좋아합니다.">
 <p>그녀는 너무 귀엽습니다.</p>
 <h2>마일스</h2>
 <p>내 다른 고양이 마일스는 먹고 자는 것만 합니다.</p>
</article>
<article>
 <h1>사진 촬영</h1>
 <h2>실내에서 움직이는 대상을 촬영하기</h2>
 <p>여기서의 요령은 대상을 어떤 속도로, 어떤 거리에서 지나갈지 예측하는 것입니다.</p>
 <img src="fluffy.jpg" alt="실타래를 쫓는 고양이가 이 기술로 꽤 잘 촬영될 수 있습니다.">
 <h2>밤의 자연</h2>
 <p>이것을 달성하려면 극도로 민감한 필름이 필요하거나 엄청난 플래시가 필요할 것입니다.</p>
</article>
<article>
 <h1>나에 대하여</h1>
 <h2>내 애완동물들</h2>
 <p>나는 플러피라는 이름의 고양이와 마일스라는 이름의 개를 키우고 있습니다.</p>
 <img src="fluffy.jpg" alt="플러피, 내 고양이는 항상 바쁩니다.">
 <p>내 개 마일스와 나는 함께 긴 산책을 즐깁니다.</p>
 <h2>음악</h2>
 <p>산책 후, 마음을 비우고 바흐의 음악을 듣는 것을 좋아합니다.</p>
</article>
<article>
 <h1>플러피와 실타래</h1>
 <p>플러피는 실타래로 노는 것을 좋아하는 고양이였습니다. 그녀는 또한 점프하는 것을 좋아했습니다.</p>
 <aside><img src="fluffy.jpg" alt="" title="플러피"></aside>
 <p>그녀는 아침에 놀고, 저녁에도 놀았습니다.</p>
</article>

4.8.4 이미지

4.8.4.1 소개

이 섹션은 비규범적입니다.

HTML에서 단일 이미지 리소스가 있을 때 이미지를 포함하려면 img 요소와 src 속성을 사용하십시오.

<h2>오늘의 추천 기사</h2>
<img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
는 영국의 </a href="/wiki/Music_hall">뮤직 홀</a> 가수였습니다...

그러나 작가가 사용자 에이전트가 선택할 수 있는 여러 이미지 리소스를 사용하고자 하는 경우가 있습니다:

위의 상황은 상호 배타적이지 않습니다. 예를 들어, 장치-픽셀-비율에 따른 다른 리소스와 아트 디렉션에 따른 다른 리소스를 결합하는 것이 합리적입니다.

이 문제를 스크립팅을 사용하여 해결할 수 있지만, 그렇게 하면 다른 문제가 발생할 수 있습니다:

이를 염두에 두고, 이 사양은 위의 문제를 선언적으로 해결하기 위한 여러 기능을 소개합니다.

장치-픽셀-비율에 따른 선택

이미지의 렌더링된 크기가 고정되어 있을 때 srcsrcset 속성을 x 지시자와 함께 사용하여 크기만 다른 여러 이미지를 제공할 수 있습니다(작은 이미지는 큰 이미지의 축소된 버전입니다).

x 지시자는 이미지의 렌더링된 크기가 뷰포트 너비에 따라 달라질 때(뷰포트 기반 선택)는 적합하지 않지만, 아트 디렉션과 함께 사용할 수 있습니다.

<h2>오늘의 추천 기사</h2>
<img src="/uploads/100-marie-lloyd.jpg"
 srcset="/uploads/150-marie-lloyd.jpg 1.5x, /uploads/200-marie-lloyd.jpg 2x"
 alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
는 영국의 </a href="/wiki/Music_hall">뮤직 홀</a> 가수였습니다...

사용자 에이전트는 사용자의 화면 픽셀 밀도, 확대/축소 수준, 그리고 사용자의 네트워크 조건과 같은 다른 요인에 따라 제공된 리소스 중에서 선택할 수 있습니다.

이전 사용자 에이전트와의 하위 호환성을 위해 srcset 속성을 아직 이해하지 못하는 경우를 대비하여 URL 중 하나가 img 요소의 src 속성에 지정됩니다. 이는 이전 사용자 에이전트에서도 유용한(사용자가 원하는 것보다 해상도가 낮을 수 있지만) 콘텐츠가 표시되도록 합니다. 새로운 사용자 에이전트의 경우 src 속성은 1x 지시자가 있는 srcset에 지정된 것처럼 리소스 선택에 참여합니다.

이미지의 렌더링된 크기는 widthheight 속성에 지정되어 사용자 에이전트가 이미지를 다운로드하기 전에 공간을 할당할 수 있습니다.

뷰포트 기반 선택

srcsetsizes 속성을 w 지시자와 함께 사용하여 크기만 다른 여러 이미지를 제공할 수 있습니다(작은 이미지는 큰 이미지의 축소된 버전입니다).

이 예에서는 배너 이미지가 전체 뷰포트 너비를 차지합니다(적절한 CSS를 사용).

<h1><img sizes="100vw" srcset="wolf-400.jpg 400w, wolf-800.jpg 800w, wolf-1600.jpg 1600w"
 src="wolf-400.jpg" alt="멋진 늑대"></h1>

사용자 에이전트는 지정된 w 지시자와 sizes 속성에 지정된 렌더링된 크기에서 각 이미지의 효과적인 픽셀 밀도를 계산할 수 있습니다. 그런 다음 사용자의 화면 픽셀 밀도, 확대/축소 수준, 그리고 사용자의 네트워크 조건과 같은 다른 요인에 따라 제공된 리소스 중에서 선택할 수 있습니다.

사용자의 화면이 320 CSS 픽셀 너비인 경우, 이는 wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x을 지정하는 것과 같습니다. 반면, 사용자의 화면이 1200 CSS 픽셀 너비인 경우, 이는 wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x을 지정하는 것과 같습니다. w 지시자와 sizes 속성을 사용함으로써 사용자 에이전트는 사용자의 장치 크기에 상관없이 올바른 이미지 소스를 다운로드할 수 있습니다.

이전 사용자 에이전트와의 하위 호환성을 위해, URL 중 하나가 img 요소의 src 속성에 지정됩니다. 새로운 사용자 에이전트에서는 src 속성이 srcset 속성이 w 지시자를 사용하는 경우 무시됩니다.

이 예에서는 웹 페이지가 뷰포트 너비에 따라 세 가지 레이아웃을 가집니다. 좁은 레이아웃에서는 이미지가 단일 열로 표시되며(각 이미지의 너비는 약 100%), 중간 레이아웃에서는 두 개의 열로 표시되며(각 이미지의 너비는 약 50%), 가장 넓은 레이아웃에서는 세 개의 열로 표시되며 페이지 여백이 있습니다(각 이미지의 너비는 약 33%). 이 레이아웃은 뷰포트가 30em 너비 및 50em 너비일 때 변경됩니다.

<img sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
 srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
 src="swing-400.jpg" alt="케틀벨 스윙">

sizes 속성은 30em50em에서 레이아웃 브레이크포인트를 설정하고, 이 브레이크포인트 사이에서 이미지 크기를 100vw, 50vw, 또는 calc(33vw - 100px)로 선언합니다. 이러한 크기는 반드시 CSS에서 지정된 실제 이미지 너비와 정확히 일치할 필요는 없습니다.

사용자 에이전트는 sizes 속성에서 참으로 평가되는 <미디어 조건>(괄호 안의 부분)을 가진 첫 번째 항목을 사용하거나, 모두 거짓으로 평가되면 마지막 항목(calc(33vw - 100px))을 사용합니다.

예를 들어, 뷰포트 너비가 29em인 경우, (max-width: 30em)은 참으로 평가되며 100vw가 사용되므로 리소스 선택을 위해 이미지 크기는 29em가 됩니다. 반면, 뷰포트 너비가 32em인 경우, (max-width: 30em)은 거짓으로 평가되지만, (max-width: 50em)은 참으로 평가되며 50vw가 사용되므로 리소스 선택을 위해 이미지 크기는 16em(뷰포트 너비의 절반)이 됩니다. 약간 더 넓은 뷰포트는 다른 레이아웃으로 인해 더 작은 이미지를 결과로 나타냅니다.

사용자 에이전트는 그런 다음 효과적인 픽셀 밀도를 계산하고 이전 예와 유사하게 적절한 리소스를 선택할 수 있습니다.

이 예는 이전 예와 동일하지만 이미지는 지연 로드됩니다. 이 경우 sizes 속성은 auto 키워드를 사용할 수 있으며, 사용자 에이전트는 width 속성(또는 CSS에서 지정된 너비)을 사용하여 소스 크기를 계산합니다.

<img loading="lazy" width="200" height="200" sizes="auto"
 srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
 src="swing-400.jpg" alt="케틀벨 스윙">

레거시 사용자 에이전트와의 더 나은 하위 호환성을 위해, 필요할 경우 폴백 크기를 지정할 수 있습니다.

<img loading="lazy" width="200" height="200"
 sizes="auto, (max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
 srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
 src="swing-400.jpg" alt="케틀벨 스윙">
아트 디렉션 기반 선택

picture 요소와 source 요소, 그리고 media 속성을 함께 사용하여 이미지 콘텐츠가 달라지는 여러 이미지를 제공할 수 있습니다(예를 들어, 작은 이미지는 큰 이미지의 잘린 버전일 수 있습니다).

<picture>
  <source media="(min-width: 45em)" srcset="large.jpg">
  <source media="(min-width: 32em)" srcset="med.jpg">
  <img src="small.jpg" alt="늑대가 눈 속을 달리고 있습니다.">
</picture>

사용자 에이전트는 source 요소의 media 속성에 있는 미디어 쿼리가 일치하는 첫 번째 요소를 선택한 후, 해당 srcset 속성에서 적절한 URL을 선택합니다.

선택된 리소스에 따라 이미지의 렌더링된 크기가 달라집니다. 다운로드 전에 사용자 에이전트가 사용할 수 있는 크기를 지정하려면 CSS를 사용할 수 있습니다.

img { width: 300px; height: 300px }
@media (min-width: 32em) { img { width: 500px; height:300px } }
@media (min-width: 45em) { img { width: 700px; height:400px } }

이 예는 아트 디렉션장치-픽셀-비율 기반 선택을 결합한 것입니다. 뷰포트의 절반을 차지하는 배너는 좁은 화면용과 넓은 화면용 두 가지 버전으로 제공됩니다.

<h1>
 <picture>
  <source media="(max-width: 500px)" srcset="banner-phone.jpeg, banner-phone-HD.jpeg 2x">
  <img src="banner.jpeg" srcset="banner-HD.jpeg 2x" alt="아침 콤보">
 </picture>
</h1>
이미지 형식 기반 선택

type 속성을 source 요소에 사용하여 서로 다른 형식의 여러 이미지를 제공할 수 있습니다.

<h2>오늘의 추천 기사</h2>
<picture>
 <source srcset="/uploads/100-marie-lloyd.webp" type="image/webp">
 <source srcset="/uploads/100-marie-lloyd.jxr" type="image/vnd.ms-photo">
 <img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
</picture>
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
는 영국의 </a href="/wiki/Music_hall">뮤직 홀</a> 가수였습니다...

이 예에서, 사용자 에이전트는 지원되는 MIME 타입을 가진 type 속성이 있는 첫 번째 소스를 선택합니다. 만약 사용자 에이전트가 WebP 이미지를 지원한다면, 첫 번째 source 요소가 선택될 것입니다. 만약 그렇지 않고, 사용자 에이전트가 JPEG XR 이미지를 지원한다면, 두 번째 source 요소가 선택됩니다. 이 두 포맷 중 어느 것도 지원되지 않는 경우, img 요소가 선택됩니다.

4.8.4.1.1 적응형 이미지

이 섹션은 비규범적입니다.

CSS와 미디어 쿼리를 사용하여 사용자의 환경, 특히 서로 다른 뷰포트 크기와 픽셀 밀도에 맞춰 동적으로 적응하는 그래픽 페이지 레이아웃을 구성할 수 있습니다. 그러나 콘텐츠의 경우 CSS가 도움이 되지 않으므로, 대신 img 요소의 srcset 속성과 picture 요소를 사용해야 합니다. 이 섹션에서는 이러한 기능을 사용하는 예제를 보여줍니다.

예를 들어, 너비가 600 CSS 픽셀보다 넓은 화면에서는 a-rectangle.png라는 300×150 이미지를 사용하고, 600 CSS 픽셀 이하의 작은 화면에서는 a-square.png라는 100×100 이미지를 사용하고자 한다고 가정해 봅시다. 이 마크업은 다음과 같이 작성할 수 있습니다:

<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses.">
 </picture>
 </figcaption>Barney Frank, 2011</figcaption>
</figure>

alt 속성에 어떤 내용을 넣어야 하는지에 대한 자세한 내용은 이미지 대체 텍스트 제공 요구 사항 섹션을 참조하십시오.

이 예제의 문제점은 이미지가 로드될 때 사용자 에이전트가 이미지의 크기를 미리 알지 못한다는 것입니다. 페이지 로드 중에 레이아웃이 여러 번 리플로우되지 않도록 하려면 CSS와 CSS 미디어 쿼리를 사용하여 크기를 제공할 수 있습니다:

<style>
 #a { width: 300px; height: 150px; }
 @media (max-width: 600px) { #a { width: 100px; height: 100px; } }
</style>
<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 </figcaption>Barney Frank, 2011</figcaption>
</figure>

또는 widthheight 속성을 사용하여 구형 사용자 에이전트를 위해 너비와 높이를 제공하고, CSS는 picture를 지원하는 사용자 에이전트에서만 사용하도록 할 수 있습니다:

<style media="(max-width: 600px)">
 #a { width: 100px; height: 100px; }
</style>
<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" width="300" height="150"
  alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 </figcaption>Barney Frank, 2011</figcaption>
</figure>

img 요소는 src 속성과 함께 사용됩니다. 이 속성은 picture 요소를 지원하지 않는 구형 사용자 에이전트를 위해 사용할 이미지의 URL을 제공합니다. 이는 src 속성에 어떤 이미지를 제공해야 하는지에 대한 질문으로 이어집니다.

저자가 구형 사용자 에이전트에서 가장 큰 이미지를 원한다면, 마크업은 다음과 같이 작성할 수 있습니다:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <img src="pear-desktop.jpeg" alt="The pear is juicy.">
</picture>

그러나 구형 모바일 사용자 에이전트가 더 중요하다면, 세 개의 이미지를 모두 source 요소에 나열하여 src 속성을 완전히 무시할 수 있습니다.

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>

이 시점에서 src 속성이 picture 요소를 지원하는 사용자 에이전트에 의해 완전히 무시되고 있으므로, src 속성은 가장 작은 이미지도, 가장 큰 이미지도 아닌 이미지로 기본 설정할 수 있습니다:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-tablet.jpeg" alt="The pear is juicy.">
</picture>

위 예제에서는 max-width 미디어 기능을 사용하여 이미지가 의도된 최대 뷰포트 크기를 지정합니다. 대신 min-width를 사용할 수도 있습니다.

<picture>
 <source srcset="pear-desktop.jpeg" media="(min-width: 1281px)">
 <source srcset="pear-tablet.jpeg" media="(min-width: 721px)">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>
4.8.4.2 source, img, 및 link 요소에 공통된 속성
4.8.4.2.1 Srcset 속성

srcset 속성은 이 섹션에서 정의된 요구사항을 가진 속성입니다.

존재하는 경우, 그 값은 하나 이상의 이미지 후보 문자열로 구성되어야 하며, 각 문자열은 U+002C 콤마 문자(,)로 구분됩니다. 만약 이미지 후보 문자열이 URL 뒤에 설명자나 ASCII 공백 문자가 없으면, 다음 이미지 후보 문자열은 하나 이상의 ASCII 공백 문자로 시작해야 합니다.

이미지 후보 문자열은 다음 구성 요소로 이루어지며, 아래 목록에 추가로 설명된 제한사항이 적용됩니다:

  1. 하나 이상의 ASCII 공백 문자.

  2. 유효한 비어있지 않은 URL, U+002C 콤마 문자로 시작하거나 끝나지 않으며, 비상호작용적이고 선택적으로 애니메이션 되는 이미지 리소스를 참조하며, 페이징 되거나 스크립트화 되지 않은 리소스여야 합니다.

  3. 하나 이상의 ASCII 공백 문자.

  4. 다음 중 하나:

  5. 하나 이상의 ASCII 공백 문자.

동일한 요소에 대해 동일한 너비 설명자 값을 가진 이미지 후보 문자열이 존재해서는 안 됩니다.

동일한 요소에 대해 동일한 픽셀 밀도 설명자 값을 가진 이미지 후보 문자열이 존재해서는 안 됩니다. 이 요구사항을 충족하기 위해 설명자가 없는 이미지 후보 문자열1x 설명자를 가진 문자열과 동일한 것으로 간주됩니다.

만약 요소에 크기 속성이 존재한다면, 해당 요소의 모든 이미지 후보 문자열에는 너비 설명자가 지정되어야 합니다.

4.8.4.2.2 Sizes 속성

sizes 속성은 이 섹션에서 정의된 요구 사항을 가진 속성입니다.

존재하는 경우, 그 값은 유효한 소스 크기 목록이어야 합니다.

유효한 소스 크기 목록은 다음 문법과 일치하는 문자열입니다: [CSSVALUES] [MQ]

<source-size-list> = <source-size>#? , <source-size-value>
<source-size> = <media-condition> <source-size-value> | auto
<source-size-value> = <length> | auto

<source-size-value>이(가) <length>인 경우, 음수일 수 없으며, 수학 함수 외의 CSS 함수를 사용할 수 없습니다.

auto 키워드는 sizes 속성 구문 분석에서 계산되는 너비입니다. 존재하는 경우, 첫 번째 항목이어야 하며 전체 <source-size-list> 값은 "auto" 문자열(ASCII 대소문자 구분 없음)이거나 "auto," 문자열(ASCII 대소문자 구분 없음)로 시작해야 합니다.

이미지 로드를 시작한 img 요소가 자동 크기 허용을 허용하고 렌더링 중인 경우, auto구체적인 객체 크기 너비입니다. 그렇지 않은 경우, auto 값은 무시되며 대신 다음 소스 크기가 사용됩니다.

auto 키워드는 다음 조건이 충족되는 경우 sizes 속성의 source 요소와 sizes 속성의 img 요소에 지정할 수 있습니다. 그렇지 않으면, auto를 지정해서는 안 됩니다.

또한 widthheight 속성 또는 CSS를 사용하여 크기를 지정하는 것이 강력하게 권장됩니다. 지정된 크기가 없으면 sizes="auto"렌더링 섹션에서 contain-intrinsic-size: 300px 150px을 의미하기 때문에 이미지가 300x150 크기로 렌더링될 가능성이 높습니다.

<source-size-value>는 이미지의 의도된 레이아웃 너비를 제공합니다. 작성자는 <media-condition>을 사용하여 다양한 환경에 대해 다른 너비를 지정할 수 있습니다.

<source-size-value>에는 퍼센트가 허용되지 않습니다. 'vw' 단위는 뷰포트 너비에 상대적인 크기를 나타내는 데 사용할 수 있습니다.

4.8.4.3 처리 모델

img 요소는 현재 요청대기 중인 요청을 가지고 있습니다. 현재 요청은 처음에 새로운 이미지 요청으로 설정됩니다. 대기 중인 요청은 처음에 null로 설정됩니다.

이미지 요청상태, 현재 URL, 그리고 이미지 데이터를 가집니다.

이미지 요청상태는 다음 중 하나입니다:

사용 불가
사용자가 어떤 이미지 데이터도 얻지 못했거나, 이미지 데이터를 일부 또는 전부 얻었지만 이미지의 크기를 얻을 만큼 충분히 디코딩하지 못한 상태입니다.
부분적으로 사용 가능
사용자가 일부 이미지 데이터를 얻었으며 적어도 이미지의 크기는 사용할 수 있는 상태입니다.
완전히 사용 가능
사용자가 모든 이미지 데이터를 얻었으며 적어도 이미지의 크기는 사용할 수 있는 상태입니다.
손상됨
사용자가 얻을 수 있는 모든 이미지 데이터를 얻었지만, 이미지 크기를 얻을 만큼 이미지 데이터를 디코딩할 수 없을 경우 (예: 이미지가 손상되었거나, 포맷이 지원되지 않거나, 데이터를 얻을 수 없는 경우).

이미지 요청현재 URL은 처음에 빈 문자열로 설정됩니다.

이미지 요청이미지 데이터는 디코딩된 이미지 데이터입니다.

이미지 요청상태부분적으로 사용 가능 또는 완전히 사용 가능일 때, 이미지 요청사용 가능하다고 합니다.

img 요소의 현재 요청상태완전히 사용 가능하고 사용자가 미디어 데이터를 오류 없이 디코딩할 수 있다면, img 요소는 완전히 디코딩 가능하다고 합니다.

이미지 요청상태는 처음에 사용 불가로 설정됩니다.

img 요소의 현재 요청사용 가능할 때, img 요소는 너비가 이미지의 밀도 보정된 자연 너비(있다면)이고, 높이가 이미지의 밀도 보정된 자연 높이(있다면)이며, 외형이 이미지의 자연스러운 외형인 그리기 소스를 제공합니다.


img 요소는 srcset 속성이 지정되었거나 부모가 picture 요소인 경우 srcset 또는 picture를 사용한다고 합니다.


img 요소는 마지막으로 선택된 소스를 가지며, 이는 처음에 null로 설정되어야 합니다.

이미지 요청마다 현재 픽셀 밀도가 있으며, 이는 처음에 1로 설정되어야 합니다.

이미지 요청마다 선호하는 밀도 보정된 크기가 있으며, 이는 너비와 높이로 구성된 구조체 또는 null입니다. 처음에는 null로 설정되어야 합니다.

이미지 요소 img밀도 보정된 자연 너비와 높이를 결정하려면:

  1. dimimg현재 요청선호하는 밀도 보정된 크기로 설정합니다.

    선호하는 밀도 보정된 크기는 이미지의 메타 정보에 기반하여 이미지 프레젠테이션 준비 알고리즘에서 설정됩니다.

  2. dim이 null이면 dimimg자연 크기로 설정합니다.

  3. dim의 너비를 img현재 요청현재 픽셀 밀도로 나눈 값으로 설정합니다.

  4. dim의 높이를 img현재 요청현재 픽셀 밀도로 나눈 값으로 설정합니다.

  5. dim을 반환합니다.

예를 들어, 현재 픽셀 밀도가 3.125인 경우, 이는 1인치 당 300개의 디바이스 픽셀이 있다는 의미이며, 따라서 이미지 데이터가 300x600이면 밀도 보정된 자연 너비와 높이는 96 CSS 픽셀 x 192 CSS 픽셀입니다.

모든 imglink 요소는 소스 세트와 연결됩니다.

소스 세트는 하나 이상의 이미지 소스소스 크기로 구성된 정렬된 집합입니다.

이미지 소스URL이며, 선택적으로 픽셀 밀도 서술자 또는 너비 서술자를 포함할 수 있습니다.

소스 크기<소스 크기 값>입니다. 소스 크기뷰포트에 상대적인 단위를 가지면, 이는 img 요소의 노드 문서뷰포트에 상대적으로 해석되어야 합니다. 다른 단위는 미디어 쿼리와 동일하게 해석되어야 합니다. [MQ]


파싱 오류는 이 섹션의 알고리즘에서 입력과 요구사항 사이의 치명적이지 않은 불일치를 나타냅니다. 사용자는 파싱 오류를 노출하도록 권장됩니다.


이미지가 성공적으로 가져왔는지 여부 (예: 응답 상태가 OK 상태였는지 여부)는 이미지의 유형과 유효한 이미지인지 여부를 결정할 때 무시되어야 합니다.

이렇게 하면 서버가 오류 응답을 반환하더라도 이미지가 표시될 수 있습니다.

사용자는 이미지의 이미지 스니핑 규칙을 적용하여 이미지 유형을 결정해야 하며, 이미지의 관련된 콘텐츠 유형 헤더공식 유형을 제공합니다. 이러한 규칙이 적용되지 않는 경우, 이미지의 유형은 이미지의 관련된 콘텐츠 유형 헤더에 의해 제공되는 유형이어야 합니다.

사용자는 img 요소에서 비이미지 리소스를 지원해서는 안 됩니다 (예: 문서 요소가 HTML 요소인 XML 파일). 사용자는 이미지 리소스에 포함된 실행 가능한 코드 (예: 스크립트)를 실행해서는 안 됩니다. 사용자는 멀티페이지 리소스의 첫 번째 페이지만 표시해야 하며 (예: PDF 파일), 리소스가 상호작용 방식으로 동작하지 않도록 해야 하지만, 리소스의 애니메이션은 존중해야 합니다.

이 명세서는 어떤 이미지 유형을 지원해야 하는지에 대해서는 명시하지 않습니다.

4.8.4.3.1 이미지를 얻는 시점

기본적으로 이미지는 즉시 로드됩니다. 사용자 에이전트는 사용자에게 필요한 경우에만 이미지를 로드하는 옵션을 제공할 수 있습니다. (예를 들어, 대역폭이 제한된 사용자는 이러한 옵션을 사용할 수 있습니다.)

이미지를 즉시 로드할 때, 사용자 에이전트는 해당 요소가 생성되었거나 관련 변형을 겪을 때마다, 애니메이션 재시작 플래그가 설정된 경우, img 요소의 이미지 데이터를 동기적으로 업데이트해야 합니다.

필요한 경우에만 이미지를 로드할 때, 사용자 에이전트는 img 요소의 현재 요청상태사용 불가일 때만 이미지 데이터를 업데이트해야 합니다. img 요소가 관련 변형을 겪을 때, 사용자 에이전트가 필요한 경우에만 이미지를 로드한다면, img 요소의 현재 요청상태사용 불가로 돌아가야 합니다.

4.8.4.3.2 DOM 변형에 반응

img 요소의 관련 변형은 다음과 같습니다:

4.8.4.3.3 사용 가능한 이미지 목록

document 객체는 사용 가능한 이미지 목록을 가져야 합니다. 이 목록의 각 이미지는 절대 URL, CORS 설정 속성 모드, 그리고 모드가 비 CORS가 아닌 경우 출처로 구성된 튜플로 식별됩니다. 각 이미지는 또한 상위 레이어 캐싱 무시 플래그를 가집니다. 사용자 에이전트는 언제든지 한 document 객체의 사용 가능한 이미지 목록에서 다른 객체로 항목을 복사할 수 있지만(예: document가 생성될 때, 다른 document에서 로드된 모든 이미지를 추가할 수 있습니다.), 이 방식으로 복사된 항목의 키를 변경해서는 안 되며, 복사된 항목에 대해 상위 레이어 캐싱 무시 플래그를 해제해야 합니다. 사용자 에이전트는 또한 메모리를 절약하기 위해 언제든지 이러한 목록에서 이미지를 제거할 수 있습니다. 사용자 에이전트는 상위 레이어 캐싱 의미에 따라 적절하게 사용 가능한 이미지 목록의 항목을 제거해야 합니다(예: HTTP `Cache-Control` 응답 헤더가 있는 경우).

사용 가능한 이미지 목록src 속성을 이전에 로드된 URL로 변경할 때 동기적 전환을 가능하게 하고, 같은 문서에서 이미지를 다시 다운로드하지 않도록 하기 위한 것입니다. 이 목록은 이전 이미지가 여전히 로드 중일 때 같은 이미지를 다시 다운로드하는 것을 방지하는 데 사용되지 않습니다.

사용자 에이전트는 사용 가능한 이미지 목록과 별도로 이미지 데이터를 저장할 수도 있습니다.

예를 들어, 리소스에 HTTP 응답 헤더 `Cache-Control: must-revalidate`가 있는 경우, 상위 레이어 캐싱 무시 플래그가 해제되면 사용자 에이전트는 사용 가능한 이미지 목록에서 해당 이미지를 제거하지만, 이미지 데이터를 별도로 보관하고 서버가 304 Not Modified 상태로 응답할 경우 이를 사용할 수 있습니다.

4.8.4.3.4 이미지 디코딩

이미지 데이터는 일반적으로 파일 크기를 줄이기 위해 인코딩됩니다. 이는 사용자 에이전트가 이미지를 화면에 표시하기 위해 데이터를 디코딩해야 한다는 것을 의미합니다. 디코딩은 이미지의 미디어 데이터를 화면에 표시하기에 적합한 비트맵 형태로 변환하는 과정입니다. 이 과정은 콘텐츠를 표시하는 다른 과정에 비해 상대적으로 느릴 수 있습니다. 따라서 사용자 에이전트는 최상의 사용자 경험을 제공하기 위해 언제 디코딩을 수행할지 선택할 수 있습니다.

이미지 디코딩이 다른 콘텐츠의 표시를 완료될 때까지 지연시키는 경우, 이를 동기적 디코딩이라고 합니다. 일반적으로 이 방법은 이미지를 다른 콘텐츠와 동시에 원자적으로 표시하는 효과가 있습니다. 그러나 이 디코딩을 수행하는 데 소요되는 시간만큼 표시가 지연됩니다.

이미지 디코딩이 다른 콘텐츠의 표시를 지연시키지 않는 경우, 이를 비동기적 디코딩이라고 합니다. 이 방법은 비이미지 콘텐츠를 더 빠르게 표시할 수 있는 효과가 있습니다. 그러나 디코딩이 완료될 때까지 화면에 이미지 콘텐츠가 표시되지 않습니다. 디코딩이 완료되면 화면이 이미지로 업데이트됩니다.

동기 및 비동기 디코딩 모드 모두에서 최종 콘텐츠는 동일한 시간이 경과한 후 화면에 표시됩니다. 주요 차이점은 사용자 에이전트가 비이미지 콘텐츠를 최종 콘텐츠보다 먼저 표시할지 여부입니다.

사용자 에이전트가 동기적 또는 비동기적 디코딩을 수행할지 결정하는 데 도움을 주기 위해, decoding 속성을 img 요소에 설정할 수 있습니다. decoding 속성의 가능한 값은 다음과 같은 이미지 디코딩 힌트 키워드입니다:

키워드 상태 설명
sync 동기적 이 이미지를 다른 콘텐츠와 원자적으로 표시하기 위해 동기적으로 디코딩하도록 설정합니다.
async 비동기적 다른 콘텐츠의 표시를 지연시키지 않기 위해 비동기적으로 디코딩하도록 설정합니다.
auto 자동 디코딩 모드에 대한 특별한 설정이 없음을 나타냅니다(기본값).

이미지를 디코딩할 때, 사용자 에이전트는 decoding 속성의 상태에 의해 나타난 선호를 존중해야 합니다. 상태가 자동으로 설정된 경우, 사용자 에이전트는 임의의 디코딩 동작을 선택할 수 있습니다.

decode() 메서드를 사용하여 디코딩 동작을 제어할 수도 있습니다. decode() 메서드는 화면에 콘텐츠를 표시하는 프로세스와 독립적으로 디코딩을 수행하므로, decoding 속성에 영향을 받지 않습니다.

4.8.4.3.5 이미지 데이터 업데이트

이 알고리즘은 병렬로 실행 중인 단계에서 호출될 수 없습니다. 사용자 에이전트가 병렬로 실행 중인 단계에서 이 알고리즘을 호출해야 하는 경우, 태스크를 대기열에 추가해야 합니다.

사용자 에이전트가 img 요소의 이미지 데이터를 업데이트할 때, 선택적으로 애니메이션 재시작 플래그가 설정된 상태로, 또는 이벤트 생략 가능 플래그가 설정된 상태로, 다음 단계를 실행해야 합니다:

  1. 요소의 노드 문서완전히 활성화되지 않았다면:

    1. 이 알고리즘을 병렬로 계속 실행합니다.

    2. 요소의 노드 문서완전히 활성화될 때까지 기다립니다.

    3. 이 인스턴스 이후에 시작된 동일한 img 요소에 대한 다른 인스턴스(심지어 중단되었고 더 이상 실행되지 않는 경우라도)가 있다면 반환합니다.

    4. 이 알고리즘을 계속하기 위해 마이크로태스크를 대기열에 추가합니다.

  2. 사용자 에이전트가 이미지를 지원할 수 없거나 이미지 지원이 비활성화된 경우, 이미지 요청을 중단하고 현재 요청보류 중인 요청사용할 수 없음 상태로 설정하고 보류 중인 요청을 null로 설정합니다.

  3. 이전 URL현재 요청현재 URL로 설정합니다.

  4. 선택된 소스를 null로, 선택된 픽셀 밀도를 정의되지 않음으로 설정합니다.

  5. 요소가 srcset 또는 picture를 사용하지 않으며, 비어 있지 않은 src 속성이 지정된 경우, 선택된 소스를 요소의 src 속성 값으로 설정하고 선택된 픽셀 밀도를 1.0으로 설정합니다.

  6. 요소의 마지막 선택된 소스선택된 소스로 설정합니다.

  7. 선택된 소스가 null이 아닌 경우:

    1. urlString을 요소의 노드 문서를 기준으로 선택된 소스에 대한 URL 인코딩-파싱 및 직렬화의 결과로 설정합니다.

    2. urlString이 실패인 경우 이 내부 단계를 중단합니다.

    3. keyurlString, img 요소의 crossorigin 속성의 모드, 및 해당 모드가 No CORS가 아닌 경우, 요소의 노드 문서출처로 구성된 튜플로 설정합니다.

    4. 사용 가능한 이미지 목록key에 대한 항목이 포함되어 있는 경우:

      1. 해당 항목에 대해 상위 계층 캐싱 무시 플래그를 설정합니다.

      2. 이미지 요청을 중단하고 현재 요청보류 중인 요청을 중단합니다.

      3. 보류 중인 요청을 null로 설정합니다.

      4. 현재 요청을 해당 항목의 이미지 데이터로 설정하고 상태완전히 사용 가능으로 설정합니다.

      5. 프레젠테이션을 위해 현재 요청을 준비합니다.

      6. 현재 요청현재 픽셀 밀도선택된 픽셀 밀도로 설정합니다.

      7. 요소 태스크를 대기열에 추가하고 img 요소에 대해 다음 단계를 실행합니다:

        1. 애니메이션 재시작이 설정된 경우 애니메이션을 재시작합니다.

        2. 현재 요청현재 URLurlString으로 설정합니다.

        3. 이벤트 생략 가능이 설정되지 않았거나 이전 URLurlString과 같지 않은 경우 이벤트를 발생시켜 loadimg 요소에 전달합니다.

      8. 이미지 데이터 업데이트 알고리즘을 중단합니다.

  8. 마이크로태스크를 대기열에 추가하여 이 알고리즘의 나머지 부분을 수행하고, 이 알고리즘을 호출한 태스크가 계속 실행될 수 있도록 합니다.

  9. 이 알고리즘의 다른 인스턴스가 img 요소에 대해 이 인스턴스 이후에 시작되었고 (중단되었고 더 이상 실행되지 않는 경우라도) 반환합니다.

    마지막 인스턴스만 효과가 있으므로 예를 들어 src, srcset, 및 crossorigin 속성이 순차적으로 설정될 때 다중 요청을 방지할 수 있습니다.

  10. 선택된 소스선택된 픽셀 밀도를 각각 이미지 소스 선택의 결과로 설정합니다.

  11. 선택된 소스가 null인 경우:

    1. 현재 요청상태손상됨으로 설정하고, 이미지 요청을 중단합니다.

    2. 요소 태스크를 대기열에 추가하고 img 요소에 대해 다음 단계를 실행합니다:

      1. 현재 요청현재 URL을 빈 문자열로 변경합니다.

      2. 다음 조건이 모두 참인 경우:

        • 요소에 src 속성이 있거나 srcset 또는 picture를 사용하고,

        • 이벤트 생략 가능이 설정되지 않았거나 이전 URL이 빈 문자열이 아닌 경우,

        이벤트를 발생시켜 errorimg 요소에 전달합니다.

    3. 반환합니다.

  12. urlString을 요소의 노드 문서를 기준으로 선택된 소스에 대한 URL 인코딩-파싱 및 직렬화의 결과로 설정합니다.

  13. urlString이 실패인 경우:

    1. 이미지 요청을 중단하고 현재 요청보류 중인 요청을 중단합니다.

    2. 현재 요청상태손상됨으로 설정합니다.

    3. 보류 중인 요청을 null로 설정합니다.

    4. 요소 태스크를 대기열에 추가하고 img 요소에 대해 다음 단계를 실행합니다:

      1. 현재 요청현재 URL선택된 소스로 변경합니다.

      2. 이벤트 생략 가능이 설정되지 않았거나 이전 URL선택된 소스와 같지 않은 경우 이벤트를 발생시켜 errorimg 요소에 전달합니다.

    5. 반환합니다.

  14. 보류 중인 요청이 null이 아니고 urlString보류 중인 요청현재 URL과 동일한 경우 반환합니다.

  15. urlString현재 요청현재 URL과 같고 현재 요청상태부분적으로 사용 가능한 경우, 이미지 요청을 중단하고 보류 중인 요청요소 태스크를 대기열에 추가하여 애니메이션 재시작이 설정된 경우 애니메이션을 재시작하고 반환합니다.

  16. 이미지 요청을 중단합니다.

  17. 이미지 요청새 이미지 요청으로 설정하고 현재 URLurlString으로 설정합니다.

  18. 만약 현재 요청상태사용 불가 또는 손상됨이라면, 현재 요청이미지 요청으로 설정하십시오. 그렇지 않으면, 보류 중인 요청이미지 요청으로 설정하십시오.

  19. 요청잠재적 CORS 요청 만들기의 결과로 설정하고 urlString, "image" 및 요소의 crossorigin 속성의 현재 상태를 사용합니다.

  20. 요청클라이언트를 요소의 노드 문서관련 설정 객체로 설정합니다.

  21. 요소가 srcset 또는 picture를 사용하는 경우, 요청이니시에이터를 "imageset"으로 설정합니다.

  22. 요청참조 정책을 요소의 referrerpolicy 속성의 현재 상태로 설정합니다.

  23. 요청우선순위를 요소의 fetchpriority 속성의 현재 상태로 설정합니다.

  24. 로드 이벤트 지연img게으른 로딩 속성적극적 상태에 있거나 스크립팅이 비활성화된 경우 true로, 그렇지 않으면 false로 설정합니다.

  25. img에 대해 요소가 게으르게 로드될 것인지 여부 결정 단계가 true를 반환하는 경우:

    1. img게으른 로드 재개 단계를 이 알고리즘의 나머지 부분으로 설정하고 이미지 가져오기 단계를 시작합니다.

    2. 게으르게 로드되는 요소의 교차 관찰 시작img 요소에 대해 실행합니다.

    3. 반환합니다.

  26. 이미지 가져오기: 가져오기 요청. 이 알고리즘을 반환하고 나머지 단계를 응답에 대해 응답 처리의 일부로 실행합니다.

    이 방식으로 획득된 리소스가 있다면, 이는 이미지 요청이미지 데이터입니다. 이는 CORS-동일 출처이거나 CORS-교차 출처일 수 있으며, 이는 이미지의 다른 API와의 상호작용에 영향을 미칩니다 (예: 캔버스에서 사용될 때).

    로드 이벤트 지연이 true일 때, 이미지를 가져오면 요소의 노드 문서의 로드 이벤트를 지연시켜야 하며, 이는 리소스가 가져온 후 네트워킹 태스크 소스에 의해 대기열에 추가된 태스크가 실행될 때까지 지연됩니다.

    이 불행히도 사용자의 로컬 네트워크에 대한 간단한 포트 스캔을 수행하는 데 사용할 수 있습니다 (특히 스크립팅과 함께 사용하면, 비록 스크립팅이 실제로 이러한 공격을 수행하는 데 필요하지 않더라도). 사용자 에이전트는 이러한 공격을 완화하기 위해 이보다 엄격한 교차 출처 접근 제어 정책을 구현할 수 있지만, 불행히도 그러한 정책은 기존 웹 콘텐츠와 호환되지 않는 경우가 많습니다.

  27. 가능한 한 빨리 다음 목록의 첫 번째 적용 가능한 항목으로 이동합니다:

    리소스 유형이 multipart/x-mixed-replace인 경우

    이미지가 가져오는 동안 대기열에 추가된 다음 태스크는 다음 단계를 실행해야 합니다:

    1. 만약 이미지 요청보류 중인 요청이며 적어도 하나의 본문 부분이 완전히 디코딩되었다면, 현재 요청에 대한 이미지 요청을 중단하고, 보류 중인 요청을 현재 요청으로 업그레이드하십시오.

    2. 그렇지 않고, 만약 이미지 요청보류 중인 요청이며 사용자 에이전트가 이미지 요청의 이미지가 치명적인 방식으로 손상되어 이미지 크기를 얻을 수 없음을 판단할 수 있는 경우, 현재 요청에 대한 이미지 요청을 중단하고, 보류 중인 요청을 현재 요청으로 업그레이드하며, 현재 요청상태손상됨으로 설정하십시오.

    3. 그렇지 않고, 만약 이미지 요청현재 요청이며, 그 상태사용 불가이고, 사용자 에이전트가 이미지 요청의 이미지의 너비와 높이를 판단할 수 있다면, 현재 요청상태부분적으로 사용 가능으로 설정하십시오.

    4. 그렇지 않고, 만약 이미지 요청현재 요청이며, 그 상태사용 불가이고, 사용자 에이전트가 이미지 요청의 이미지가 치명적인 방식으로 손상되어 이미지 크기를 얻을 수 없음을 판단할 수 있는 경우, 현재 요청상태손상됨으로 설정하십시오.

    이미지가 가져오는 중일 때 네트워킹 작업 소스에 의해 대기열에 추가된작업은 이미지의 표현을 업데이트해야 합니다. 그러나 새로운 본문 부분이 들어올 때마다 사용자 에이전트가 이미지의 너비와 높이를 결정할 수 있다면, img 요소를 제공하기 위해 현재 요청을 준비하고 이전 이미지를 교체해야 합니다. 하나의 본문 부분이 완전히 디코딩되면 다음 단계를 수행하십시오:

    1. img 요소의 현재 요청상태완전히 사용 가능으로 설정합니다.

    2. 이벤트 생략 가능이 설정되지 않았거나 이전 URLurlString과 같지 않은 경우, 요소 태스크를 대기열에 추가하고 img 요소에 대해 이벤트를 발생시켜 load를 전달합니다.

    그렇지 않으면

    이미지 데이터가 지원되는 파일 형식이 아닌 경우, 사용자 에이전트는 이미지 요청상태손상됨으로 설정하고, 현재 요청보류 중인 요청을 중단하고, 보류 중인 요청을 현재 요청으로 업그레이드한 다음, 이벤트 생략 가능이 설정되지 않았거나 이전 URLurlString과 같지 않은 경우 요소 태스크를 대기열에 추가하고 img 요소에 대해 이벤트를 발생시켜 error를 전달합니다.

사용자 에이전트가 요소 x에 대해 위 알고리즘을 실행하는 동안, 요소가 연결된 상태가 아닌 경우에도 요소 x에 대한 강한 참조가 요소의 노드 문서에서 유지되어야 합니다.

이미지 요청 또는 null 이미지 요청에 대해 이미지 요청을 중단하는 것은 다음 단계를 실행하는 것을 의미합니다:

  1. 이미지 요청이 null이면 반환합니다.

  2. 가능하면 이미지 요청이미지 데이터를 잊어버립니다.

  3. 이미지 요청에 대해 가져오기 알고리즘의 모든 인스턴스를 중단하고 해당 알고리즘에서 생성된 보류 중인 모든 태스크를 삭제합니다.

img 요소에 대해 대기 중인 요청을 현재 요청으로 업그레이드한다는 것은 다음 단계를 실행하는 것을 의미합니다:

  1. img 요소의 현재 요청보류 중인 요청으로 설정합니다.

  2. img 요소의 보류 중인 요청을 null로 설정합니다.

4.8.4.3.6 프레젠테이션을 위한 이미지 준비

이미지 요소 img에 대해 이미지 요청 req을(를) 주어진 프레젠테이션을 위해 이미지를 준비하려면:

  1. exifTagMapreq이미지 데이터에서 얻은 EXIF 태그로 설정합니다. 이는 관련 코덱에 의해 정의됩니다. [EXIF]

  2. physicalWidthphysicalHeight을(를) req이미지 데이터에서 얻은 너비와 높이로 설정합니다. 이는 관련 코덱에 의해 정의됩니다.

  3. dimXexifTagMap의 태그 0xA002 (PixelXDimension)의 값으로 설정합니다.

  4. dimYexifTagMap의 태그 0xA003 (PixelYDimension)의 값으로 설정합니다.

  5. resXexifTagMap의 태그 0x011A (XResolution)의 값으로 설정합니다.

  6. resYexifTagMap의 태그 0x011B (YResolution)의 값으로 설정합니다.

  7. resUnitexifTagMap의 태그 0x0128 (ResolutionUnit)의 값으로 설정합니다.

  8. dimX 또는 dimY 중 하나라도 양의 정수가 아닌 경우, 반환합니다.

  9. resX 또는 resY 중 하나라도 양의 부동 소수점 숫자가 아닌 경우, 반환합니다.

  10. resUnit2 (Inch)와 같지 않으면 반환합니다.

  11. widthFromDensityphysicalWidth의 값에 72를 곱하고 resX로 나눈 값으로 설정합니다.

  12. heightFromDensityphysicalHeight의 값에 72를 곱하고 resY로 나눈 값으로 설정합니다.

  13. widthFromDensitydimX과 같지 않거나 heightFromDensitydimY와 같지 않으면 반환합니다.

  14. req이미지 데이터CORS-교차 출처이면, img자연 치수dimXdimY로 설정하고, img의 픽셀 데이터를 적절히 스케일링하고 반환합니다.

  15. req선호하는 밀도 보정 치수를 폭을 dimX로, 높이를 dimY로 설정된 구조체로 설정합니다.

  16. reqimg 요소의 프레젠테이션을 적절하게 업데이트합니다.

EXIF의 해상도는 CSS 포인트 당 인치와 동등하므로, 72는 해상도에서 크기를 계산하기 위한 기본값입니다.

이미지가 이미 프레젠테이션된 후에 EXIF가 도착하는 경우에 대해 아직 명확하게 지정되지 않았습니다. 참조 이슈 #4929.

4.8.4.3.7 이미지 소스 선택

이미지 요소 el에 대해 img 요소를 주어진 이미지 소스 선택하려면:

  1. el에 대한 소스 세트 업데이트를 수행합니다.

  2. el소스 세트가 비어 있으면, URL로 null을 반환하고 픽셀 밀도로 undefined를 반환합니다.

  3. el소스 세트에서 이미지 소스를 선택한 결과를 반환합니다.

소스 세트 sourceSet에 대해 이미지 소스를 선택하려면:

  1. 만약 sourceSet에 있는 항목 bsourceSet의 이전 항목 a와 동일한 관련 픽셀 밀도 디스크립터를 갖고 있다면, 항목 b를 제거합니다. sourceSet에 있는 항목들이 더 이상 이전 항목과 동일한 관련 픽셀 밀도 디스크립터를 갖지 않을 때까지 이 단계를 반복합니다.

  2. 구현에 정의된 방식으로 sourceSet에서 하나의 이미지 소스를 선택합니다. 이를 selectedSource로 합니다.

  3. selectedSource와 그에 연관된 픽셀 밀도를 반환합니다.

4.8.4.3.8 속성에서 소스 세트 생성

문자열 기본 소스, 문자열 srcset, 문자열 sizes, 요소 또는 null img이 주어졌을 때 소스 세트 생성을 요청받으면:

  1. source set을 빈 소스 세트로 설정합니다.

  2. srcset이 빈 문자열이 아닌 경우, source setsrcset파싱한 결과로 설정합니다.

  3. 소스 크기img와 함께 sizes파싱한 결과로 설정합니다.

  4. 기본 소스가 빈 문자열이 아니고, source set에 픽셀 밀도 디스크립터 값이 1인 이미지 소스너비 디스크립터가 포함되지 않은 경우, 기본 소스source set에 추가합니다.

  5. source set소스 밀도를 정규화합니다.

  6. source set을 반환합니다.

4.8.4.3.9 소스 세트 업데이트

주어진 img 또는 link 요소 el에 대해 소스 세트를 업데이트하도록 요청받으면, 사용자 에이전트는 다음을 수행해야 합니다:

  1. el소스 세트를 빈 소스 세트로 설정합니다.

  2. elements에 « el »을(를) 할당합니다.

  3. 만약 el이(가) picture 요소의 자식인 img 요소라면, elements의 내용을 el의 부모 노드의 자식 요소들로 교체하고, 상대적인 순서를 유지합니다.

  4. imgel을 할당합니다. 만약 el이(가) img 요소가 아니라면 null을 할당합니다.

  5. child에 대해 elements에서 다음을 수행합니다:

    1. 만약 childel과 동일하다면:

      1. default source를 빈 문자열로 설정합니다.

      2. srcset을 빈 문자열로 설정합니다.

      3. sizes을 빈 문자열로 설정합니다.

      4. 만약 el이(가) img 요소이고 srcset 속성을 가지고 있다면, srcset을 해당 속성의 값으로 설정합니다.

      5. 그렇지 않고, el이(가) link 요소이고 imagesrcset 속성을 가지고 있다면, srcset을 해당 속성의 값으로 설정합니다.

      6. 만약 el이(가) img 요소이고 sizes 속성을 가지고 있다면, sizes을 해당 속성의 값으로 설정합니다.

      7. 그렇지 않고, el이(가) link 요소이고 imagesizes 속성을 가지고 있다면, sizes을 해당 속성의 값으로 설정합니다.

      8. 만약 el이(가) img 요소이고 src 속성을 가지고 있다면, default source를 해당 속성의 값으로 설정합니다.

      9. 그렇지 않고, el이(가) link 요소이고 href 속성을 가지고 있다면, default source를 해당 속성의 값으로 설정합니다.

      10. el소스 세트default source, srcset, sizes, 그리고 img을 사용하여 소스 세트 생성의 결과로 설정합니다.

      11. 반환합니다.

        만약 el이(가) link 요소라면, elements에는 오직 el만 포함되므로, 이 단계가 즉시 도달되고 나머지 알고리즘은 실행되지 않습니다.

    2. 만약 childsource 요소가 아니라면, 다음으로 넘어갑니다.

    3. 만약 childsrcset 속성을 가지고 있지 않다면, 다음으로 넘어갑니다.

    4. child의 srcset 속성을 파싱하고, 반환된 소스 세트source set으로 설정합니다.

    5. 만약 source set이(가) 0개의 이미지 소스를 가지고 있다면, 다음으로 넘어갑니다.

    6. 만약 childmedia 속성을 가지고 있으며, 그 값이 환경과 일치하지 않으면, 다음으로 넘어갑니다.

    7. child의 sizes 속성을 파싱하고, img을 사용하여 source set소스 크기를 반환된 값으로 설정합니다.

    8. 만약 childtype 속성을 가지고 있으며, 그 값이 알 수 없거나 지원되지 않는 MIME 타입이라면, 다음으로 넘어갑니다.

    9. 만약 childwidth 또는 height 속성을 가지고 있다면, el크기 속성 소스child로 설정합니다. 그렇지 않으면, el크기 속성 소스el로 설정합니다.

    10. 소스 밀도를 정규화합니다 source set의.

    11. el소스 세트source set으로 설정합니다.

    12. 반환합니다.

img 요소는 독립적으로 이전 형제 source 요소와 img 요소 자체를 고려하여 이미지 소스를 선택하며, 동일한 picture 요소 내의 다른 img 요소나 source 요소와 같은 무효한 요소는 무시합니다.

4.8.4.3.10 srcset 속성 파싱

요소에서 srcset 속성을 파싱하도록 요청받았을 때, 요소의 srcset 속성 값을 다음과 같이 파싱합니다:

  1. input을 이 알고리즘에 전달된 값으로 설정합니다.

  2. positioninput의 시작을 가리키는 포인터로 설정합니다.

  3. candidates를 초기에는 빈 소스 세트로 설정합니다.

  4. 분할 루프: position을 기준으로 input에서 ASCII 공백 문자 또는 U+002C 쉼표 문자를 포함하는 코드 포인트 시퀀스를 수집합니다. U+002C 쉼표 문자가 수집된 경우, 이는 파싱 오류입니다.

  5. positioninput의 끝을 넘어서면 candidates를 반환합니다.

  6. position을 기준으로 input에서 ASCII 공백 문자가 아닌 코드 포인트 시퀀스를 수집하고, 이를 url로 설정합니다.

  7. descriptors를 새로운 빈 목록으로 설정합니다.

  8. 만약 url이 U+002C 쉼표로 끝난다면:

    1. url에서 모든 U+002C 쉼표 문자를 제거합니다. 만약 이 과정에서 하나 이상의 문자가 제거되었다면, 이는 파싱 오류입니다.

    그렇지 않다면:

    1. 기술자 토크나이저: position을 기준으로 input 내의 ASCII 공백 문자를 건너뜁니다.

    2. current descriptor를 빈 문자열로 설정합니다.

    3. state기술자 내로 설정합니다.

    4. cposition에서의 문자로 설정합니다. state의 값에 따라 다음을 수행합니다. 이 단계에서는 "EOF"가 input의 끝을 넘어선 position을 나타내는 특수 문자임을 의미합니다.

      기술자 내

      c의 값에 따라 다음을 수행합니다:

      ASCII 공백 문자

      만약 current descriptor가 비어 있지 않다면, current descriptordescriptors에 추가하고, current descriptor를 빈 문자열로 설정합니다. state기술자 후로 설정합니다.

      U+002C 쉼표 (,)

      positioninput의 다음 문자로 이동합니다. 만약 current descriptor가 비어 있지 않다면, 이를 descriptors에 추가합니다. 기술자 파서 단계로 이동합니다.

      U+0028 왼쪽 괄호 (()

      ccurrent descriptor에 추가합니다. state괄호 내로 설정합니다.

      EOF

      만약 current descriptor가 비어 있지 않다면, 이를 descriptors에 추가합니다. 기술자 파서 단계로 이동합니다.

      기타

      ccurrent descriptor에 추가합니다.

      괄호 내

      c의 값에 따라 다음을 수행합니다:

      U+0029 오른쪽 괄호 ())

      ccurrent descriptor에 추가합니다. state기술자 내로 설정합니다.

      EOF

      current descriptordescriptors에 추가합니다. 기술자 파서 단계로 이동합니다.

      기타

      ccurrent descriptor에 추가합니다.

      기술자 후

      c의 값에 따라 다음을 수행합니다:

      ASCII 공백 문자

      이 상태를 유지합니다.

      EOF

      기술자 파서 단계로 이동합니다.

      기타

      state기술자 내로 설정합니다. positioninput이전 문자로 설정합니다.

      positioninput의 다음 문자로 이동합니다. 이 단계를 반복합니다.

      향후 추가 사항과의 호환성을 위해, 이 알고리즘은 다중 기술자와 괄호를 포함한 기술자를 지원합니다.

  9. 기술자 파서: error아니오로 설정합니다.

  10. width없음으로 설정합니다.

  11. density없음으로 설정합니다.

  12. future-compat-h없음으로 설정합니다.

  13. descriptors의 각 기술자에 대해 다음 목록에서 적절한 단계를 실행합니다:

    기술자가 유효한 음수가 아닌 정수와 U+0077 라틴 소문자 W 문자로 구성된 경우
    1. 만약 사용자 에이전트가 sizes 속성을 지원하지 않는 경우, error로 설정합니다.

      규격 준수 사용자 에이전트는 sizes 속성을 지원합니다. 그러나, 사용자 에이전트는 실습에서 점진적으로 기능을 구현하고 배포하는 경향이 있습니다.

    2. 만약 widthdensity가 모두 없음이 아니라면, error로 설정합니다.

    3. 기술자에 음수가 아닌 정수 파싱 규칙을 적용합니다. 결과가 0이라면, error로 설정합니다. 그렇지 않으면, width를 그 결과로 설정합니다.

    기술자가 유효한 부동소수점 숫자와 U+0078 라틴 소문자 X 문자로 구성된 경우
    1. 만약 width, density, 그리고 future-compat-h가 모두 없음이 아니라면, error로 설정합니다.

    2. 기술자에 부동소수점 숫자 값 파싱 규칙을 적용합니다. 결과가 0보다 작다면, error로 설정합니다. 그렇지 않으면, density를 그 결과로 설정합니다.

      만약 density가 0이라면, 자연 치수는 무한대가 됩니다. 사용자 에이전트는 이미지를 렌더링할 수 있는 크기에 제한을 둘 것으로 예상됩니다.

    기술자가 유효한 음수가 아닌 정수와 U+0068 라틴 소문자 H 문자로 구성된 경우

    이는 파싱 오류입니다.

    1. 만약 future-compat-hdensity가 모두 없음이 아니라면, error로 설정합니다.

    2. 기술자에 음수가 아닌 정수 파싱 규칙을 적용합니다. 결과가 0이라면, error로 설정합니다. 그렇지 않으면, future-compat-h를 그 결과로 설정합니다.

    기타

    error로 설정합니다.

  14. 만약 future-compat-h없음이 아니고 width없음이라면, error로 설정합니다.

  15. 만약 error가 여전히 아니오라면, 새로운 이미지 소스candidates에 추가하며, URL을 url로, width가 없음이 아니라면 width로, density가 없음이 아니라면 pixel density로 설정합니다. 그렇지 않으면, 이는 파싱 오류입니다.

  16. 분할 루프 단계로 돌아갑니다.

4.8.4.3.11 sizes 속성 파싱

요소 element에서 img 요소 또는 null img와 함께 sizes 속성을 파싱하도록 요청받았을 때:

  1. unparsed sizes listelementsizes 속성 값(또는 속성이 없는 경우 빈 문자열)에서 쉼표로 구분된 구성 요소 값 목록 파싱의 결과로 설정합니다. [CSSSYNTAX]

  2. size를 null로 설정합니다.

  3. unparsed sizes list 내의 각 unparsed size에 대해:

    1. unparsed size의 끝에서 모든 연속된 <whitespace-token>을 제거합니다. unparsed size가 이제 비어 있다면, 이는 파싱 오류입니다. 계속합니다.

    2. 만약 unparsed size의 마지막 구성 요소 값이 유효한 음수가 아닌 <source-size-value>라면, size를 그 값으로 설정하고 unparsed size에서 구성 요소 값을 제거합니다. 수학 함수 이외의 CSS 함수는 유효하지 않습니다. 그렇지 않으면, 이는 파싱 오류입니다. 계속합니다.

    3. 만약 sizeauto이고, img가 null이 아니며, img렌더링 중이고, imgauto-sizes를 허용한다면, sizeimg구체적 객체 크기 너비로, CSS 픽셀 단위로 설정합니다.

      만약 size가 여전히 auto라면, 이는 무시됩니다.

    4. unparsed size의 끝에서 모든 연속된 <whitespace-token>을 제거합니다. unparsed size가 이제 비어 있다면:

      1. 만약 이것이 unparsed sizes list의 마지막 항목이 아니었다면, 이는 파싱 오류입니다.

      2. 만약 sizeauto가 아니라면, size를 반환합니다. 그렇지 않으면, 계속합니다.

    5. unparsed size의 남은 구성 요소 값<media-condition>으로 파싱합니다. 올바르게 파싱되지 않거나, 올바르게 파싱되었지만 <media-condition>이 false로 평가된다면, 계속합니다. [MQ]

    6. 만약 sizeauto가 아니라면, size를 반환합니다. 그렇지 않으면, 계속합니다.

  4. 100vw를 반환합니다.

마지막 항목이 아닌 <source-size-list><source-size-value><length>인 경우, 동반되는 <media-condition> 없이 단독으로 사용하는 것은 유효하지 않습니다. 그러나, 파싱 알고리즘은 리스트의 어느 지점에서도 이를 허용하며, 리스트의 이전 항목들이 사용되지 않았다면 즉시 이를 사이즈로 수락합니다. 이는 향후 확장을 가능하게 하고, 최종 쉼표와 같은 단순한 작성자 오류로부터 보호하기 위함입니다. auto 키워드는 다른 항목들이 뒤따라와 레거시 사용자 에이전트를 위한 폴백을 제공하는 것이 허용됩니다.

4.8.4.3.12 소스 밀도 정규화

이미지 소스픽셀 밀도 설명자, 너비 설명자, 또는 설명자 없이 URL과 함께 제공될 수 있습니다. 소스 세트를 정규화하면 모든 이미지 소스픽셀 밀도 설명자를 부여합니다.

소스 세트의 밀도를 정규화하라는 요청을 받으면, 사용자 에이전트는 다음을 수행해야 합니다:

  1. source set소스 크기source size로 설정합니다.

  2. source set 내의 각 이미지 소스에 대해:

    1. 만약 이미지 소스픽셀 밀도 설명자를 가지고 있다면, 다음 이미지 소스계속합니다.

    2. 그렇지 않고 이미지 소스너비 설명자를 가지고 있다면, 너비 설명자픽셀 밀도 설명자로 대체합니다. 값은 너비 설명자 값소스 크기로 나눈 값이며 단위는 x입니다.

      만약 소스 크기가 0이면, 밀도는 무한대가 되어, 자연 크기가 0 x 0이 됩니다.

    3. 그렇지 않으면, 이미지 소스1x픽셀 밀도 설명자를 부여합니다.

4.8.4.3.13 환경 변화에 대응

사용자 에이전트는 img 요소의 이미지를 업데이트하여 환경 변화에 대응하기 위해 언제든지 다음 알고리즘을 실행할 수 있습니다. (사용자 에이전트가 이 알고리즘을 실행해야 할 의무는 없습니다. 예를 들어, 사용자가 더 이상 페이지를 보지 않는 경우, 환경이 다시 변할 수 있으므로 사용자가 페이지로 돌아올 때까지 어떤 이미지를 사용할지 결정하는 것을 연기할 수 있습니다.)

사용자 에이전트는 특히 사용자가 뷰포트 크기를 변경할 때(예: 창 크기를 조정하거나 페이지 확대/축소를 변경할 때)와 img 요소가 문서에 삽입될 때 이 알고리즘을 실행하여 밀도 보정된 자연 너비와 높이가 새로운 뷰포트와 일치하고, 아트 디렉션이 포함된 경우 올바른 이미지가 선택되도록 할 것을 권장합니다.

  1. 안정 상태 대기를 수행합니다. 동기식 섹션은 이 알고리즘의 나머지 모든 단계를 포함하며 알고리즘이 동기식 섹션이 종료되었다고 말할 때까지 계속됩니다. (동기식 섹션의 단계는 ⌛로 표시됩니다.)

  2. img 요소가 srcset 또는 picture를 사용하지 않거나, 노드 문서완전히 활성화되지 않음 상태이거나, 이미지 데이터의 리소스 타입이 multipart/x-mixed-replace이거나, 보류 중인 요청이 null이 아닌 경우, 반환합니다.

  3. 이미지 소스 선택에서 URL과 픽셀 밀도로부터 선택된 소스선택된 픽셀 밀도를 얻습니다.

  4. 선택된 소스가 null인 경우, 반환합니다.

  5. 선택된 소스선택된 픽셀 밀도가 요소의 마지막 선택된 소스현재 픽셀 밀도와 동일한 경우, 반환합니다.

  6. URL 인코딩, 파싱 및 직렬화 결과를 사용하여 urlString을 설정합니다.

  7. urlString이 실패한 경우, 반환합니다.

  8. ⌛ 요소의 crossorigin 콘텐츠 속성의 상태를 corsAttributeState로 설정합니다.

  9. img 요소의 노드 문서원본origin으로 설정합니다.

  10. img 요소의 노드 문서관련 설정 객체client로 설정합니다.

  11. keyurlString, corsAttributeState, 및 corsAttributeStateNo CORS가 아닌 경우 origin을 포함하는 튜플로 설정합니다.

  12. urlStringcurrent URL로 가지는 새로운 이미지 요청image request로 설정합니다.

  13. ⌛ 요소의 보류 중인 요청image request로 설정합니다.

  14. 동기식 섹션을 종료하고 나머지 단계를 병렬로 계속합니다.

  15. 사용 가능한 이미지 목록key의 항목이 포함되어 있는 경우, image request이미지 데이터를 항목의 데이터로 설정합니다. 다음 단계로 진행합니다.

    그렇지 않으면:

    1. 잠재적 CORS 요청 생성 결과를 request로 설정하고, urlString, "image", 및 corsAttributeState를 사용합니다.

    2. request클라이언트client로, 이니시에이터를 "imageset"로 설정하고, request동기 플래그를 설정합니다.

    3. 요소의 referrerpolicy 속성의 현재 상태를 requestreferrer policy로 설정합니다.

    4. 요소의 fetchpriority 속성의 현재 상태를 request우선순위로 설정합니다.

    5. fetch를 사용하여 requestresponse를 가져옵니다.

    6. 만약 response안전하지 않은 응답네트워크 오류이거나, 이미지 형식이 지원되지 않거나, image request의 이미지가 치명적인 방식으로 손상되어 이미지 크기를 얻을 수 없거나, 리소스 타입이 multipart/x-mixed-replace인 경우, 보류 중인 요청을 null로 설정하고 이 단계를 중단합니다.

    7. 그렇지 않으면, response안전하지 않은 응답image request이미지 데이터로 설정합니다. 이는 CORS 동일 출처 또는 CORS 교차 출처일 수 있으며, 이는 다른 API와의 상호작용에 영향을 미칩니다 (예: 캔버스에서 사용될 때).

  16. 요소 작업 대기열에 추가를 수행하여 img 요소와 다음 단계를 설정합니다:

    1. 만약 img 요소가 이 알고리즘이 시작된 이후 관련 변형을 경험했다면, 보류 중인 요청을 null로 설정하고 이 단계를 중단합니다.

    2. img 요소의 마지막 선택된 소스선택된 소스로, img 요소의 현재 픽셀 밀도선택된 픽셀 밀도로 설정합니다.

    3. image request상태완전히 사용 가능으로 설정합니다.

    4. key를 사용하여 이미지를 사용 가능한 이미지 목록에 추가하고, 상위 계층 캐싱 무시 플래그를 설정합니다.

    5. 보류 중인 요청을 현재 요청으로 업그레이드합니다.

    6. img 요소를 사용하여 이미지 요청을 발표를 위해 준비합니다.

    7. 이벤트를 발생시켜 로드라는 이름의 이벤트를 img 요소에 전달합니다.

4.8.4.4 이미지의 대체 텍스트를 제공하기 위한 요구 사항
4.8.4.4.1 일반적인 지침

별도로 명시되지 않은 경우, alt 속성은 반드시 지정되어야 하며, 그 값은 비어있어서는 안 됩니다. 이 값은 이미지의 적절한 대체물이 되어야 합니다. alt 속성에 대한 구체적인 요구 사항은 이미지가 표현하려는 의도에 따라, 다음 섹션에서 설명된 바와 같이 달라집니다.

대체 텍스트를 작성할 때 고려해야 할 가장 일반적인 규칙은 다음과 같습니다: 모든 이미지를 alt 속성의 텍스트로 교체해도 페이지의 의미가 변경되지 않도록 하는 것이 목적입니다.

따라서 일반적으로 대체 텍스트는 이미지를 포함할 수 없었을 때 작성했을 내용을 고려하여 작성할 수 있습니다.

이와 연관된 또 다른 규칙은 alt 속성의 값은 절대로 이미지의 캡션, 제목, 또는 설명으로 간주될 수 있는 텍스트를 포함해서는 안 된다는 것입니다. 이 속성은 사용자가 이미지를 대신하여 사용할 수 있는 대체 텍스트를 포함해야 하며, 이미지를 보완하기 위한 것이 아닙니다. 보완적인 정보가 필요하다면 title 속성을 사용할 수 있습니다.

또 다른 관련 규칙은 alt 속성의 값이 이미지 옆에 있는 본문에 이미 제공된 정보를 반복해서는 안 된다는 것입니다.

대체 텍스트를 생각하는 한 가지 방법은 이미지를 포함한 페이지를 누군가에게 전화로 설명한다고 생각하는 것입니다. 이미지가 있다는 사실을 언급하지 않고 페이지를 읽어주었을 때 사용하는 말이 일반적으로 대체 텍스트를 작성하는 좋은 출발점입니다.

하나 이상의 이미지를 포함하지만 텍스트 콘텐츠는 없는 a 요소가 하이퍼링크를 생성하거나, button 요소인 경우, alt 속성에는 링크나 버튼의 목적을 함께 전달하는 텍스트가 포함되어야 합니다.

이 예시에서는 사용자가 세 가지 색상 목록에서 선호하는 색상을 선택하도록 요청받습니다. 각 색상은 이미지로 제공되지만, 이미지를 표시하지 않도록 설정된 사용자 에이전트에서는 색상 이름이 대신 사용됩니다:

<h1>색상을 선택하세요</h1>
<ul>
 <li><a href="green.html"><img src="green.jpeg" alt="Green"></a></li>
 <li><a href="blue.html"><img src="blue.jpeg" alt="Blue"></a></li>
 <li><a href="red.html"><img src="red.jpeg" alt="Red"></a></li>
</ul>

이 예시에서는 각 버튼에 사용자가 원하는 색상 출력을 나타내는 이미지 세트가 있습니다. 각 경우에 첫 번째 이미지는 대체 텍스트를 제공합니다.

<button name="rgb"><img src="red" alt="RGB"><img src="green" alt=""><img src="blue" alt=""></button>
<button name="cmyk"><img src="cyan" alt="CMYK"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>

각 이미지가 텍스트의 일부를 나타내므로, 이렇게도 작성할 수 있습니다:

<button name="rgb"><img src="red" alt="R"><img src="green" alt="G"><img src="blue" alt="B"></button>
<button name="cmyk"><img src="cyan" alt="C"><img src="magenta" alt="M"><img src="yellow" alt="Y"><img src="black" alt="K"></button>

그러나 다른 대체 텍스트와 함께 사용할 경우에는 이 방법이 효과적이지 않을 수 있으며, 각 경우에 대체 텍스트를 한 이미지에 포함시키는 것이 더 나을 수 있습니다:

<button name="rgb"><img src="red" alt="sRGB profile"><img src="green" alt=""><img src="blue" alt=""></button>
<button name="cmyk"><img src="cyan" alt="CMYK profile"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>
4.8.4.4.3 대체 그래픽 표현을 가진 문구나 단락: 차트, 다이어그램, 그래프, 지도, 일러스트레이션

때때로 흐름도, 다이어그램, 그래프, 또는 방향을 보여주는 간단한 지도와 같은 그래픽 형식으로 더 명확하게 설명할 수 있습니다. 이러한 경우, img 요소를 사용하여 이미지를 제공할 수 있지만, 느린 연결 속도, 텍스트 전용 브라우저 사용, 손이 자유롭지 않은 자동차 음성 웹 브라우저를 사용하거나 단순히 시각장애인인 경우와 같은 이미지 표시가 불가능한 사용자를 위해 텍스트 버전도 제공되어야 합니다.

텍스트는 alt 속성에 제공되어야 하며, src 속성에 지정된 이미지와 동일한 메시지를 전달해야 합니다.

대체 텍스트는 이미지에 대한 설명이 아닌, 이미지의 대체물이라는 것을 이해하는 것이 중요합니다.

다음 예제에서는 이미지 형식의 흐름도가 있으며, alt 속성에 흐름도를 텍스트로 재구성한 내용이 있습니다:

<p>일반적인 경우, 토큰화 단계에서 처리하는 데이터는 네트워크에서 오지만, 스크립트에서도 올 수 있습니다.</p>
<p><img src="images/parsing-model-overview.svg" alt="네트워크는 데이터를 입력 스트림 전처리기로 전달하고, 전처리기는 데이터를 토큰화기로 전달합니다. 토큰화기는 데이터를 트리 구성 단계로 전달하며, 여기서 데이터는 DOM과 스크립트 실행으로 전달됩니다. 스크립트 실행은 DOM과 연결되며, document.write()를 사용하여 데이터를 토큰화기로 전달합니다."></p>

다음은 설명에 이미지를 포함시키는 문제에 대한 좋은 해결책과 나쁜 해결책을 보여주는 또 다른 예입니다.

먼저, 좋은 해결책입니다. 이 샘플은 이미지가 처음부터 존재하지 않았던 것처럼 대체 텍스트를 작성하는 방법을 보여줍니다.

<!-- 이것은 올바른 방법입니다. -->
<p>
 당신은 집 서쪽에 있는 열린 들판에 서 있습니다.
 <img src="house.jpeg" alt="그 집은 흰색이며, 앞문은 판자로 덮여 있습니다.">
 작은 우편함이 있습니다.
</p>

다음으로 나쁜 해결책입니다. 이 잘못된 방법에서는 대체 텍스트가 이미지에 대한 단순한 설명일 뿐, 이미지의 텍스트 대체물이 아닙니다. 이 방법이 나쁜 이유는 이미지가 표시되지 않을 때 텍스트의 흐름이 첫 번째 예제만큼 자연스럽지 않기 때문입니다.

<!-- 이것은 잘못된 방법입니다. -->
<p>
 당신은 집 서쪽에 있는 열린 들판에 서 있습니다.
 <img src="house.jpeg" alt="하얀색 집, 판자로 덮인 앞문.">
 작은 우편함이 있습니다.
</p>

"판자로 덮인 하얀색 집 사진"과 같은 텍스트도 역시 나쁜 대체 텍스트가 될 것입니다(비록 title 속성이나 figcaption 요소에 적합할 수는 있지만).

4.8.4.4.4 대체 그래픽 표현을 가진 짧은 구절이나 레이블: 아이콘, 로고

문서는 아이콘 형태로 정보를 포함할 수 있습니다. 아이콘은 시각적 브라우저 사용자들이 한눈에 특징을 인식하도록 돕기 위한 것입니다.

일부 경우, 아이콘은 동일한 의미를 전달하는 텍스트 레이블을 보조하는 역할을 합니다. 이러한 경우, alt 속성이 있어야 하지만, 그 값은 비워져 있어야 합니다.

여기서 아이콘은 동일한 의미를 전달하는 텍스트 옆에 있기 때문에, alt 속성은 비어 있습니다:

<nav>
 <p><a href="/help/"><img src="/icons/help.png" alt=""> 도움말</a></p>
 <p><a href="/configure/"><img src="/icons/configuration.png" alt=""> 설정 도구</a></p>
</nav>

다른 경우에는, 아이콘에 그 의미를 설명하는 텍스트가 옆에 없으며, 아이콘이 자체적으로 설명되어야 합니다. 이러한 경우, alt 속성에 해당하는 텍스트 레이블을 제공해야 합니다.

여기서는 뉴스 사이트의 게시물이 주제를 나타내는 아이콘으로 레이블이 지정되었습니다.

<body>
 <article>
  <header>
   <h1>라따뚜이, <i>올해의 영화</i> 수상</h1>
   <p><img src="movies.png" alt="영화"></p>
  </header>
  <p>픽사는 지난 12년 동안 8번이나 <i>올해의 영화</i> 상을 수상했습니다.</p>
 </article>
 </article>
  <header>
   <h1>최신 TWiT 에피소드가 온라인에 게시됨</h1>
   <p><img src="podcasts.png" alt="팟캐스트"></p>
  </header>
  </p>최신 TWiT 에피소드가 게시되었으며, 여기에서 여러 기술 뉴스 이야기를 듣고, iPhone에 대해 더 많은 정보를 배울 수 있습니다. 이번 주에 패널들은 iPhone의 애플 로고가 얼마나 반사되는지를 비교합니다.</p>
 </article>
</body>

많은 페이지에는 회사, 조직, 프로젝트, 밴드, 소프트웨어 패키지, 국가 등의 특정 엔티티를 나타내는 로고, 배지, 깃발 또는 상징이 포함되어 있습니다.

로고가 해당 엔티티를 대표하는 데 사용되는 경우(예: 페이지 헤딩으로 사용되는 경우), alt 속성에는 로고가 나타내는 엔티티의 이름이 포함되어야 합니다. alt 속성에는 "로고"라는 단어와 같은 텍스트가 포함되어서는 안 됩니다. 전달하려는 것은 그것이 로고라는 사실이 아니라 엔티티 자체이기 때문입니다.

로고가 엔티티의 이름 옆에 사용되는 경우, 로고는 보조적이며, alt 속성은 비어 있어야 합니다.

로고가 단순히 장식용으로 사용되는 경우(예: 브랜드 이미지로 사용되거나 해당 로고가 속한 엔티티를 언급하는 기사에 측면 이미지로 사용되는 경우), 아래의 순수 장식용 이미지 항목이 적용됩니다. 로고가 실제로 논의되고 있는 경우, 이는 대체 그래픽 표현(로고 자체)을 가진 문구나 단락으로 사용되고 있으므로, 위의 첫 번째 항목이 적용됩니다.

다음 코드 조각에서는 위의 네 가지 경우 모두가 나타납니다. 먼저, 회사 로고가 회사명을 대표하는 데 사용된 예입니다:

<h1><img src="XYZ.gif" alt="XYZ 회사"></h1>

다음은 회사 이름 바로 옆에 로고가 사용된 단락입니다. 따라서 대체 텍스트가 없습니다:

<article>
 <h2>뉴스</h2>
 <p>우리는 최근에 <img src="alpha.gif" alt=""> ΑΒΓ 회사를 인수할 계획입니다. 이 회사는 우리 제품 유형을 전문으로 하는 작은 그리스 회사입니다.</p>

세 번째 코드 조각에서는 획득에 대해 논의하는 더 큰 기사에서 사이드에 로고가 사용되었습니다:

<aside><p><img src="alpha-large.gif" alt=""></p></aside>
 <p>ΑΒΓ 회사는 좋은 분기를 보냈으며, 그들의 계정을 분석한 파이 차트 연구 결과는 파란색 슬라이스가 초록색 및 주황색 슬라이스보다 훨씬 크다는 것을 보여줍니다. 이는 항상 좋은 징조입니다.</p>
</article>

마지막으로, 로고에 대해 논의하는 의견 기사가 있습니다. 따라서 로고는 대체 텍스트에 자세히 설명되어 있습니다.

<p>그들의 로고를 잠시 생각해 보십시오:</p>

<p><img src="/images/logo" alt="초록색 원 안에 중심에 위치한 초록색 물음표로 구성되어 있습니다."></p>

<p>이 얼마나 독창적이지 않습니까? 저는 이 사양들이 이제 모든 사람들이 채택할 것이라고 확신합니다! 그들은 적어도 일련의 둥근 사각형이 있는 일종의 무언가를 시도했을 것입니다. 적어도 그린과 굵은 흰색 윤곽선의 다양한 색조가 있는 것은 파란색 책 표지에 잘 어울렸을 것입니다.</p>

이 예는 이미지가 사용 가능하지 않을 때, 텍스트가 대신 사용되며, 텍스트가 마치 이미지가 처음부터 없었던 것처럼 주변 텍스트와 매끄럽게 연결되는 방식으로 대체 텍스트를 작성해야 함을 보여줍니다.

4.8.4.4.5 그래픽으로 렌더링된 텍스트: 타이포그래피 효과

때때로 이미지는 단지 텍스트로만 구성되며, 이미지의 목적은 텍스트를 렌더링하는 데 사용된 실제 타이포그래피 효과를 강조하는 것이 아니라, 단순히 텍스트 자체를 전달하는 것입니다.

이러한 경우, alt 속성은 반드시 존재해야 하며, 이미지 자체에 쓰인 것과 동일한 텍스트로 구성되어야 합니다.

예를 들어, "Earth Day"라는 텍스트가 포함된 그래픽이 있다고 가정해 보겠습니다. 이 텍스트는 모든 글자가 꽃과 식물로 장식되어 있습니다. 이 텍스트가 단순히 그래픽 사용자를 위해 페이지를 돋보이게 하기 위한 제목으로 사용된다면, 적절한 대체 텍스트는 단순히 "Earth Day"일 뿐이며, 장식에 대해 언급할 필요는 없습니다:

<h1><img src="earthdayheading.png" alt="Earth Day"></h1>

조명된 필사본에서는 일부 이미지에 그래픽을 사용할 수 있습니다. 이러한 상황에서 대체 텍스트는 이미지가 나타내는 문자 자체일 뿐입니다.

<p><img src="initials/o.svg" alt="O">nce upon a time and a long long time ago, late at
night, when it was dark, over the hills, through the woods, across a great ocean, in a land far
away, in a small house, on a hill, under a full moon...

이미지가 Unicode로는 나타낼 수 없는 문자를 표현하는 데 사용되는 경우, 예를 들어, 외자 문자나 새로운 통화 기호와 같은 새로운 문자일 경우, 대체 텍스트는 그 문자의 발음을 나타내는 더 일반적인 방식으로 제공해야 합니다. 예를 들어, 그 문자의 발음을 나타내기 위해 히라가나나 가타카나를 사용할 수 있습니다.

1997년의 이 예에서는 한 막대가 아닌 두 막대를 가진 꼬불꼬불한 E 모양의 새로운 통화 기호가 이미지로 표현되어 있습니다. 대체 텍스트는 그 문자의 발음을 제공합니다.

<p>단지 <img src="euro.png" alt="euro"> 5.99!

문자와 동일한 목적을 제공할 수 있는 경우 이미지를 사용하지 않아야 합니다. 예를 들어, 장식 때문에 텍스트를 직접적으로 나타낼 수 없거나 적절한 문자가 없기 때문에 이미지를 사용하는 것이 적절한 경우에만 이미지를 사용해야 합니다.

작성자가 특정 문자를 지원하지 않는 기본 시스템 폰트 때문에 이미지를 사용하려는 유혹을 받는다면, 웹 폰트가 이미지보다 더 나은 솔루션입니다.

4.8.4.4.6 주변 텍스트의 일부에 대한 그래픽 표현

많은 경우에 이미지는 실제로 보조적인 역할을 하며, 그 존재는 단지 주변 텍스트를 강화하는 데 그칩니다. 이러한 경우, alt 속성은 반드시 존재해야 하며, 그 값은 빈 문자열이어야 합니다.

일반적으로 이미지를 제거해도 페이지의 유용성이 떨어지지 않지만, 이미지를 포함하면 시각적 브라우저 사용자가 개념을 더 쉽게 이해할 수 있는 경우에 이 범주에 속합니다.

이전 단락을 그래픽으로 표현한 플로우차트:

<p>네트워크는 데이터를 입력 스트림 전처리기로 전달하고, 이것은 다시 토크나이저로 전달되며, 그 후 트리 구성 단계로 전달됩니다. 여기서 데이터는 DOM과 스크립트 실행으로 모두 전달됩니다. 스크립트 실행은 DOM과 연결되어 있으며, document.write()를 사용하여 데이터를 다시 토크나이저로 전달합니다.</p>
<p><img src="images/parsing-model-overview.svg" alt=""></p>

이러한 경우에 대체 텍스트에 캡션만 포함하는 것은 잘못된 것입니다. 캡션을 포함하려면 title 속성을 사용하거나 figurefigcaption 요소를 사용할 수 있습니다. 후자의 경우, 이미지는 실제로 대체 그래픽 표현이 있는 문구 또는 단락이 되며, 따라서 대체 텍스트가 필요합니다.

<!-- title="" 속성을 사용하는 경우 -->
<p>네트워크는 데이터를 입력 스트림 전처리기로 전달하고, 이것은 다시 토크나이저로 전달되며, 그 후 트리 구성 단계로 전달됩니다. 여기서 데이터는 DOM과 스크립트 실행으로 모두 전달됩니다. 스크립트 실행은 DOM과 연결되어 있으며, document.write()를 사용하여 데이터를 다시 토크나이저로 전달합니다.</p>
<p><img src="images/parsing-model-overview.svg" alt="" title="파싱 모델의 플로우차트 표현"></p>
<!-- <figure> 및 <figcaption>을 사용하는 경우 -->
<p>네트워크는 데이터를 입력 스트림 전처리기로 전달하고, 이것은 다시 토크나이저로 전달되며, 그 후 트리 구성 단계로 전달됩니다. 여기서 데이터는 DOM과 스크립트 실행으로 모두 전달됩니다. 스크립트 실행은 DOM과 연결되어 있으며, document.write()를 사용하여 데이터를 다시 토크나이저로 전달합니다.</p>
<figure>
 <img src="images/parsing-model-overview.svg" alt="네트워크는 입력 스트림 전처리기로, 전처리기는 토크나이저로, 토크나이저는 트리 구성 단계로 이어집니다. 트리 구성 단계에서 두 가지 항목으로 이어집니다. 첫 번째는 스크립트 실행으로, document.write()를 통해 다시 토크나이저로 이어집니다. 두 번째 항목은 DOM으로, DOM은 스크립트 실행과 연결됩니다.">
 <figcaption>파싱 모델의 플로우차트 표현.</figcaption>
</figure>
<!-- 잘못된 방법입니다. 이렇게 하지 마십시오. 위의 예제를 따르세요. -->
<p>네트워크는 데이터를 입력 스트림 전처리기로 전달하고, 이것은 다시 토크나이저로 전달되며, 그 후 트리 구성 단계로 전달됩니다. 여기서 데이터는 DOM과 스크립트 실행으로 모두 전달됩니다. 스크립트 실행은 DOM과 연결되어 있으며, document.write()를 사용하여 데이터를 다시 토크나이저로 전달합니다.</p>
<p><img src="images/parsing-model-overview.svg" alt="파싱 모델의 플로우차트 표현"></p>
<!-- 이미지 캡션을 alt="" 속성에 포함하지 마세요! -->

이전 단락을 그래픽으로 표현한 그래프:

<p>2007년 웹의 수십억 페이지를 다룬 연구에 따르면, 약 62%의 문서가 웹 브라우저의 Quirks 렌더링 모드를 트리거했으며, 약 30%는 Almost Standards 모드를, 약 9%는 Standards 모드를 트리거했습니다.</p>
<p><img src="rendering-mode-pie-chart.png" alt=""></p>
4.8.4.4.7 부수적 이미지

때때로 이미지는 콘텐츠에 필수적이지 않지만, 순전히 장식적이지도 않고 텍스트와 완전히 중복되지도 않습니다. 이러한 경우, alt 속성이 반드시 존재해야 하며, 그 값은 빈 문자열이거나 이미지가 전달하는 정보를 텍스트로 표현한 것이어야 합니다. 이미지에 제목을 나타내는 캡션이 있는 경우, alt 속성의 값은 비어 있어서는 안 됩니다(그렇지 않으면 시각적이지 않은 독자에게 혼란을 줄 수 있습니다).

정치 인물에 대한 뉴스 기사에서 그 인물의 얼굴이 이미지로 표시된 경우를 생각해보세요. 이 이미지는 순전히 장식적이지 않으므로 스토리와 관련이 있습니다. 이미지가 스토리와 완전히 중복되지도 않으므로 정치인이 어떻게 생겼는지 보여줍니다. 대체 텍스트를 제공할 필요가 있는지 여부는 이미지가 텍스트의 해석에 영향을 미치는지에 따라 저자의 결정에 따라 달라집니다.

첫 번째 변형에서는 이미지가 맥락 없이 표시되며 대체 텍스트가 제공되지 않습니다:

<p><img src="president.jpeg" alt=""> 오늘의 국민투표를 앞두고 대통령은 모든 유권자에게 공개 서한을 작성했습니다. 서한에서 그녀는 나라가 분열되어 있다고 인정했습니다.</p>

사진이 단순히 얼굴을 나타내는 것이라면 그것을 설명하는 데는 가치가 없을 수 있습니다. 독자가 그 인물이 붉은 머리인지 금발 머리인지, 흰 피부인지 검은 피부인지, 한 눈인지 두 눈인지에 관심이 없을 것입니다.

그러나 사진이 더 동적이고 예를 들어 정치인이 화를 내거나, 매우 행복해하거나, 크게 낙담한 모습을 보여준다면, 그러한 대체 텍스트는 기사의 분위기를 설정하는 데 유용할 것입니다. 그렇지 않으면 그 분위기가 놓칠 수 있습니다:

<p><img src="president.jpeg" alt="대통령이 슬퍼하고 있다."> 오늘의 국민투표를 앞두고 대통령은 모든 유권자에게 공개 서한을 작성했습니다. 서한에서 그녀는 나라가 분열되어 있다고 인정했습니다.</p>
<p><img src="president.jpeg" alt="대통령이 기뻐하고 있다!"> 오늘의 국민투표를 앞두고 대통령은 모든 유권자에게 공개 서한을 작성했습니다. 서한에서 그녀는 나라가 분열되어 있다고 인정했습니다.</p>

그 인물이 "슬프다" 또는 "기쁘다"는 사실은 단락의 나머지 부분이 어떻게 해석되어야 하는지에 영향을 미칩니다: 그녀가 나라가 분열된 것에 불만이 있음을 말하고 있는 것인지, 아니면 분열된 나라가 그녀의 정치 경력에 좋다는 것을 말하고 있는 것인지에 따라 해석이 달라집니다.

이미지에 캡션이 있는 경우, 대체 텍스트를 포함함으로써 비시각적 사용자가 캡션이 무엇을 참조하는지 혼란스러워하지 않도록 합니다.

<p>오늘의 국민투표를 앞두고 대통령은 모든 유권자에게 공개 서한을 작성했습니다. 서한에서 그녀는 나라가 분열되어 있다고 인정했습니다.</p>
<figure>
 <img src="president.jpeg" alt="높은 이마, 밝은 표정, 짙은 머리카락으로 완성된 대통령의 얼굴.">
 <figcaption> 루리타니아의 대통령. 사진 © 2014 PolitiPhoto. </figcaption>
</figure>
4.8.4.4.8 정보 추가가 없는 순전히 장식적인 이미지

이미지가 장식적이지만 페이지에 특정적으로 사용되지 않는 경우 — 예를 들어 사이트 전체의 디자인 스키마의 일부를 형성하는 이미지 — 해당 이미지는 문서의 마크업이 아닌 사이트의 CSS에 지정해야 합니다.

그러나 주변 텍스트에서 논의되지 않지만 여전히 관련성이 있는 장식적인 이미지는 img 요소를 사용하여 페이지에 포함할 수 있습니다. 이러한 이미지는 장식적이지만 여전히 콘텐츠의 일부를 형성합니다. 이 경우 alt 속성이 반드시 존재해야 하며, 그 값은 빈 문자열이어야 합니다.

이미지가 관련성이 있지만 순전히 장식적인 예는 블랙 록 시티 풍경의 사진을 포함한 버닝 맨 행사에 대한 블로그 게시물, 또는 시를 낭송하는 페이지에 포함된 시에서 영감을 받은 그림의 이미지 등이 포함될 수 있습니다. 다음 코드 조각은 후자의 경우를 보여줍니다(이 코드 조각에는 첫 번째 절만 포함되어 있습니다):

<h1>The Lady of Shalott</h1>
<p><img src="shalott.jpeg" alt=""></p>
<p>On either side the river lie<br>
Long fields of barley and of rye,<br>
That clothe the wold and meet the sky;<br>
And through the field the road run by<br>
To many-tower'd Camelot;<br>
And up and down the people go,<br>
Gazing where the lilies blow<br>
Round an island there below,<br>
The island of Shalott.</p>

그림이 더 작은 이미지 파일로 잘려 다시 완전한 그림을 형성하도록 함께 표시될 때, 하나의 이미지에는 alt 속성이 전체 그림에 적합한 관련 규칙에 따라 설정되어야 하며, 나머지 모든 이미지의 alt 속성은 빈 문자열로 설정되어야 합니다.

다음 예에서 XYZ Corp의 회사 로고를 나타내는 그림이 두 조각으로 나뉘었으며, 첫 번째는 "XYZ"라는 글자를, 두 번째는 "Corp"라는 단어를 포함하고 있습니다. 대체 텍스트("XYZ Corp")는 모두 첫 번째 이미지에 있습니다.

<h1><img src="logo1.png" alt="XYZ Corp"></img src="logo2.png" alt=""></h1>

다음 예에서 평가는 세 개의 채워진 별과 두 개의 빈 별로 표시됩니다. 대체 텍스트가 "★★★☆☆"일 수 있지만, 저자는 대신 "3 out of 5"라는 형태로 평가를 더 유용하게 제공하기로 결정했습니다. 이는 첫 번째 이미지의 대체 텍스트이며 나머지는 빈 대체 텍스트를 갖습니다.

<p>Rating: <meter max=5 value=3><img src="1" alt="3 out of 5"
  ></img src="1" alt=""></img src="1" alt=""></img src="0" alt=""
  ></img src="0" alt=""></meter></p>

일반적으로 링크를 위해 이미지를 분할하는 대신 이미지 맵을 사용하는 것이 좋습니다.

그러나 이미지가 실제로 분할되어 분할된 그림의 구성 요소 중 일부가 링크의 유일한 내용물인 경우, 각 링크당 하나의 이미지는 해당 링크의 목적을 나타내는 alt 속성에 대체 텍스트를 가져야 합니다.

다음 예에서는 날아다니는 스파게티 몬스터 엠블럼을 나타내는 그림으로, 각 왼쪽 면발과 오른쪽 면발이 다른 이미지에 들어 있어 사용자가 모험에서 왼쪽을 선택하거나 오른쪽을 선택할 수 있습니다.

<h1>The Church</h1>
<p>You come across a flying spaghetti monster. Which side of His Noodliness do you wish to reach out for?</p>
<p><a href="?go=left" ><img src="fsm-left.png"  alt="Left side."></a
  ><img src="fsm-middle.png" alt=""
  ><a href="?go=right"><img src="fsm-right.png" alt="Right side."></a></p>
4.8.4.4.11 콘텐츠의 주요 부분

어떤 경우에는 이미지가 콘텐츠의 중요한 부분을 차지합니다. 예를 들어, 사진 갤러리의 일부인 페이지에서는 이미지 자체가 페이지의 핵심일 수 있습니다.

콘텐츠의 주요 부분을 구성하는 이미지에 대한 대체 텍스트를 제공하는 방법은 이미지의 출처에 따라 다릅니다.

일반적인 경우

잡지 리뷰의 스크린샷 시리즈나 만화, 해당 사진에 대한 블로그 게시물과 같이 이미지에 대한 자세한 대체 텍스트를 제공할 수 있는 경우, 이미지의 대체로 사용할 수 있는 텍스트가 alt 속성에 제공되어야 합니다.

새로운 OS의 스크린샷 갤러리에 있는 스크린샷 예시:

<figure>
 <img src="KDE%20Light%20desktop.png"
      alt="바탕화면은 파란색이며, 왼쪽에는 두 개의 열로 이루어진 아이콘이 있습니다. 시스템, 홈, K-Mail 등으로 읽을 수 있습니다. 메뉴가 창에 맞지 않을 경우 두 번째 줄로 감싸진 창이 열려 있습니다. 창 상단에는 아이콘 목록이 있으며, 아래에는 주소 표시줄, 왼쪽에는 탭 아이콘 목록, 하단에는 상태 표시줄, 중간에는 두 개의 창이 있습니다. 바탕화면 하단에는 몇 개의 버튼, 페이저, 열린 응용 프로그램 목록 및 시계가 있는 막대가 있습니다.">
 <figcaption>KDE 바탕화면의 스크린샷.</figcaption>
</figure>

재무 보고서의 그래프 예시:

<img src="sales.gif"
     title="판매 그래프"
     alt="1998년부터 2005년까지 매출이 매년 다음과 같은 비율로 증가했습니다: 624%, 75%, 138%, 40%, 35%, 9%, 21%">

"판매 그래프"는 판매 그래프에 대한 부적절한 대체 텍스트입니다. 캡션으로 적합한 텍스트는 일반적으로 대체 텍스트로 적합하지 않습니다.

완전한 설명이 어려운 이미지

어떤 경우에는 이미지의 특성상 대체 텍스트를 완벽하게 제공하는 것이 불가능할 수 있습니다. 예를 들어, 이미지가 명확하지 않거나, 복잡한 프랙탈이거나, 상세한 지형도일 수 있습니다.

이러한 경우 alt 속성에는 적절한 대체 텍스트가 포함되어야 하지만, 그 텍스트는 다소 간단할 수 있습니다.

예를 들어, 로르샤흐 잉크블롯 테스트의 이미지를 설명하는 데 유용한 텍스트는 거의 없습니다. 그러나 간단한 설명이라도 없는 것보다 낫습니다:

<figure>
 <img src="/commons/a/a7/Rorschach1.jpg" alt="왼쪽-오른쪽 대칭을 가진 형태로, 경계가 흐릿하며, 중앙에 작은 틈이 있고, 중앙에서 약간 비켜난 두 개의 큰 틈과 그 아래에 두 개의 유사한 틈이 있습니다. 윤곽은 하단보다 상단이 넓으며, 측면은 중앙보다 위로 더 많이 확장되고, 중앙은 측면 아래로 확장됩니다.">
 <figcaption>로르샤흐 잉크블롯 테스트의 첫 번째 카드의 검은 윤곽.</figcaption>
</figure>

다음은 대체 텍스트의 잘못된 사용 사례입니다:

<!-- 이 예시는 잘못된 것입니다. 따라하지 마십시오. -->
<figure>
 <img src="/commons/a/a7/Rorschach1.jpg" alt="로르샤흐 잉크블롯 테스트의 첫 번째 카드의 검은 윤곽.">
 <figcaption>로르샤흐 잉크블롯 테스트의 첫 번째 카드의 검은 윤곽.</figcaption>
</figure>

이와 같이 캡션을 대체 텍스트에 포함시키는 것은 사용자에게 중복된 정보를 제공하여 불필요하게 혼란을 줄 수 있습니다.

또한, 프랙탈과 같이 완전한 설명이 어려운 이미지의 예도 있습니다. 프랙탈은 본질적으로 무한한 세부 사항을 포함하고 있기 때문입니다.

다음은 만델브로 집합 이미지에 대한 전체 보기의 대체 텍스트를 제공하는 한 가지 방법입니다.

<img src="ms1.jpeg" alt="만델브로 집합은 실축의 양의 방향에서 꼭지점이 있는 심장형으로 나타나며, 같은 중심선에 따라 정렬된 더 작은 전구가 부정적인 방향에서 접촉하며, 이러한 두 모양은 다양한 크기의 더 작은 전구로 둘러싸여 있습니다.">

비슷하게, 전기의 일부로 사람의 얼굴 사진이 포함된 경우, 이는 콘텐츠와 매우 관련이 있고 중요한 부분으로 간주될 수 있지만, 이를 완전히 텍스트로 대체하는 것은 어려울 수 있습니다:

<section class="bio">
 <h1>아이작 아시모프의 전기</h1>
 <p>1920년에 <b>이삭 유도비치 오지모프</b>라는 이름으로 태어난 아이작은 다작 작가였습니다.</p>
 <p><img src="headpics/asimov.jpeg" alt="아이작 아시모프는 짙은 머리카락, 높은 이마, 안경을 썼습니다. 나이가 들어서는 긴 흰색 구레나룻을 기르기도 했습니다."></p>
 <p>아시모프는 러시아에서 태어났으며, 세 살 때 미국으로 이주했습니다.</p>
 <p>...</p>
</section>

이러한 경우 대체 텍스트에 이미지 자체의 존재를 언급하는 것은 불필요하고 권장되지 않습니다. 예를 들어, 대체 텍스트가 "아이작 아시모프의 사진"이라고 하면, 적합한 사용자 에이전트는 "(이미지) 아이작 아시모프의 사진" 대신 "(이미지) 아이작 아시모프는 짙은 머리카락, 높은 이마, 안경을 썼습니다..."라고 읽어주는 것이 더 유용합니다.

내용을 알 수 없는 이미지

어떤 경우에는 이미지에 대한 대체 텍스트가 전혀 제공되지 않을 수 있습니다. 예를 들어, 이미지가 자동으로 얻어지거나 관련된 대체 텍스트가 없는 경우(예: 웹캠), 스크립트를 사용하여 사용자가 제공한 이미지를 사용하여 페이지를 생성하는 경우(예: 사진 공유 사이트), 또는 저자 자신이 이미지가 무엇을 나타내는지 모르는 경우(예: 시각장애인이 블로그에 이미지를 공유하는 경우) 등이 있습니다.

이 경우 alt 속성을 생략할 수 있지만, 다음 조건 중 하나를 충족해야 합니다.

이러한 경우는 가능한 최소한으로 유지해야 합니다. 저자가 실제 대체 텍스트를 제공할 가능성이 조금이라도 있다면, alt 속성을 생략하는 것은 허용되지 않습니다.

사진 공유 사이트에서 메타데이터 없이 캡션만 포함된 이미지를 받은 경우 다음과 같이 표시할 수 있습니다:

<figure>
 <img src="1100670787_6a7c664aef.jpg">
 <figcaption>Bubbles traveled everywhere with us.</figcaption>
</figure>

그러나 사용자로부터 얻은 이미지의 중요한 부분에 대한 자세한 설명을 페이지에 포함시키는 것이 더 좋습니다.

시각장애인의 블로그에 사용자가 촬영한 사진이 표시되는 경우, 초기에는 사용자가 촬영한 사진이 무엇을 보여주는지 모를 수 있습니다:

<article>
 <h1>사진을 찍었어요</h1>
 <p>오늘 나가서 사진을 찍었어요!</p>
 <figure>
  <img src="photo2.jpeg">
  <figcaption>내 현관 앞에서 눈을 감고 찍은 사진.</figcaption>
 </figure>
</article>

그러나 시간이 지나면서 친구들로부터 이미지에 대한 설명을 얻고 대체 텍스트를 포함할 수 있습니다:

<article>
 <h1>사진을 찍었어요</h1>
 <p>오늘 나가서 사진을 찍었어요!</p>
 <figure>
  <img src="photo2.jpeg" alt="사진에는 지붕 가장자리에서 매달려 있는 다람쥐 먹이통이 보입니다. 먹이통은 절반 정도 차 있으며, 주변에는 다람쥐가 없습니다. 배경에는 초점이 맞지 않은 나무들이 찍혀 있습니다. 먹이통은 나무로 만들어졌으며, 금속 그물이 붙어 있고, 안에는 땅콩이 들어 있습니다. 지붕의 가장자리도 나무로 만들어졌으며, 흰색과 옅은 파란색 줄무늬로 칠해져 있습니다.">
  <figcaption>내 현관 앞에서 눈을 감고 찍은 사진.</figcaption>
 </figure>
</article>

때로는 이미지의 전체적인 의미가 텍스트 설명을 제공하지 않는 것이며, 사용자가 설명을 제공하도록 유도하는 경우도 있습니다. 예를 들어, CAPTCHA 이미지의 목적은 사용자가 그래픽을 실제로 읽을 수 있는지 확인하는 것입니다. 다음은 CAPTCHA를 표시하는 한 가지 방법입니다(title 속성에 주목하십시오):

<p><label>이 이미지에는 무엇이 적혀 있습니까?
<img src="captcha.cgi?id=8934" title="CAPTCHA">
<input type=text name=captcha></label>
(이미지를 볼 수 없는 경우 <a href="?audio">오디오</a> 테스트를 대신 사용할 수 있습니다.)</p>

또한 이미지에 대한 대체 텍스트를 정확하게 작성하는 목적으로 이미지를 표시하고 대체 텍스트를 요청하는 소프트웨어도 있습니다. 이러한 페이지는 다음과 같은 이미지 표를 포함할 수 있습니다:

<table>
 <thead>
  <tr> <th> 이미지 <th> 설명
 <tbody>
  <tr>
   <td> <img src="2421.png" title="이미지 640 x 100, 파일 이름 'banner.gif'">
   <td> <input name="alt2421">
  </tr>
   </td> <img src="2422.png" title="이미지 200 x 480, 파일 이름 'ad3.gif'">
   <td> <input name="alt2422">
</table>

이 예에서도 가능한 많은 유용한 정보가 title 속성에 포함되어 있다는 점에 유의하십시오.

일부 사용자는 이미지 자체를 전혀 사용할 수 없습니다(예: 연결 속도가 매우 느리거나 텍스트 전용 브라우저를 사용하거나 차량용 음성 웹 브라우저로 페이지를 듣거나 단순히 시각장애인이기 때문입니다). 이 때문에 alt 속성은 대체 텍스트가 제공되지 않거나 제공할 수 없는 경우에만 생략할 수 있으며, 위의 예시와 같이 제공되지 않은 경우에만 생략할 수 있습니다. 저자의 노력 부족은 alt 속성을 생략할 수 있는 정당한 이유가 아닙니다.

4.8.4.4.12 사용자에게 의도되지 않은 이미지

일반적으로 저자는 img 요소를 이미지를 보여주는 것 외의 목적으로 사용하는 것을 피해야 합니다.

img 요소가 페이지 뷰 수를 계산하는 서비스의 일부와 같이 이미지를 표시하는 것 외의 목적으로 사용되는 경우, alt 속성은 빈 문자열이어야 합니다.

이러한 경우 widthheight 속성은 모두 0으로 설정해야 합니다.

4.8.4.4.13 이미지를 볼 수 있는 것으로 알려진 특정 인물에게 보내는 이메일 또는 개인 문서에 포함된 이미지

이 섹션은 공개적으로 접근할 수 있는 문서나 저자가 개인적으로 알지 못하는 대상 독자를 대상으로 하는 문서(예: 웹사이트의 문서, 공개 메일링 리스트에 발송된 이메일, 소프트웨어 문서)에는 적용되지 않습니다.

이미지를 볼 수 있는 것으로 알려진 특정 인물에게 보내는 개인 통신(예: HTML 이메일)에 이미지가 포함된 경우, alt 속성을 생략할 수 있습니다. 그러나 이러한 경우에도 사용자가 이미지를 지원하지 않는 메일 클라이언트를 사용하는 경우나, 문서가 이미지를 쉽게 볼 수 없는 다른 사용자에게 전달될 수 있음을 고려하여 저자는 대체 텍스트를 포함할 것을 강력히 권장합니다(위에서 설명한 이미지 종류에 따라 적절하게).

4.8.4.4.14 마크업 생성기를 위한 지침

마크업 생성기(WYSIWYG 저작 도구와 같은)는 가능한 한 사용자로부터 대체 텍스트를 받아야 합니다. 그러나 많은 경우에 이것이 불가능하다는 점이 인식됩니다.

링크의 유일한 콘텐츠로 사용되는 이미지의 경우, 마크업 생성기는 링크 대상의 제목이나 URL을 확인하여 이 정보를 대체 텍스트로 사용해야 합니다.

캡션이 있는 이미지의 경우, 마크업 생성기는 figurefigcaption 요소 또는 title 속성을 사용하여 이미지의 캡션을 제공해야 합니다.

마지막 수단으로 구현자는 이미지가 단순히 장식적이며 정보는 추가하지 않지만 여전히 주변 콘텐츠에 특정한 이미지라고 가정하고 alt 속성을 빈 문자열로 설정하거나, 이미지가 콘텐츠의 중요한 부분이라고 가정하고 alt 속성을 아예 생략해야 합니다.

마크업 생성기는 대체 텍스트를 얻을 수 없어서 alt 속성을 생략해야 하는 img 요소에 generator-unable-to-provide-required-alt 속성을 지정할 수 있습니다. 이 속성의 값은 빈 문자열이어야 합니다. 이러한 속성을 포함하는 문서는 적합하지 않지만, 적합성 검사기는 이 오류를 묵인합니다.

이것은 적합성 검사기에서 대체 텍스트가 없다는 오류를 방지하기 위해 마크업 생성기가 잘못된 대체 텍스트를 제공하는 실수를 방지하기 위한 것입니다. 자동화된 적합성 검사기는 잘못된 대체 텍스트와 올바른 대체 텍스트를 구별할 수 없기 때문입니다.

마크업 생성기는 일반적으로 이미지의 파일 이름을 대체 텍스트로 사용하는 것을 피해야 합니다. 마찬가지로, 마크업 생성기는 표현 사용자 에이전트(예: 웹 브라우저)에서도 동일하게 제공되는 콘텐츠에서 대체 텍스트를 생성하는 것을 피해야 합니다.

이유는 페이지가 생성된 후 일반적으로 업데이트되지 않지만, 나중에 페이지를 읽는 브라우저는 사용자가 업데이트할 수 있기 때문입니다. 따라서 브라우저는 페이지가 생성될 때 마크업 생성기보다 최신 상태의 정교한 휴리스틱을 가질 가능성이 더 큽니다.

4.8.4.4.15 적합성 검사기를 위한 지침

적합성 검사기는 아래 나열된 조건 중 하나에 해당하지 않는 한 alt 속성이 없음을 오류로 보고해야 합니다:

4.8.5 iframe 요소

Element/iframe

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera15+Edge79+
Edge (레거시)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

HTMLIFrameElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
임베디드 콘텐츠.
인터랙티브 콘텐츠.
구체적인 콘텐츠.
이 요소가 사용될 수 있는 컨텍스트:
임베디드 콘텐츠가 예상되는 곳.
콘텐츠 모델:
없음.
태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
src — 리소스의 주소
srcdociframe에 렌더링할 문서
name내비게이블 콘텐츠의 이름
sandbox — 중첩된 콘텐츠에 대한 보안 규칙
allowPermissions policyiframe의 콘텐츠에 적용
allowfullscreeniframe의 콘텐츠가 requestFullscreen()을 사용할 수 있는지 여부
width — 가로 크기
height — 세로 크기
referrerpolicy — 이 요소가 시작하는 페치에 대한 리퍼러 정책
loading — 로딩 지연을 결정할 때 사용됨
접근성 고려사항:
작성자를 위한 안내.
구현자를 위한 안내.
DOM 인터페이스:
[Exposed=Window]
interface HTMLIFrameElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute (TrustedHTML or DOMString) srcdoc;
  [CEReactions] attribute DOMString name;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList sandbox;
  [CEReactions] attribute DOMString allow;
  [CEReactions] attribute boolean allowFullscreen;
  [CEReactions] attribute DOMString width;
  [CEReactions] attribute DOMString height;
  [CEReactions] attribute DOMString referrerPolicy;
  [CEReactions] attribute DOMString loading;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;
  Document? getSVGDocument();

  // 구식 멤버도 포함
};

iframe 요소는 대표하는 내비게이블 콘텐츠입니다.

src 속성은 이 요소의 URL을 제공합니다. 이 속성이 지정되어 있다면, itemprop 속성이 iframe 요소에 지정된 경우 src 속성도 지정되어야 합니다.

Element/iframe#attr-srcdoc

모든 최신 엔진에서 지원됩니다.

Firefox25+Safari6+Chrome20+
Opera?Edge79+
Edge (레거시)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?

srcdoc 속성은 이 요소의 내비게이블 콘텐츠에 포함될 페이지의 콘텐츠를 제공합니다. 이 속성의 값은 iframe srcdoc 문서라는 documentURLabout:srcdoc과 일치하도록 사용됩니다.

srcdoc 속성이 지정되어 있다면, 이 속성의 값은 다음과 같은 문법 구성 요소로 구성된 HTML 문법을 사용해야 합니다:

  1. 아무 개수의 주석ASCII 공백 문자.
  2. 선택적으로 DOCTYPE.
  3. 아무 개수의 주석ASCII 공백 문자.
  4. html 요소의 형식으로 된 문서 요소.
  5. 아무 개수의 주석ASCII 공백 문자.

위의 요구 사항은 XML 문서에서도 적용됩니다.

여기에서 블로그는 srcdoc 속성과 아래에 설명된 sandbox 속성을 결합하여 이 기능을 지원하는 사용자 에이전트에서 블로그 댓글에 스크립트 삽입으로부터 추가적인 보호를 제공합니다:

<article>
 <h1>I got my own magazine!</h1>
 <p>After much effort, I've finally found a publisher, and so now I have my own magazine! Isn't that awesome?! The first issue will come out in September, and we have articles about getting food, and about getting in boxes, it's going to be great!</p>
 <footer>
  <p>Written by <a href="/users/cap">cap</a>, 1 hour ago.</footer>
 </article>
  <footer> Thirteen minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>did you get a cover picture yet?"></iframe>
 </article>
 <article>
  <footer> Nine minutes ago, <a href="/users/cap">cap</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>Yeah, you can see it <a href=&quot;/gallery?mode=cover&amp;amp;page=1&quot;>in my gallery</a>."></iframe>
 </article>
 <article>
  <footer> Five minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>hey that's earl's table.<p>you should get earl&amp;amp;me on the next cover."></iframe>
 </article>

따옴표를 어떻게 이스케이프해야 하는지(그렇지 않으면 srcdoc 속성이 조기 종료될 수 있음)와 샌드박스된 콘텐츠에 언급된 원시 앰퍼샌드(예: URL 또는 산문에서) 이스케이프가 어떻게 이중으로 처리되어야 하는지 주목하십시오. — 처음에는 srcdoc 속성을 처음 구문 분석할 때 앰퍼샌드가 유지되도록 하고, 그 후 샌드박스된 콘텐츠를 구문 분석할 때 앰퍼샌드가 오해되지 않도록 다시 이스케이프를 해야 합니다.

또한 DOCTYPEiframe srcdoc 문서에서 선택적이며, html, head, body 요소가 선택적 시작 및 종료 태그를 가지며, title 요소도 iframe srcdoc 문서에서 선택적이라는 사실에 주목하십시오. srcdoc 속성에 있는 마크업은 전체 문서를 나타내지만 비교적 간결할 수 있습니다. 구문에서 문자 그대로 나타나야 하는 것은 body 요소의 내용뿐입니다. 다른 요소들은 암시적으로만 존재합니다.

HTML 문법에서는 작성자가 U+0022 인용 부호 문자를 사용하여 속성 내용을 감싸고 U+0026 AMPERSAND(&) 및 U+0022 인용 부호(") 문자를 이스케이프하고, sandbox 속성을 지정하여 콘텐츠가 안전하게 포함되도록 해야 합니다(앰퍼샌드를 인용 부호 앞에서 이스케이프하여 인용 부호가 &quot;이 되도록 합니다).

XML에서는 U+003C LESS-THAN SIGN 문자(<)도 이스케이프해야 합니다. 속성 값의 정규화를 방지하기 위해 XML의 공백 문자 중 일부 — 구체적으로 U+0009 캐릭터 탭(탭), U+000A 줄 바꿈(LF), U+000D 캐리지 리턴(CR) — 도 이스케이프해야 합니다. [XML]

src 속성과 srcdoc 속성이 모두 지정된 경우, srcdoc 속성이 우선 적용됩니다. 이를 통해 작성자는 srcdoc 속성을 지원하지 않는 레거시 사용자 에이전트를 위한 대체 URL을 제공할 수 있습니다.


iframe HTML 요소 삽입 단계insertedNode가 주어진 경우 다음과 같습니다.

  1. insertedNode섀도우 포함 루트탐색 컨텍스트가 null인 경우, 반환합니다.

  2. insertedNode에 대해 새 자식 내비게이블을 생성합니다.

  3. 만약 insertedNodesandbox 속성이 있다면, 해당 속성의 값을 기준으로 insertedNodeiframe sandboxing 플래그 세트분석합니다.

  4. insertedNodeiframe 속성을 initialInsertion 값을 true로 설정하여 처리합니다.

iframe HTML 요소 제거 단계removedNode가 주어진 경우, removedNode에 대해 자식 내비게이블을 파괴합니다.

이 작업은 unload 이벤트가 발생하지 않은 상태에서 이루어집니다(요소의 콘텐츠 문서파괴됩니다, 언로드되지 않습니다).

iframe 요소가 섀도우 트리 내에서 처리되지만, 이 외에도 그들의 동작과 관련하여 섀도우 트리에 대해 정의되지 않은 여러 측면이 있습니다. 자세한 내용은 문제 #763을 참조하십시오.

iframe 요소에 null이 아닌 내비게이블 콘텐츠가 있고, srcdoc 속성이 설정, 변경, 또는 제거될 때마다 사용자 에이전트는 iframe 속성을 처리해야 합니다.

마찬가지로, iframe 요소에 null이 아닌 내비게이블 콘텐츠가 있지만 지정된 srcdoc 속성이 없고, src 속성이 설정, 변경, 또는 제거될 때마다 사용자 에이전트는 iframe 속성을 처리해야 합니다.

다음은 요소 element에 대한 iframe 속성 처리을 수행하는 방법입니다. 선택적으로 부울 initialInsertion이 있습니다(기본값은 false).

  1. elementsrcdoc 속성이 지정된 경우:

    1. element현재 탐색은 지연 로드되었습니다 부울 값을 false로 설정합니다.

    2. 주어진 element에 대한 지연 로드 요소 단계가 true를 반환하는 경우:

      1. 이 알고리즘의 나머지 부분을 srcdoc 리소스로 탐색으로 시작하여 element지연 로드 재개 단계로 설정합니다.

      2. element현재 탐색이 지연 로드되었습니다 부울 값을 true로 설정합니다.

      3. element에 대해 지연 로드 요소를 교차 관찰 시작합니다.

      4. 반환합니다.

    3. srcdoc 리소스로 탐색: element, about:srcdoc, 빈 문자열 및 elementsrcdoc 속성 값을 주어진 iframe 또는 frame을 탐색합니다.

      결과로 나온 documentiframe srcdoc 문서로 간주되어야 합니다.

  2. 그 외의 경우:

    1. urlelementinitialInsertion이 주어진 iframe 및 frame 요소에 대한 공유 속성 처리 단계를 실행한 결과로 설정합니다.

    2. url이 null이면 반환합니다.

    3. urlabout:blank일치하고 initialInsertion이 true인 경우:

      1. element에 대해 iframe 로드 이벤트 단계를 실행합니다.

      2. 반환합니다.

    4. referrerPolicyelementreferrerpolicy 콘텐츠 속성의 현재 상태로 설정합니다.

    5. element현재 탐색은 지연 로드되었습니다 부울 값을 false로 설정합니다.

    6. 주어진 element에 대한 지연 로드 요소 단계가 true를 반환하는 경우:

      1. 이 알고리즘의 나머지 부분을 탐색으로 시작하여 element지연 로드 재개 단계로 설정합니다.

      2. element현재 탐색이 지연 로드되었습니다 부울 값을 true로 설정합니다.

      3. element에 대해 지연 로드 요소를 교차 관찰 시작합니다.

      4. 반환합니다.

    7. 탐색: element, urlreferrerPolicy이 주어진 iframe 또는 frame을 탐색합니다.

iframeframe 요소에 대한 공유 속성 처리 단계는 요소 element와 부울 initialInsertion이 주어진 경우 다음과 같습니다:

  1. urlabout:blank URL 기록으로 설정합니다.

  2. elementsrc 속성이 지정되어 있고 그 값이 빈 문자열이 아닌 경우:

    1. 그 속성의 값을 element노드 문서와 상대적으로 주어진 URL 인코딩-구문 분석을 실행한 결과를 maybeURL로 설정합니다.

    2. maybeURL이 실패하지 않으면, urlmaybeURL로 설정합니다.

  3. element노드 내비게이블포괄적인 조상 내비게이블url조각 제외로 설정하여 url동일한 활성 문서를 포함하는 내비게이블을 포함하는 경우, null을 반환합니다.

  4. urlabout:blank일치하고 initialInsertion이 true인 경우, element콘텐츠 내비게이블활성 문서url이 주어진 URL 및 기록 업데이트 단계를 실행합니다.

    이는 about:blank?foo와 같은 url을 처리하는 데 필요합니다. url이 단순히 about:blank인 경우, 이 작업은 아무런 작업도 수행하지 않습니다.

  5. url을 반환합니다.

iframe 또는 frame을 탐색하는 방법은 요소 element, URL url, 리퍼러 정책 referrerPolicy 및 선택적으로 문자열 또는 null srcdocString(기본값은 null)을 사용하여 다음과 같이 합니다.

  1. historyHandling을 "자동"으로 설정합니다.

  2. element내비게이블 콘텐츠활성 문서완전히 로드된 상태가 아니면, historyHandling을 "대체"로 설정합니다.

  3. elementiframe인 경우, element대기 중인 리소스 타이밍 시작 시간element현재 고해상도 시간으로 설정합니다.

  4. element내비게이블 콘텐츠urlelement노드 문서를 사용하여 탐색합니다. historyHandlinghistoryHandling으로, referrerPolicyreferrerPolicy로, 문서 리소스srcdocString으로 설정합니다.

documentiframe 로드 진행 중 플래그와 iframe 로드 음소거 플래그를 가지고 있습니다. document가 생성될 때, 이러한 플래그는 해당 document에 대해 해제되어야 합니다.

iframe 로드 이벤트 단계를 실행하는 방법은 주어진 iframe 요소 element에 대해 다음과 같습니다.

  1. 확인: element내비게이블 콘텐츠가 null이 아님을 확인합니다.

  2. childDocumentelement내비게이블 콘텐츠활성 문서로 설정합니다.

  3. childDocumentiframe 로드 음소거 플래그가 설정되어 있으면 반환합니다.

  4. element대기 중인 리소스 타이밍 시작 시간이 null이 아닌 경우:

    1. globalelement노드 문서관련 글로벌 객체로 설정합니다.

    2. fallbackTimingInfoelement대기 중인 리소스 타이밍 시작 시간global에 주어진 현재 고해상도 시간을 사용하여 새로운 fetch 타이밍 정보로 설정합니다.

    3. url, "iframe", global, 빈 문자열, 새로운 응답 본문 정보 및 0을 사용하여 리소스 타이밍 표시를 수행합니다.

    4. element대기 중인 리소스 타이밍 시작 시간을 null로 설정합니다.

  5. childDocumentiframe 로드 진행 중 플래그를 설정합니다.

  6. element에서 로드라는 이름의 이벤트를 발생시킵니다.

  7. childDocumentiframe 로드 진행 중 플래그를 해제합니다.

이 작업은 스크립팅과 함께 사용되어 로컬 네트워크의 HTTP 서버의 URL 공간을 탐색할 수 있습니다. 사용자 에이전트는 이러한 공격을 완화하기 위해 위에서 설명한 것보다 더 엄격한 교차 출처 액세스 제어 정책을 구현할 수 있지만, 안타깝게도 이러한 정책은 일반적으로 기존 웹 콘텐츠와 호환되지 않습니다.

요소 유형이 로드 이벤트를 잠재적으로 지연시킬 수 있는 경우, 해당 유형의 각 요소 element에 대해, 사용자 에이전트는 element노드 문서의 로드 이벤트를 지연시켜야 하며, 다음 중 하나라도 참인 경우에만 element내비게이블 콘텐츠가 null이 아닙니다.

로드 이벤트 처리 중에 element내비게이블 콘텐츠가 다시 탐색되면, 로드 이벤트는 더 지연될 것입니다.

iframe 요소에는 초기 값이 false인 현재 탐색이 지연 로드됨 부울이 관련되어 있습니다. 이 부울은 iframe 속성을 처리하는 알고리즘에서 설정되고 해제됩니다.

현재 탐색이 지연 로드되지 않은 iframe 요소는 로드 이벤트를 잠재적으로 지연시킵니다.

iframe 요소에는 null 또는 DOMHighResTimeStamp가 관련되어 있으며, 대기 중인 리소스 타이밍 시작 시간으로 설정됩니다. 이 값은 처음에 null로 설정됩니다.

요소가 생성될 때, srcdoc 속성이 설정되지 않았고 src 속성이 설정되지 않았거나 설정되었지만 그 값을 구문 분석할 수 없는 경우, 요소의 내비게이블 콘텐츠초기 about:blank document에서 유지됩니다.

사용자가 이 페이지에서 다른 곳으로 이동하면, iframe내비게이블 콘텐츠활성 WindowProxy 객체는 새로운 Window 객체에 대해 프록시로 동작하지만, src 속성은 변경되지 않습니다.


name 속성은, 존재할 경우, 유효한 탐색 가능 대상 이름이어야 합니다. 지정된 값은 내용 탐색 가능 요소가 존재할 때, 그것이 생성될 때 그 요소의 이름으로 사용됩니다.


Element/iframe#attr-sandbox

모든 현재 엔진에서 지원됩니다.

Firefox17+Safari5+Chrome4+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

sandbox 속성은, 지정되면, iframe에 호스팅된 모든 콘텐츠에 대해 일련의 추가 제한을 활성화합니다. 이 속성의 값은 유일한 공백으로 구분된 토큰의 무작위 집합이어야 하며, ASCII 대소문자 구분이 없는 형식이어야 합니다. 허용되는 값은 다음과 같습니다:

이 속성이 설정되면 콘텐츠는 고유한 불투명 원본으로 취급되며, 양식, 스크립트 및 다양한 잠재적으로 성가신 API가 비활성화되고, 링크가 다른 탐색 가능 항목을 대상으로 하지 못하게 됩니다. allow-same-origin 키워드는 콘텐츠가 실제 원본에서 가져온 것으로 처리되도록 하며, 불투명 원본으로 강제되지 않도록 합니다. allow-top-navigation 키워드는 콘텐츠가 탐색할 수 있도록 허용하며, 탐색 가능 항목을 탐색할 수 있도록 합니다. allow-top-navigation-by-user-activation 키워드는 비슷한 방식으로 동작하지만, 사용자가 활성화한 경우에만 탐색을 허용합니다. allow-top-navigation-to-custom-protocols 키워드는 fetch 스킴이 아닌 항목으로의 탐색을 다시 활성화하여 외부 소프트웨어로 전달될 수 있도록 합니다. allow-forms, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-popups, allow-presentation, allow-scripts, 및 allow-popups-to-escape-sandbox 키워드는 양식, 모달 대화 상자, 화면 방향 고정, 포인터 잠금 API, 팝업, 프레젠테이션 API, 스크립트 및 비샌드박스 보조 브라우징 컨텍스트의 생성을 다시 활성화합니다. allow-downloads 키워드는 콘텐츠가 다운로드를 수행할 수 있도록 허용합니다. [POINTERLOCK] [SCREENORIENTATION] [PRESENTATION]

allow-top-navigation 키워드와 allow-top-navigation-by-user-activation 키워드는 둘 다 지정될 수 없습니다. 이는 중복되며, 이 경우 allow-top-navigation만 효과가 있습니다.

마찬가지로, allow-top-navigation-to-custom-protocols 키워드는 allow-top-navigation 또는 allow-popups 중 하나가 지정된 경우 지정될 수 없습니다. 이는 중복됩니다.

샌드박스 콘텐츠 내에서 alert(), confirm(), 및 prompt()를 허용하려면, allow-modalsallow-same-origin 키워드를 모두 지정해야 하며, 로드된 URL이 동일 출처여야 하고 최상위 출처와 동일해야 합니다. allow-same-origin 키워드가 없으면 콘텐츠는 항상 교차 출처로 취급되며, 교차 출처 콘텐츠는 간단한 대화 상자를 표시할 수 없습니다.

allow-scripts 키워드와 allow-same-origin 키워드를 함께 설정하면, 동일 출처로 되어 있는 경우 iframe을 포함하는 페이지에서 임베디드 페이지가 sandbox 속성을 단순히 제거한 다음 스스로를 다시 로드할 수 있으므로, 샌드박스에서 완전히 벗어날 수 있습니다.

이 플래그는 iframe 요소의 내용 탐색 가능 요소탐색될 때만 효과가 있습니다. 플래그를 제거하거나, sandbox 속성을 제거해도 이미 로드된 페이지에는 아무런 영향이 없습니다.

잠재적으로 악의적인 파일은 iframe 요소가 포함된 파일과 동일한 서버에서 제공되어서는 안 됩니다. 사용자가 악의적인 콘텐츠를 직접 방문하도록 설득할 수 있는 경우, 악의적인 콘텐츠를 샌드박싱하는 것은 거의 도움이 되지 않습니다. 악의적인 HTML 콘텐츠가 야기할 수 있는 피해를 제한하려면 별도의 전용 도메인에서 제공해야 합니다. 다른 도메인을 사용하면 파일의 스크립트가 사이트를 공격할 수 없으며, 사용자가 해당 페이지를 보호되지 않은 상태에서 직접 방문하도록 속임을 당하더라도 문제가 발생하지 않습니다. sandbox 속성의 보호를 받지 않고도 해당 페이지를 방문할 수 있습니다.

iframe 요소의 sandbox 속성이 설정되거나 변경될 때, 해당 요소가 null이 아닌 내용 탐색 가능 요소를 가지고 있는 경우, 사용자 에이전트는 속성의 값을 사용하여 샌드박스 지시문을 분석해야 합니다.

iframe 요소의 sandbox 속성이 제거될 때, 해당 요소가 null이 아닌 내용 탐색 가능 요소를 가지고 있는 경우, 사용자 에이전트는 iframe 요소의 iframe 샌드박싱 플래그 집합을 비워야 합니다.

이 예에서는 완전히 알 수 없는 잠재적으로 악의적인 사용자 제공 HTML 콘텐츠가 페이지에 포함되어 있습니다. 별도의 도메인에서 제공되기 때문에 모든 일반적인 교차 사이트 제한 사항의 영향을 받습니다. 또한, 포함된 페이지는 스크립트, 플러그인 및 양식이 비활성화되어 있으며, 자신 또는 자신이 포함한 프레임이나 창 이외의 항목을 탐색할 수 없습니다.

<p>We're not scared of you! Here is your content, unedited:</p>
<iframe sandbox src="https://usercontent.example.net/getusercontent.cgi?id=12193"></iframe>

별도의 도메인을 사용하는 것이 중요합니다. 공격자가 사용자를 직접 해당 페이지로 이동하도록 설득할 수 있는 경우, 페이지는 사이트의 원본 컨텍스트에서 실행되지 않으며, 사용자는 페이지에서 발견된 모든 공격에 취약해질 수 있습니다.

이 예에서는 다른 사이트에서 제공되는 가젯이 포함되어 있습니다. 이 가젯은 스크립트와 양식이 활성화되어 있으며, 원본 샌드박스 제한이 해제되어 가젯이 원본 서버와 통신할 수 있습니다. 그러나 샌드박스는 여전히 유용하며, 플러그인과 팝업을 비활성화하여 사용자가 악성 코드 및 기타 성가신 요소에 노출되는 위험을 줄여줍니다.

<iframe sandbox="allow-same-origin allow-forms allow-scripts"
    src="https://maps.example.com/embedded.html"></iframe>

파일 A에 다음과 같은 조각이 포함되어 있다고 가정해 봅시다:

<iframe sandbox="allow-same-origin allow-forms" src=B></iframe>

파일 B에도 iframe이 포함되어 있다고 가정해 봅시다:

<iframe sandbox="allow-scripts" src=C></iframe>

또한 파일 C에는 링크가 포함되어 있다고 가정해 봅시다:

<a href=D>Link</a>

이 예에서 모든 파일이 text/html로 제공되었다고 가정해 봅시다.

이 시나리오에서 C 페이지에는 모든 샌드박스 플래그가 설정되어 있습니다. A에 있는 iframe에서 스크립트가 비활성화되어 있기 때문에, B에 설정된 allow-scripts 키워드가 무시됩니다. 또한, B의 내부 iframe에는 allow-forms 키워드가 설정되어 있지 않기 때문에 양식도 비활성화됩니다.

이제 A에 있는 스크립트가 A와 B의 모든 sandbox 속성을 제거한다고 가정해 봅시다. 이 경우 즉시 아무 것도 변경되지 않습니다. 사용자가 C에서 링크를 클릭하여 D 페이지를 B에 로드하면, 페이지 D는 이제 B에 있는 iframeallow-same-originallow-forms 키워드가 설정된 것처럼 작동합니다. 이는 페이지 B가 로드될 때 A의 내용 탐색 가능 요소의 상태였기 때문입니다.

일반적으로 sandbox 속성을 동적으로 제거하거나 변경하는 것은 권장되지 않습니다. 이는 무엇이 허용되고 무엇이 허용되지 않을지를 판단하기 어렵게 만들 수 있습니다.


allow 속성은 지정되었을 때, 컨테이너 정책을 결정하며, 권한 정책Document 내에서 iframe내용 탐색 가능 요소에서 초기화될 때 사용됩니다. 값은 직렬화된 권한 정책이어야 합니다. [PERMISSIONSPOLICY]

이 예에서는 iframe이 사용되어 온라인 내비게이션 서비스의 지도를 임베드합니다. allow 속성은 중첩된 컨텍스트 내에서 지리 위치 API를 활성화하는 데 사용됩니다.

<iframe src="https://maps.example.com/" allow="geolocation"></iframe>

allowfullscreen 속성은 부울 속성입니다. 지정되었을 때, Document 객체가 iframe 요소의 내용 탐색 가능 요소에서 초기화될 때, "fullscreen" 기능을 어떤 출처에서든 사용할 수 있도록 허용하는 권한 정책이 적용됩니다. 이는 권한 정책 속성 처리 알고리즘에 의해 적용됩니다. [PERMISSIONSPOLICY]

여기서 iframe이 사용되어 비디오 사이트의 플레이어를 임베드합니다. 플레이어가 전체 화면으로 비디오를 재생할 수 있도록 allowfullscreen 속성이 필요합니다.

<article>
 <header>
  <p><img src="/usericons/1627591962735"> <b>Fred Flintstone</b></p>
  <p><a href="/posts/3095182851" rel=bookmark>12:44</a><a href="#acl-3095182851">Private Post</a></p>
 </header>
 <p>Check out my new ride!</p>
 <iframe src="https://video.example.com/embed?id=92469812" allowfullscreen></iframe>
</article>

allow 또는 allowfullscreeniframe 요소의 내용 탐색 가능 요소 내에서 해당 기능이 이미 허용되지 않은 경우, 기능에 대한 접근 권한을 부여할 수 없습니다.

Document 객체 document가 정책 제어 기능 feature을(를) 사용할 수 있는지 여부를 결정하려면 다음 단계를 실행합니다.

  1. document탐색 컨텍스트가 null이면, false를 반환합니다.

  2. document완전히 활성화된 상태가 아니면, false를 반환합니다.

  3. document, document출처에서 feature기능이 활성화되었는지 확인한 결과가 "Enabled"이면, true를 반환합니다.

  4. false를 반환합니다.

allowallowfullscreen 속성은 내용 탐색 가능 요소활성 문서권한 정책에만 영향을 미치기 때문에, iframe내용 탐색 가능 요소탐색될 때만 효과가 있습니다. 이를 추가하거나 제거해도 이미 로드된 문서에는 영향을 미치지 않습니다.


iframe 요소는 임베드된 콘텐츠가 특정 치수를 가지는 경우(예: 광고 유닛에 잘 정의된 치수가 있음) 치수 속성을 지원합니다.

iframe 요소는 절대 대체 콘텐츠를 가지지 않습니다. 항상 새로운 자식 탐색 가능 요소를 생성하며, 지정된 초기 콘텐츠가 성공적으로 사용되었는지 여부와 관계없이 작동합니다.


referrerpolicy 속성은 리퍼러 정책 속성입니다. 이 속성의 목적은 리퍼러 정책을 설정하는 것으로, iframe 속성 처리 시 사용됩니다. [REFERRERPOLICY]

loading 속성은 지연 로딩 속성입니다. 이 속성의 목적은 뷰포트 밖에 있는 iframe 요소를 로드하는 정책을 나타내는 것입니다.

loading 속성의 상태가 Eager 상태로 변경되면, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. resumptionStepsiframe 요소의 지연 로드 재개 단계로 설정합니다.

  2. resumptionSteps가 null이면, 반환합니다.

  3. iframe지연 로드 재개 단계를 null로 설정합니다.

  4. resumptionSteps를 호출합니다.


iframe 요소의 하위 요소는 아무것도 나타내지 않습니다. (레거시 사용자 에이전트에서는 iframe 요소를 지원하지 않기 때문에, 콘텐츠가 대체 콘텐츠로 작동할 수 있는 마크업으로 구문 분석됩니다.)

HTML 파서iframe 요소 내의 마크업을 텍스트로 처리합니다.


HTMLIFrameElement/src

모든 현재 엔진에서 지원됨.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

IDM 속성 src, name, sandbox, 및 allow은 각각 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

HTMLIFrameElement/srcdoc

모든 현재 엔진에서 지원됨.

Firefox25+ Safari6+ Chrome20+
Opera? Edge79+
Edge (Legacy)? Internet ExplorerNo
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

srcdoc getter 단계는 다음과 같습니다:

  1. attribute를 null, srcdoc로컬 이름, 및 this로 주어진 네임스페이스로 속성을 가져오는 결과로 설정합니다.

  2. attribute가 null이면, 빈 문자열을 반환합니다.

  3. attribute을 반환합니다.

srcdoc setter 단계는 다음과 같습니다:

  1. compliantString을(를) 신뢰할 수 있는 타입 규격 문자열 가져오기 알고리즘의 결과로, TrustedHTML, this관련 전역 객체, 주어진 값, "HTMLIFrameElement srcdoc", 및 "script"와 함께 설정합니다.

  2. 속성 값을 설정하는데, this, srcdoc로컬 이름, 및 compliantString을(를) 사용합니다.

sandboxDOMTokenList에 대해 지원되는 토큰sandbox 속성에 정의된 허용된 값들이며 사용자 에이전트가 지원하는 값들입니다.

allowFullscreen IDL 속성은 반영해야 하며, allowfullscreen 콘텐츠 속성을 반영해야 합니다.

HTMLIFrameElement/referrerPolicy

모든 현재 엔진에서 지원됨.

Firefox50+ Safari14+ Chrome52+
Opera? Edge79+
Edge (Legacy)? Internet ExplorerNo
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

referrerPolicy IDL 속성은 referrerpolicy 콘텐츠 속성을 반영해야 하며, 알려진 값들만 허용됩니다.

loading IDL 속성은 loading 콘텐츠 속성을 반영해야 하며, 알려진 값들만 허용됩니다.

HTMLIFrameElement/contentDocument

모든 현재 엔진에서 지원됨.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer8+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

contentDocument getter 단계는 this콘텐츠 문서를 반환하는 것입니다.

HTMLIFrameElement/contentWindow

모든 현재 엔진에서 지원됨.

Firefox1+ Safari3+ Chrome1+
Opera8+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

contentWindow getter 단계는 this콘텐츠 창을 반환하는 것입니다.

다음은 광고 중개업체의 광고를 포함하기 위해 iframe을 사용하는 페이지의 예입니다:

<iframe src="https://ads.example.com/?customerid=923513721&amp;format=banner"
    width="468" height="60"></iframe>

4.8.6 embed 요소

Element/embed

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLEmbedElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
임베디드 콘텐츠.
인터랙티브 콘텐츠.
직관적 콘텐츠.
이 요소가 사용될 수 있는 컨텍스트:
임베디드 콘텐츠가 예상되는 곳.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐츠 속성:
전역 속성
src — 리소스의 주소
type — 임베디드 리소스의 타입
width — 가로 차원
height — 세로 차원
네임스페이스가 없는 다른 속성(자세한 내용은 설명 참조).
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLEmbedElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString width;
  [CEReactions] attribute DOMString height;
  Document? getSVGDocument();

  // obsolete members도 포함
};

embed 요소는 외부 애플리케이션 또는 상호작용 콘텐츠와의 통합 지점을 제공합니다.

src 속성은 임베디드된 리소스의 URL을 제공합니다. 이 속성이 존재하는 경우 유효한 비어 있지 않은 URL을 포함해야 합니다.

itemprop 속성이 embed 요소에 지정된 경우 src 속성도 지정되어야 합니다.

type 속성은, 존재하는 경우 플러그인을 선택할 때 사용되는 MIME 타입을 제공합니다. 이 값은 유효한 MIME 타입 문자열이어야 합니다. type 속성과 src 속성이 모두 존재하는 경우, type 속성은 src 속성으로 제공된 리소스의 명시적 콘텐츠 타입 메타데이터와 동일한 타입을 지정해야 합니다.

다음 조건이 발생하는 동안, 해당 요소에 대해 인스턴스화된 모든 플러그인은 제거되어야 하며, embed 요소는 아무것도 나타내지 않습니다:

embed 요소는 다음 조건이 모두 동시에 충족될 때 잠재적으로 활성 상태로 간주됩니다:

embed 요소가 잠재적으로 활성 상태가 아니었을 때 잠재적으로 활성 상태가 되고, 잠재적으로 활성 상태를 유지하는 embed 요소가 src 속성이 설정, 변경, 또는 제거되거나 type 속성이 설정, 변경, 또는 제거될 때마다, 사용자 에이전트는 해당 요소에 대해 요소 작업을 큐에 추가하고, 해당 요소에 대해 embed 요소 설정 단계를 실행해야 합니다.

지정된 embed 요소설정 단계는 다음과 같습니다:

  1. 다른 작업설정 단계를 실행하기 위해 큐에 추가되었다면 반환합니다.

  2. 만약 요소src 속성이 설정되어 있다면:

    1. urlURL 인코딩-파싱의 결과로 설정하여 요소src 속성의 값을 요소노드 문서를 기준으로 상대적으로 처리합니다.

    2. 만약 url이 실패라면 반환합니다.

    3. 요청을 새 요청으로 설정하며, urlURL, 클라이언트요소노드 문서관련 설정 객체, 대상은 "embed", 자격 증명 모드는 "include", 모드는 "navigate", 발기자 유형은 "embed", URL 자격 증명 플래그가 설정되어 있는 것으로 합니다.

    4. 요청을 가져오며, 응답 처리응답 응답으로 설정합니다:

      1. 만약 작업embed 요소 설정 단계요소에 대해 실행하기 위해 큐에 추가되었다면, 반환합니다.

      2. 응답네트워크 오류인 경우, 요소에 대해 이벤트로드로 트리거하며 반환합니다.

      3. 유형콘텐츠 유형요소응답으로 결정하여 설정합니다.

      4. 유형을 다음과 같이 스위치합니다:

        null
        1. 요소에 대해 플러그인을 표시하지 않습니다.

        그 외의 경우
        1. 만약 요소내비게이션 가능 콘텐츠가 null인 경우, 요소에 대해 새 하위 내비게이션 가능 객체를 생성합니다.

        2. 요소내비게이션 가능 콘텐츠응답URL로, 요소노드 문서를 사용하여 응답응답으로, 히스토리 처리를 "대체"로 설정하여 내비게이트합니다.

          요소src 속성은 내비게이션 가능 콘텐츠가 다른 위치로 내비게이트된 경우 업데이트되지 않습니다.

        3. 요소는 이제 내비게이션 가능 콘텐츠를 나타냅니다.

      리소스를 가져오는 과정은 요소로드 이벤트를 지연시켜야 합니다.

  3. 그렇지 않으면 요소에 대해 플러그인을 표시하지 않습니다.

주어진 embed 요소 element응답 response에 대해 콘텐츠 유형을 결정하려면 다음 단계를 수행하십시오:

  1. 요소type 속성이 있으며 해당 속성의 값이 플러그인이 지원하는 유형인 경우, type 속성의 값을 반환합니다.

  2. 만약 응답경로플러그인이 지원하는 패턴과 일치한다면, 해당 플러그인이 처리할 수 있는 유형을 반환합니다.

    예를 들어, 플러그인은 .swf로 끝나는 경로 컴포넌트를 처리할 수 있다고 할 수 있습니다.

  3. 만약 응답명시적 콘텐츠 타입 메타데이터가 있고, 해당 값이 플러그인이 지원하는 유형이라면, 해당 값을 반환합니다.

  4. null을 반환합니다.

위 알고리즘이 응답정상 상태가 아닌 경우도 허용하는 것은 의도된 것입니다. 이렇게 하면 서버가 오류 응답(예: HTTP 500 내부 서버 오류 코드)에도 불구하고 플러그인 데이터를 반환할 수 있습니다.

플러그인을 표시하지 않으려면 embed 요소 요소에 대해 다음 단계를 실행합니다:

  1. 요소에 대해 하위 내비게이션 가능 객체를 파괴합니다.

  2. 요소에 대해 플러그인을 찾을 수 없다는 표시를 표시하고, 그 내용을 요소로 설정합니다.

  3. 요소는 이제 아무것도 나타내지 않습니다.

embed 요소에는 대체 콘텐츠가 없으며, 후손 요소는 무시됩니다.

embed 요소가 잠재적으로 활성 상태를 멈추면, 해당 요소에 대해 인스턴스화된 모든 플러그인이 언로드되어야 합니다.

embed 요소는 로드 이벤트를 지연시킬 가능성이 있습니다.

embed 요소는 차원 속성을 지원합니다.

IDL 속성 srctype은 각각 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

4.8.7 object 요소

요소/object

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (레거시)12+인터넷 익스플로러
Firefox 안드로이드?Safari iOS?Chrome 안드로이드?WebView 안드로이드?삼성 인터넷?Opera 안드로이드?

HTMLObjectElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+인터넷 익스플로러5.5+
Firefox 안드로이드?Safari iOS1+Chrome 안드로이드?WebView 안드로이드?삼성 인터넷?Opera 안드로이드12.1+
범주:
흐름 콘텐츠.
구 문 콘텐츠.
포함된 콘텐츠.
목록에 나열됨 폼 관련 요소.
명확한 콘텐츠.
이 요소가 사용할 수 있는 문맥:
포함된 포함된 콘텐츠가 예상되는 경우.
콘텐츠 모델:
투명.
태그 생략 in text/html:
태그 생략은 불가능합니다.
콘텐츠 속성:
전역 속성
data — 리소스의 주소
type — 포함된 리소스의 유형
name탐색 가능한 콘텐츠의 이름
form — 이 요소를 요소와 연결
width — 수평 차원
height — 수직 차원
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
인터페이스 HTMLObjectElement : HTMLElement {
  [HTMLConstructor] 생성자();

  [CEReactions] 속성 USVString data;
  [CEReactions] 속성 DOMString type;
  [CEReactions] 속성 DOMString name;
  readonly 속성 HTMLFormElement? form;
  [CEReactions] 속성 DOMString width;
  [CEReactions] 속성 DOMString height;
  readonly 속성 문서? contentDocument;
  readonly 속성 WindowProxy? contentWindow;
  문서? getSVGDocument();

  readonly 속성 boolean willValidate;
  readonly 속성 ValidityState validity;
  readonly 속성 DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  // 또한 사용되지 않는 멤버를 포함합니다
};

object 요소에 의해 인스턴스화된 콘텐츠의 유형에 따라, 노드는 다른 인터페이스도 지원합니다.

object 요소는 외부 리소스를 나타낼 수 있으며, 리소스의 유형에 따라 이미지 또는 자식 탐색 가능으로 처리됩니다.

data 속성은 리소스의 URL을 지정합니다. 이 속성은 필수이며, 공백으로 둘러싸일 수 있는 유효한 비어 있지 않은 URL을 포함해야 합니다.

type 속성이 존재하는 경우, 리소스의 유형을 지정합니다. 속성이 존재하는 경우, 속성은 유효한 MIME 타입 문자열이어야 합니다.

name 속성이 존재하는 경우, 유효한 탐색 가능한 대상 이름이어야 합니다. 주어진 값은 요소의 탐색 가능한 콘텐츠의 이름으로 사용되며, 적용 가능한 경우 요소의 탐색 가능한 콘텐츠새 자식 탐색 가능을 생성할 때 존재해야 합니다.

다음 조건 중 하나가 발생할 때마다:

...사용자 에이전트는 object 요소를 지정하여 요소 작업을 큐에 넣어 다음 단계를 수행하여 object 요소가 무엇을 나타내는지 다시 결정해야 합니다. 이 작업큐에 있거나 적극적으로 실행 중인 경우, 요소의 노드 문서의 로드 이벤트를 지연시켜야 합니다.

  1. 사용자가 이 object 요소의 대체 콘텐츠를 기본 동작 대신 표시하도록 선호를 표시한 경우, 아래의 대체로 표시된 단계로 건너뜁니다.

    예를 들어, 사용자는 이 콘텐츠가 사용자가 더 접근하기 쉬운 형식을 사용하기 때문에 요소의 대체 콘텐츠를 표시하도록 요청할 수 있습니다.

  2. 요소가 조상 미디어 요소를 가지고 있거나, 조상 object 요소가 대체 콘텐츠를 표시하지 않는 경우, 또는 요소가 문서에 포함되지 않은 경우 비활성 탐색 컨텍스트를 가지고 있는 경우, 또는 요소의 노드 문서가 완전히 활성화되지 않은 경우, 또는 요소가 열린 요소 스택에 있는 경우, 또는 요소가 렌더링되지 않는 경우, 아래의 대체로 표시된 단계로 건너뜁니다.

  3. data 속성이 존재하고 값이 비어 있지 않은 경우:

    1. type 속성이 존재하고 값이 사용자 에이전트가 지원하는 유형이 아닌 경우, 사용자 에이전트는 콘텐츠의 실제 유형을 검사하지 않고 아래의 대체로 표시된 단계로 건너뛸 수 있습니다.

    2. 속성의 값을 URL로 인코딩-파싱하여 data 속성의 값을 요소의 노드 문서에 상대적으로 파싱한 결과를 url로 둡니다.

    3. url이 실패한 경우, 요소에서 오류라는 이름의 이벤트를 발생시키고 아래의 대체로 표시된 단계로 건너뜁니다.

    4. request라는 새 요청을 만듭니다. 이 요청의 URLurl이며, 클라이언트는 요소의 노드 문서관련 설정 객체, 목적지는 "object", 자격 증명 모드는 "포함", 모드는 "탐색", 발신자 유형은 "object", URL 자격 증명 플래그가 설정된 상태입니다.

    5. 요청요청합니다.

      리소스를 가져오는 것은 요소의 노드 문서의 로드 이벤트를 지연시켜야 합니다. 리소스가 페치된 후 작업에 의해 큐에 추가된 작업이 실행되면 이 작업이 실행됩니다.

    6. 리소스가 아직 사용 가능하지 않은 경우 (예: 리소스가 캐시에 없어서 리소스를 로드하려면 네트워크 요청이 필요함), 아래의 대체로 표시된 단계로 건너뜁니다. 리소스가 사용 가능해지면 네트워킹 작업 소스에 의해 큐에 추가된 작업은 이 알고리즘을 이 단계에서 다시 시작해야 합니다. 리소스는 점진적으로 로드될 수 있으며, 사용자 에이전트는 리소스의 일부만 로드되더라도 리소스가 사용 가능하다고 간주할 수 있습니다.

    7. 로드가 실패한 경우 (예: HTTP 404 오류, DNS 오류 등), 요소에서 오류라는 이름의 이벤트를 발생시키고 아래의 대체로 표시된 단계로 건너뜁니다.

    8. 리소스 유형을 다음과 같이 결정합니다:

      1. 리소스 유형을 알 수 없음으로 설정합니다.

      2. 사용자 에이전트가 이 리소스에 대한 Content-Type 헤더를 엄격하게 준수하도록 구성되어 있고, 리소스에 관련된 Content-Type 메타데이터가 있는 경우, 리소스 유형리소스의 Content-Type 메타데이터에 지정된 유형으로 설정하고 아래의 처리기로 표시된 단계로 건너뜁니다.

        이로 인해 보안 취약점이 발생할 수 있습니다. 예를 들어, 사이트가 특정 유형을 사용하는 리소스를 포함하려고 하지만 원격 사이트가 이를 재정의하여 대신 사용자 에이전트에 다른 유형의 콘텐츠를 제공하여 다른 보안 특성을 트리거하는 경우입니다.

      3. 다음 목록에서 적절한 단계 집합을 실행합니다:

        리소스에 관련된 Content-Type 메타데이터가 있는 경우
        1. binary를 false로 설정합니다.

        2. 리소스의 Content-Type 메타데이터에 지정된 유형이 "text/plain"이고, 리소스가 텍스트 또는 바이너리 리소스를 구분하기 위한 규칙을 적용한 결과 텍스트가 아닌 경우, binary를 true로 설정합니다.

        3. 리소스의 Content-Type 메타데이터에 지정된 유형이 "application/octet-stream"인 경우, binary를 true로 설정합니다.

        4. binary가 false인 경우, 리소스 유형을 리소스의 Content-Type 메타데이터에 지정된 유형으로 설정하고 아래의 처리기로 표시된 단계로 건너뜁니다.

        5. type 속성이 object 요소에 존재하고 그 값이 application/octet-stream이 아닌 경우, 다음 단계를 실행합니다:

          1. 속성 값이 "image/"로 시작하고 XML MIME 타입이 아닌 경우, 리소스 유형을 해당 type 속성에 지정된 유형으로 설정합니다.

          2. 아래의 처리기로 표시된 단계로 건너뜁니다.

        리소스에 관련된 Content-Type 메타데이터가 없는 경우
        1. type 속성이 object 요소에 존재하는 경우, 잠정 유형을 해당 type 속성에 지정된 유형으로 설정합니다.

          그렇지 않은 경우, 잠정 유형을 리소스의 계산된 유형으로 설정합니다.

        2. 잠정 유형application/octet-stream이 아닌 경우, 리소스 유형잠정 유형으로 설정하고 아래의 처리기로 표시된 단계로 건너뜁니다.

      4. 명시된 리소스의 URL에 URL 파서 알고리즘을 적용한 결과(리디렉션 후), URL 레코드의 경로 구성 요소가 플러그인에서 지원하는 패턴과 일치하는 경우, 리소스 유형을 해당 플러그인이 처리할 수 있는 유형으로 설정합니다.

        예를 들어, 플러그인은 ".swf" 네 글자 문자열로 끝나는 경로 구성 요소를 처리할 수 있다고 할 수 있습니다.

      이 단계가 완료되거나 위의 하위 단계 중 하나가 다음 단계로 바로 넘어가면 리소스 유형이 여전히 알 수 없을 수 있습니다. 두 경우 모두 다음 단계에서 대체가 트리거됩니다.

    9. 처리기: 다음 중 일치하는 첫 번째 경우에 따라 콘텐츠를 처리합니다:

      리소스 유형이 XML MIME 타입이거나 리소스 유형이 "image/"로 시작하지 않는 경우

      object 요소의 탐색 가능한 콘텐츠가 null인 경우, 요소에 대해 새 자식 탐색 가능을 생성합니다.

      response응답으로 설정합니다. 가져오기.

      responseURLabout:blank와 일치하지 않으면, 요소의 노드 문서를 사용하여 요소의 탐색 가능한 콘텐츠historyHandling을 "대체"로 설정하여 탐색합니다.

      data 속성의 object 요소는 탐색 가능한 콘텐츠가 다른 위치로 탐색된 경우 업데이트되지 않습니다.

      object 요소는 자신의 탐색 가능한 콘텐츠를 나타냅니다.

      리소스 유형이 "image/"로 시작하고 이미지 지원이 비활성화되지 않은 경우

      자식 탐색 가능을 파괴합니다. object 요소를 주어진 대로.

      이미지를 위한 스니핑 규칙을 적용하여 이미지 유형을 결정합니다.

      object 요소는 지정된 이미지를 나타냅니다.

      이미지를 렌더링할 수 없는 경우, 예를 들어 잘못된 형식이거나 지원되지 않는 형식인 경우, 아래의 대체로 표시된 단계로 건너뜁니다.

      그 외의 경우

      지정된 리소스 유형은 지원되지 않습니다. 아래의 대체로 표시된 단계로 건너뜁니다.

      이전 단계가 리소스 유형을 알 수 없음으로 끝난 경우, 이 경우가 트리거됩니다.

    10. 요소의 콘텐츠는 object 요소가 나타내는 콘텐츠의 일부가 아닙니다.

    11. object 요소가 탐색 가능한 콘텐츠를 나타내지 않는 경우, 리소스가 완전히 로드된 후, 요소의 object 요소에 주어진 요소 작업을 큐에 넣어 이벤트로드라는 이름으로 발생시킵니다.

      요소가 탐색 가능한 콘텐츠를 나타내는 경우, 생성된 document완전히 로드될 때 유사한 작업이 큐에 추가됩니다.

    12. 반환합니다.

  4. 대체: object 요소는 자식 요소를 나타냅니다. 이것이 요소의 대체 콘텐츠입니다. 요소에 대해 자식 탐색 가능을 파괴합니다.

위 알고리즘에 따라, object 요소의 콘텐츠는 참조된 리소스를 표시할 수 없는 경우(예: 404 오류가 반환된 경우) 사용되는 대체 콘텐츠로 작동합니다. 이를 통해 여러 object 요소를 서로 중첩하여 서로 다른 기능을 가진 여러 사용자 에이전트를 대상으로 할 수 있으며, 사용자 에이전트는 자신이 지원하는 첫 번째 요소를 선택합니다.

object 요소는 로드 이벤트를 지연시킬 수 있습니다.

form 속성은 object 요소를 폼 소유자와 명시적으로 연결하는 데 사용됩니다.

object 요소는 크기 속성을 지원합니다.

HTMLObjectElement/data

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLObjectElement/type

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+

HTMLObjectElement/name

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+

IDL 속성 data, type, 그리고 name은 각각 동일한 이름의 관련 콘텐츠 속성을 반영해야 합니다.

HTMLObjectElement/contentDocument

모든 현재 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

contentDocument getter 단계는 이것콘텐츠 문서를 반환하는 것입니다.

HTMLObjectElement/contentWindow

모든 현재 엔진에서 지원합니다.

Firefox22+Safari13+Chrome53+
Opera?Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

contentWindow getter 단계는 이것콘텐츠 윈도우를 반환하는 것입니다.

willValidate, validity, 그리고 validationMessage 속성과, checkValidity(), reportValidity(), setCustomValidity() 메서드는 제약 조건 검증 API의 일부입니다. form IDL 속성은 요소의 폼 API의 일부입니다.

이 예제에서는 object 요소를 사용하여 HTML 페이지를 다른 페이지에 포함합니다.

<figure>
<object data="clock.html"></object>
<figcaption>My HTML Clock</figcaption>
</figure>

4.8.8 video 요소

요소/video

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLVideoElement

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
범주:
플로우 콘텐츠.
구문 콘텐츠.
내장 콘텐츠.
이 요소가 controls 속성을 가지고 있는 경우: 인터랙티브 콘텐츠.
감지 가능한 콘텐츠.
이 요소가 사용될 수 있는 문맥:
내장 콘텐츠가 예상되는 곳.
콘텐츠 모델:
이 요소가 src 속성을 가지고 있는 경우: 0개 이상의 track 요소, 그 후 투명, 하지만 미디어 요소 하위 요소는 없음.
이 요소가 src 속성을 가지고 있지 않은 경우: 0개 이상의 source 요소, 그 후 0개 이상의 track 요소, 그 후 투명, 하지만 미디어 요소 하위 요소는 없음.
text/html에서의 태그 생략:
둘 중 어느 태그도 생략할 수 없음.
콘텐츠 속성:
글로벌 속성
src — 리소스의 주소
crossorigin — 이 요소가 교차 출처 요청을 처리하는 방법
poster — 비디오 재생 전에 표시할 포스터 프레임
preload미디어 리소스에 얼마나 많은 버퍼링이 필요할 것 같은지에 대한 힌트
autoplay — 페이지가 로드될 때 미디어 리소스가 자동으로 시작될 수 있다는 힌트
playsinline — 사용자 에이전트가 요소의 재생 영역 내에서 비디오 콘텐츠를 표시하도록 권장
loop미디어 리소스를 반복할지 여부
muted — 기본적으로 미디어 리소스를 음소거할지 여부
controls — 사용자 에이전트 제어 표시
width — 수평 크기
height — 수직 크기
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLVideoElement : HTMLMediaElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long width;
  [CEReactions] attribute unsigned long height;
  readonly attribute unsigned long videoWidth;
  readonly attribute unsigned long videoHeight;
  [CEReactions] attribute USVString poster;
  [CEReactions] attribute boolean playsInline;
};

video 요소는 비디오나 영화를 재생하거나 자막이 포함된 오디오 파일을 재생하는 데 사용됩니다.

video 요소 내부에 콘텐츠를 제공할 수 있습니다. 사용자 에이전트는 이 콘텐츠를 사용자에게 표시하지 않아야 합니다. 이 콘텐츠는 비디오를 지원하지 않는 이전 웹 브라우저용으로 의도된 것으로, 이러한 이전 브라우저의 사용자에게 비디오 콘텐츠에 접근하는 방법을 안내하는 텍스트가 표시되도록 합니다.

특히, 이 콘텐츠는 접근성 문제를 해결하기 위한 것이 아닙니다. 시각 장애인, 청각 장애인, 청각 장애인 및 기타 신체적 또는 인지적 장애를 가진 사용자를 위해 비디오 콘텐츠를 접근 가능하게 만드는 다양한 기능이 제공됩니다. 자막은 비디오 스트림에 내장되거나 track 요소를 사용하여 외부 파일로 제공될 수 있습니다. 수화 트랙은 비디오 스트림에 내장될 수 있습니다. 오디오 설명은 비디오 스트림에 내장되거나 WebVTT 파일을 사용하여 텍스트 형식으로 제공될 수 있으며, 사용자 에이전트에 의해 음성으로 변환될 수 있습니다. WebVTT는 또한 챕터 제목을 제공하는 데 사용할 수 있습니다. 미디어 요소를 전혀 사용하지 않으려는 사용자에게는, video 요소 근처의 텍스트에서 간단히 링크하여 대본 또는 다른 텍스트 대안을 제공할 수 있습니다. [WEBVTT]

video 요소는 미디어 요소로, 그 미디어 데이터는 명목상 비디오 데이터이며, 관련 오디오 데이터가 있을 수 있습니다.

src, crossorigin, preload, autoplay, loop, mutedcontrols 속성은 모든 미디어 요소에 공통된 속성입니다.

poster 속성은 사용자 에이전트가 비디오 데이터가 없는 동안 표시할 수 있는 이미지 파일의 URL을 제공합니다. 속성이 존재하는 경우, 공백으로 둘러싸일 수 있는 유효한 비어 있지 않은 URL을 포함해야 합니다.

지정된 리소스를 사용해야 하는 경우, 요소가 생성되거나 poster 속성이 설정, 변경 또는 제거될 때, 사용자 에이전트는 요소의 포스터 프레임을 결정하기 위해 다음 단계를 실행해야 합니다(요소의 포스터 표시 플래그의 값에 관계없이):

  1. video 요소에 대해 실행 중인 이 알고리즘의 인스턴스가 있는 경우, 포스터 프레임을 변경하지 않고 해당 인스턴스를 중단합니다.

  2. poster 속성의 값이 빈 문자열이거나 속성이 없는 경우 포스터 프레임이 없으므로 반환합니다.

  3. urlposter 속성의 값을 요소의 노드 문서와 상대적으로 URL을 인코딩-파싱한 결과로 설정합니다.

  4. url이 실패인 경우, 반환합니다. 포스터 프레임이 없습니다.

  5. request를 새로운 요청으로 설정하며, 그 URLurl, 클라이언트는 요소의 노드 문서관련 설정 객체, 대상은 "image", 시작자 유형은 "video", 자격 증명 모드는 "include"이며, 그 URL 자격 증명 플래그가 설정됩니다.

  6. 요청request합니다. 이는 요소의 노드 문서로드 이벤트를 지연시켜야 합니다.

  7. 이렇게 얻은 이미지가 있는 경우, 포스터 프레임은 해당 이미지입니다. 그렇지 않으면 포스터 프레임이 없습니다.

poster 속성으로 제공되는 이미지, 포스터 프레임은 사용자가 비디오가 어떤지에 대한 아이디어를 얻을 수 있도록 비디오의 대표 프레임(일반적으로 첫 번째 비어 있지 않은 프레임 중 하나)으로 의도된 것입니다.

playsinline 속성은 불리언 속성입니다. 이 속성이 존재하면, 비디오는 전체 화면이나 독립적인 크기 조정 가능한 창으로 표시되는 대신 기본적으로 문서 내에서 "인라인"으로 표시되어야 한다는 힌트를 사용자 에이전트에 제공합니다.

playsinline 속성이 없다고 해서 비디오가 기본적으로 전체 화면으로 표시된다는 것을 의미하지는 않습니다. 실제로 대부분의 사용자 에이전트는 기본적으로 모든 비디오를 인라인으로 재생하도록 선택했으며, 이러한 사용자 에이전트에서는 playsinline 속성이 아무런 영향을 미치지 않습니다.


video 요소는 아래 목록에서 첫 번째 일치 조건에 대해 주어진 것을 나타냅니다:

비디오 데이터가 없는 경우(요소의 readyState 속성이 HAVE_NOTHING 또는 HAVE_METADATA 이지만 비디오 데이터가 전혀 얻어지지 않았거나 요소의 readyState 속성이 이후 값으로 설정되어 있지만 미디어 리소스에 비디오 채널이 없는 경우)
video 요소는 포스터 프레임을 나타내며, 포스터 프레임이 있는 경우 또는 그렇지 않으면 투명한 검정과 자연 크기가 없습니다.
video 요소가 일시 중지되고, 현재 재생 위치가 비디오의 첫 번째 프레임인 경우, 요소의 포스터 표시 플래그가 설정됨
video 요소는 포스터 프레임을 나타내며, 포스터 프레임이 있는 경우 또는 그렇지 않으면 비디오의 첫 번째 프레임을 나타냅니다.
video 요소가 일시 중지되었으며, 현재 재생 위치에 해당하는 비디오 프레임이 사용할 수 없는 경우(예: 비디오가 탐색 중이거나 버퍼링 중이기 때문에)
video 요소가 잠재적으로 재생 중이거나 일시 중지 상태가 아닌 경우(예: 탐색 중이거나 멈춘 경우)
video 요소는 마지막으로 렌더링된 비디오 프레임을 나타냅니다.
video 요소가 일시 중지된 경우
video 요소는 현재 재생 위치에 해당하는 비디오 프레임을 나타냅니다.
그 외의 경우(video 요소가 비디오 채널을 가지고 있으며 잠재적으로 재생 중인 경우)
video 요소는 계속 증가하는 "현재" 위치에서 비디오 프레임을 나타냅니다. 현재 재생 위치가 변경되어 마지막으로 렌더링된 프레임이 비디오의 현재 재생 위치에 해당하지 않게 되면, 새 프레임이 렌더링되어야 합니다.

비디오 프레임은 선택된 비디오 트랙에서 얻어야 하며, 이벤트 루프가 마지막으로 1단계에 도달했을 때 이뤄져야 합니다.

비디오 스트림에서 특정 재생 위치에 해당하는 프레임은 비디오 스트림의 형식에 의해 정의됩니다.

video 요소는 또한 텍스트 트랙 큐텍스트 트랙 큐 활성 플래그가 설정되어 있고, 텍스트 트랙표시 중 모드에 있을 경우 이들을 나타냅니다. 그리고 미디어 리소스에서 나오는 오디오를 현재 재생 위치에서 동기화된 상태로 나타냅니다.

비디오 리소스와 연관된 오디오는, 재생되는 경우, 요소의 실효 미디어 볼륨에서 현재 재생 위치에서 동기화되어 재생되어야 합니다. 사용자 에이전트는 오디오 트랙에서 활성화된 트랙을 재생해야 하며, 이벤트 루프가 마지막으로 1단계에 도달했을 때 이러한 트랙이 활성화되어야 합니다.

위 내용 외에도, 사용자 에이전트는 비디오에 텍스트 또는 아이콘을 오버레이하거나 요소의 재생 영역의 다른 부분에 적절한 방식으로 텍스트 또는 아이콘을 오버레이하여 사용자가 "버퍼링 중", "비디오가 로드되지 않음", "오류" 또는 더 자세한 정보를 받을 수 있도록 할 수 있습니다.

비디오를 렌더링할 수 없는 사용자 에이전트는 대신 요소가 외부 비디오 재생 유틸리티 또는 비디오 데이터 자체로 연결되는 링크를 나타내도록 할 수 있습니다.

video 요소의 미디어 리소스가 비디오 채널을 가지고 있는 경우, 요소는 페인트 소스를 제공하며, 그 너비는 미디어 리소스자연 너비, 높이는 미디어 리소스자연 높이이며, 현재 재생 위치에 해당하는 비디오 프레임의 모습이며, 해당 비디오 프레임이 사용할 수 없는 경우(예: 비디오가 탐색 중이거나 버퍼링 중인 경우) 이전 모습이거나(있는 경우) 그렇지 않으면(예: 비디오가 첫 번째 프레임을 아직 로드 중인 경우) 검정색입니다.


video.videoWidth

HTMLVideoElement/videoWidth

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
video.videoHeight

HTMLVideoElement/videoHeight

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

이 속성들은 비디오의 본래 크기를 반환하거나, 크기를 알 수 없는 경우 0을 반환합니다.

비디오의 본래 너비본래 높이미디어 리소스의 크기, 종횡비, 클린 아퍼처, 해상도 등을 고려한 후의 CSS 픽셀로 표현된 크기입니다. 자막 포맷이 비디오 데이터의 크기에 어떻게 종횡비를 적용하여 "올바른" 크기를 얻을지 정의하지 않는 경우, 사용자 에이전트는 한 차원을 늘리고 다른 차원을 변경하지 않음으로써 이 비율을 적용해야 합니다.

videoWidth IDL 속성은 비디오의 본래 너비CSS 픽셀 단위로 반환해야 합니다. videoHeight IDL 속성은 비디오의 본래 높이CSS 픽셀 단위로 반환해야 합니다. 요소의 readyState 속성이 HAVE_NOTHING 인 경우 이 속성은 0을 반환해야 합니다.

비디오의 본래 너비본래 높이가 변경될 때마다 (예를 들어, 선택된 비디오 트랙이 변경된 경우 포함), 요소의 readyState 속성이 HAVE_NOTHING 이 아닌 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가해야 하며, 이벤트resize라는 이름으로 미디어 요소에서 발생시켜야 합니다.

video 요소는 크기 속성을 지원합니다.

다른 스타일 규칙이 없는 경우, 비디오 콘텐츠는 요소의 재생 영역 내에 최대 크기로 렌더링되어야 하며, 비디오 콘텐츠의 종횡비가 유지되어야 합니다. 따라서 재생 영역의 종횡비가 비디오의 종횡비와 일치하지 않는 경우, 비디오는 레터박스 또는 필러박스로 표시됩니다. 요소의 재생 영역의 비디오를 포함하지 않는 부분은 아무것도 나타내지 않습니다.

CSS를 구현한 사용자 에이전트에서는 위 요구 사항을 렌더링 섹션에서 제안된 스타일 규칙을 사용하여 구현할 수 있습니다.

video 요소의 재생 영역의 본래 너비포스터 프레임이 사용 가능하고 현재 요소가 포스터 프레임을 나타내는 경우, 포스터 프레임의 본래 너비입니다. 그렇지 않으면 비디오 리소스의 본래 너비입니다. 그렇지 않으면 본래 너비는 존재하지 않습니다.

video 요소의 재생 영역의 본래 높이포스터 프레임이 사용 가능하고 현재 요소가 포스터 프레임을 나타내는 경우, 포스터 프레임의 본래 높이입니다. 그렇지 않으면 비디오 리소스의 본래 높이입니다. 그렇지 않으면 본래 높이는 존재하지 않습니다.

기본 객체 크기는 너비가 300 CSS 픽셀 이며, 높이가 150 CSS 픽셀입니다. [CSSIMAGES]


사용자 에이전트는 자막, 오디오 설명 트랙 및 비디오 스트림과 관련된 기타 추가 데이터를 표시하거나 비활성화할 수 있는 제어 기능을 제공해야 합니다. 이러한 기능은 다시 말하지만 페이지의 정상적인 렌더링을 방해하지 않아야 합니다.

사용자 에이전트는 사용자가 전체 화면 또는 독립적인 크기 조정 가능 창과 같은 사용자에게 더 적합한 방식으로 비디오 콘텐츠를 볼 수 있도록 허용할 수 있습니다. 사용자 에이전트는 비디오를 재생할 때 기본적으로 이러한 보기 모드를 트리거할 수 있지만, playsinline 속성이 지정된 경우에는 그렇게 하지 않아야 합니다. 다른 사용자 인터페이스 기능과 마찬가지로 이를 활성화하는 제어는 사용자 에이전트가 사용자 인터페이스를 노출하지 않는 한 페이지의 정상적인 렌더링을 방해하지 않아야 합니다. 그러나 이러한 독립적인 보기 모드에서는 controls 속성이 없어도 전체 사용자 인터페이스를 표시할 수 있습니다.

사용자 에이전트는 비디오 재생이 진행되는 동안 화면 보호기를 비활성화하는 등 사용자의 경험을 방해할 수 있는 시스템 기능에 비디오 재생이 영향을 미치도록 할 수 있습니다.


poster IDL 속성은 poster 콘텐츠 속성을 반영해야 합니다.

playsInline IDL 속성은 반영해야 합니다. playsinline 콘텐츠 속성을 반영해야 합니다.

이 예제는 비디오 재생이 실패했을 때 이유를 알려주는 메시지를 표시하는 방법을 보여줍니다:

<script>
 function failed(e) {
   // 비디오 재생이 실패했습니다 - 그 이유를 설명하는 메시지를 표시하세요
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('비디오 재생이 중단되었습니다.');
       break;
     case e.target.error.MEDIA_ERR_NETWORK:
       alert('네트워크 오류로 인해 비디오 다운로드가 중간에 실패했습니다.');
       break;
     case e.target.error.MEDIA_ERR_DECODE:
       alert('비디오 재생이 중단되었습니다. 손상 문제나 브라우저에서 지원하지 않는 기능을 사용하는 비디오 때문일 수 있습니다.');
       break;
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
       alert('서버나 네트워크 오류로 인해 비디오를 로드할 수 없었거나, 형식이 지원되지 않습니다.');
       break;
     default:
       alert('알 수 없는 오류가 발생했습니다.');
       break;
   }
 }
</script>
<p><video src="tgif.vid" autoplay controls onerror="failed(event)"></video></p>
<p><a href="tgif.vid">비디오 파일 다운로드</a>.</p>

4.8.9 audio 요소

Element/audio

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android3+Samsung Internet?Opera Android11+

HTMLAudioElement

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
임베디드 콘텐츠.
요소에 controls 속성이 있는 경우: 인터랙티브 콘텐츠.
요소에 controls 속성이 있는 경우: 구체적인 콘텐츠.
이 요소를 사용할 수 있는 문맥:
임베디드 콘텐츠가 예상되는 곳.
콘텐츠 모델:
요소에 src 속성이 있는 경우: 0개 이상의 track 요소, 그런 다음 투명, 단 미디어 요소의 하위 요소는 포함하지 않음.
요소에 src 속성이 없는 경우: 0개 이상의 source 요소, 그런 다음 0개 이상의 track 요소, 그런 다음 투명, 단 미디어 요소의 하위 요소는 포함하지 않음.
text/html에서 태그 생략:
태그를 생략할 수 없음.
콘텐츠 속성:
글로벌 속성
src — 리소스의 주소
crossorigin — 요소가 CORS 요청을 처리하는 방법
preload미디어 리소스가 얼마나 많은 버퍼링이 필요할지 힌트
autoplay미디어 리소스를 페이지가 로드될 때 자동으로 시작할 수 있는지 힌트
loop미디어 리소스를 반복할지 여부
muted — 기본적으로 미디어 리소스를 음소거할지 여부
controls — 사용자 에이전트 제어 표시
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window,
 LegacyFactoryFunction=Audio(optional DOMString src)]
interface HTMLAudioElement : HTMLMediaElement {
  [HTMLConstructor] constructor();
};

audio 요소는 소리 또는 오디오 스트림을 나타냅니다.

컨텐츠는 audio 요소 안에 제공될 수 있습니다. 사용자 에이전트는 이 콘텐츠를 사용자에게 표시해서는 안 됩니다. 이 콘텐츠는 audio를 지원하지 않는 구형 웹 브라우저를 위해 제공되며, 이러한 구형 브라우저 사용자에게 오디오 콘텐츠에 접근하는 방법을 알려주는 텍스트가 표시될 수 있습니다.

특히 이 콘텐츠는 접근성 문제를 해결하기 위한 것이 아닙니다. 청각 장애인이나 기타 신체적, 인지적 장애를 가진 사람들이 오디오 콘텐츠에 접근할 수 있도록 다양한 기능이 제공됩니다. 자막이나 수화 비디오가 있는 경우, 사용자는 시각적 대안을 활성화할 수 있도록 video 요소를 사용하여 오디오를 재생할 수 있습니다. 내비게이션을 돕기 위해 track 요소와 WebVTT 파일을 사용하여 챕터 제목을 제공할 수 있습니다. 그리고 자연스럽게, 단순히 audio 요소 근처의 산문에서 이들에게 링크를 제공하여 텍스트 대체물이나 다른 대안을 제공할 수 있습니다. [WEBVTT]

audio 요소는 미디어 요소로서 그 미디어 데이터는 본질적으로 오디오 데이터입니다.

src, crossorigin, preload, autoplay, loop, muted, 그리고 controls 속성은 모든 미디어 요소에 공통된 속성입니다.

audio = new Audio([ url ])

HTMLAudioElement/Audio

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

새로운 audio 요소를 반환하며, 해당되는 경우 전달된 인수의 값을 사용하여 src 속성이 설정됩니다.

유산 팩토리 함수는 HTMLAudioElement 객체를 생성하기 위해 제공됩니다 (DOM의 createElement()와 같은 팩토리 메서드 외에도): Audio(src). 호출될 때, 유산 팩토리 함수는 다음 단계를 수행해야 합니다:

  1. document현재 글로벌 객체관련 Document로 설정합니다.

  2. audio요소를 생성한 결과로 설정하고, document, audio, 그리고 HTML 네임스페이스를 사용합니다.

  3. 속성 값을 설정하여 audio에 "preload"와 "auto"를 사용합니다.

  4. src가 제공된 경우, "src"와 src를 사용하여 audio속성 값을 설정합니다. (이것은 객체의 리소스 선택 알고리즘을 반환 전에 호출하도록 사용자 에이전트에게 지시합니다.)

  5. audio를 반환합니다.

4.8.10 track 요소

Element/track

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android25+WebView Android?Samsung Internet?Opera Android12.1+

HTMLTrackElement

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
미디어 요소의 자식으로, 플로우 콘텐츠 전에 사용합니다.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
종료 태그가 없습니다.
콘텐츠 속성:
전역 속성
kind — 텍스트 트랙의 유형
src — 리소스의 주소
srclang — 텍스트 트랙의 언어
label — 사용자에게 표시되는 레이블
default — 다른 텍스트 트랙이 더 적합하지 않을 경우 트랙을 활성화합니다.
접근성 고려사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTrackElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString kind;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString srclang;
  [CEReactions] attribute DOMString label;
  [CEReactions] attribute boolean default;

  const unsigned short NONE = 0;
  const unsigned short LOADING = 1;
  const unsigned short LOADED = 2;
  const unsigned short ERROR = 3;
  readonly attribute unsigned short readyState;

  readonly attribute TextTrack track;
};

track 요소는 저자가 미디어 요소에 대한 명시적인 외부 타임드 텍스트 트랙을 지정할 수 있도록 합니다. 이 요소 자체는 아무것도 나타내지 않습니다.

kind 속성은 열거형 속성이며, 다음 키워드 및 상태를 가집니다:

키워드 상태 간략한 설명
subtitles 자막 대화의 전사 또는 번역으로, 소리는 들리지만 이해되지 않을 때 적합합니다 (예: 사용자가 미디어 리소스의 오디오 트랙의 언어를 이해하지 못하는 경우). 비디오에 오버레이됩니다.
captions 캡션 대화, 음향 효과, 관련 음악 신호 및 기타 관련 오디오 정보를 전사하거나 번역한 것으로, 소리가 없거나 명확하게 들리지 않을 때 적합합니다 (예: 소리가 음소거되었거나 주변 소음에 의해 묻혔거나 사용자가 청각 장애인인 경우). 비디오에 오버레이되며, 청각 장애인에게 적합한 것으로 레이블링됩니다.
descriptions 설명 미디어 리소스의 비디오 구성 요소를 설명하는 텍스트로, 시각적 구성 요소가 가려지거나 사용할 수 없거나 화면이 없는 상태에서 응용 프로그램과 상호 작용하는 경우 (예: 운전 중이거나 사용자가 시각 장애인인 경우) 오디오로 합성됩니다.
chapters 챕터 메타데이터 스크립트에서 사용하기 위한 트랙입니다. 사용자 에이전트에 의해 표시되지 않습니다.
metadata 메타데이터

속성의 누락된 값 기본값자막 상태이며, 잘못된 값 기본값메타데이터 상태입니다.

src 속성은 텍스트 트랙 데이터의 URL을 제공합니다. 값은 유효한 비어 있지 않은 URL이어야 합니다 (주위에 공백이 있을 수 있음). 이 속성은 필수입니다.

요소는 초기 상태로 빈 문자열을 가지는 관련 트랙 URL (문자열)을 가집니다.

요소의 src 속성이 설정되면 다음 단계를 실행합니다:

  1. trackURL을 실패로 설정합니다.

  2. value를 요소의 src 속성 값으로 설정합니다.

  3. value가 빈 문자열이 아니면, trackURLURL을 인코딩, 파싱 및 직렬화한 결과로 설정합니다 (요소의 노드 문서를 기준으로 함).

  4. 요소의 트랙 URLtrackURL로 설정합니다 (실패하지 않은 경우); 그렇지 않으면 빈 문자열로 설정합니다.

요소의 트랙 URL이 WebVTT 리소스를 식별하고, 요소의 kind 속성이 챕터 메타데이터 또는 메타데이터 상태에 있지 않은 경우, WebVTT 파일은 큐 텍스트를 사용하는 WebVTT 파일이어야 합니다. [WEBVTT]

srclang 속성은 텍스트 트랙 데이터의 언어를 제공합니다. 값은 유효한 BCP 47 언어 태그여야 합니다. 이 속성은 요소의 kind 속성이 자막 상태에 있는 경우 필수입니다. [BCP47]

요소에 srclang 속성이 있으며 그 값이 빈 문자열이 아닌 경우, 요소의 트랙 언어는 속성의 값입니다. 그렇지 않으면 요소에 트랙 언어가 없습니다.

label 속성은 트랙에 대한 사용자 읽기 가능한 제목을 제공합니다. 이 제목은 사용자 에이전트가 자막, 캡션오디오 설명 트랙을 사용자 인터페이스에 나열할 때 사용됩니다.

label 속성이 존재하는 경우, 그 값은 빈 문자열이 아니어야 합니다. 또한 동일한 미디어 요소의 두 track 자식 요소가 동일한 상태의 kind 속성을 가지고, srclang 속성이 둘 다 없거나 동일한 언어를 나타내며, label 속성이 둘 다 없거나 동일한 값을 가질 수 없습니다.

요소에 label 속성이 있으며 그 값이 빈 문자열이 아닌 경우, 요소의 트랙 레이블은 속성의 값입니다. 그렇지 않으면 요소의 트랙 레이블은 빈 문자열입니다.

default 속성은 부울 속성으로, 지정된 경우, 사용자의 기본 설정이 다른 트랙이 더 적합하다고 표시하지 않는 한 트랙이 활성화됨을 나타냅니다.

미디어 요소track 요소 자식이 kind 속성이 자막 또는 캡션 상태에 있고 default 속성이 지정된 요소가 하나 이상 없어야 합니다.

미디어 요소track 요소 자식이 kind 속성이 설명 상태에 있고 default 속성이 지정된 요소가 하나 이상 없어야 합니다.

미디어 요소track 요소 자식이 kind 속성이 챕터 메타데이터 상태에 있고 default 속성이 지정된 요소가 하나 이상 없어야 합니다.

track 요소의 kind 속성이 메타데이터 상태에 있고 default 속성이 지정된 경우, 그 수에는 제한이 없습니다.

track.readyState

텍스트 트랙 준비 상태를 나타내는 숫자 값을 반환합니다:

track.NONE (0)

텍스트 트랙이 로드되지 않은 상태입니다.

track.LOADING (1)

텍스트 트랙이 로딩 중인 상태입니다.

track.LOADED (2)

텍스트 트랙이 로드된 상태입니다.

track.ERROR (3)

텍스트 트랙 로드 실패 상태입니다.

track.track

TextTrack 객체를 반환합니다.

readyState 속성은 track 요소의 텍스트 트랙텍스트 트랙 준비 상태에 해당하는 숫자 값을 반환해야 합니다.

NONE (숫자 값 0)
텍스트 트랙이 로드되지 않은 상태입니다.
LOADING (숫자 값 1)
텍스트 트랙이 로딩 중인 상태입니다.
LOADED (숫자 값 2)
텍스트 트랙이 로드된 상태입니다.
ERROR (숫자 값 3)
텍스트 트랙 로드 실패 상태입니다.

track IDL 속성은 가져올 때 track 요소의 텍스트 트랙에 해당하는 TextTrack 객체를 반환해야 합니다.

HTMLTrackElement/src

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

src, srclang, label, default IDL 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다. kind IDL 속성은 알려진 값으로만 제한된 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

이 비디오는 여러 언어로 된 자막을 가지고 있습니다:

<video src="brave.webm">
 <track kind=subtitles src=brave.en.vtt srclang=en label="English">
 <track kind=captions src=brave.en.hoh.vtt srclang=en label="English for the Hard of Hearing">
 <track kind=subtitles src=brave.fr.vtt srclang=fr lang=fr label="Français">
 <track kind=subtitles src=brave.de.vtt srclang=de lang=de label="Deutsch">
</video>

(마지막 두 개의 lang 속성은 자막의 언어가 아니라 label 속성의 언어를 설명합니다. 자막의 언어는 srclang 속성에 의해 지정됩니다.)

4.8.11 미디어 요소

HTMLMediaElement 객체들(audiovideo, 이 사양에서)은 미디어 요소로 알려져 있습니다.

HTMLMediaElement

모든 최신 엔진에서 지원됨.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
enum CanPlayTypeResult { "" /* 빈 문자열 */, "maybe", "probably" };
typedef (MediaStream or MediaSource or Blob) MediaProvider;

[Exposed=Window]
interface HTMLMediaElement : HTMLElement {

  // 오류 상태
  readonly attribute MediaError? error;

  // 네트워크 상태
  [CEReactions] attribute USVString src;
  attribute MediaProvider? srcObject;
  readonly attribute USVString currentSrc;
  [CEReactions] attribute DOMString? crossOrigin;
  const unsigned short NETWORK_EMPTY = 0;
  const unsigned short NETWORK_IDLE = 1;
  const unsigned short NETWORK_LOADING = 2;
  const unsigned short NETWORK_NO_SOURCE = 3;
  readonly attribute unsigned short networkState;
  [CEReactions] attribute DOMString preload;
  readonly attribute TimeRanges buffered;
  undefined load();
  CanPlayTypeResult canPlayType(DOMString type);

  // 준비 상태
  const unsigned short HAVE_NOTHING = 0;
  const unsigned short HAVE_METADATA = 1;
  const unsigned short HAVE_CURRENT_DATA = 2;
  const unsigned short HAVE_FUTURE_DATA = 3;
  const unsigned short HAVE_ENOUGH_DATA = 4;
  readonly attribute unsigned short readyState;
  readonly attribute boolean seeking;

  // 재생 상태
  attribute double currentTime;
  undefined fastSeek(double time);
  readonly attribute unrestricted double duration;
  object getStartDate();
  readonly attribute boolean paused;
  attribute double defaultPlaybackRate;
  attribute double playbackRate;
  attribute boolean preservesPitch;
  readonly attribute TimeRanges played;
  readonly attribute TimeRanges seekable;
  readonly attribute boolean ended;
  [CEReactions] attribute boolean autoplay;
  [CEReactions] attribute boolean loop;
  Promise<undefined> play();
  undefined pause();

  // 컨트롤
  [CEReactions] attribute boolean controls;
  attribute double volume;
  attribute boolean muted;
  [CEReactions] attribute boolean defaultMuted;

  // 트랙
  [SameObject] readonly attribute AudioTrackList audioTracks;
  [SameObject] readonly attribute VideoTrackList videoTracks;
  [SameObject] readonly attribute TextTrackList textTracks;
  TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
};

미디어 요소 속성src, crossorigin, preload, autoplay, loop, mutedcontrols는 모든 미디어 요소에 적용됩니다. 이 섹션에서 정의됩니다.

미디어 요소는 사용자에게 오디오 데이터 또는 비디오 및 오디오 데이터를 제공하는 데 사용됩니다. 이 섹션에서는 오디오나 비디오에 대한 미디어 요소에 동일하게 적용되므로 이를 미디어 데이터라고 합니다.

미디어 리소스라는 용어는 전체 미디어 데이터를 나타내는 데 사용됩니다. 예를 들어, 전체 비디오 파일 또는 전체 오디오 파일을 의미합니다.

미디어 리소스는 연관된 출처(origin)를 가지며, 이는 "none", "multiple", "rewritten" 또는 출처 중 하나일 수 있습니다. 초기값은 "none"으로 설정됩니다.

미디어 리소스는 여러 오디오 및 비디오 트랙을 가질 수 있습니다. 미디어 요소의 목적상, 미디어 리소스의 비디오 데이터는 마지막으로 이벤트 루프1단계에 도달했을 때 요소의 videoTracks 속성에 의해 선택된 현재 트랙(있는 경우)의 비디오 데이터만 해당하며, 미디어 리소스의 오디오 데이터는 마지막으로 이벤트 루프1단계에 도달했을 때 요소의 audioTracks 속성에 의해 현재 활성화된 트랙들(있는 경우)을 혼합한 결과입니다.

audio 요소와 video 요소 모두 오디오 및 비디오에 사용될 수 있습니다. 두 요소의 주요 차이점은 audio 요소는 시각적 콘텐츠(예: 비디오나 자막)에 대한 재생 영역이 없다는 점이고, video 요소는 재생 영역이 있다는 점입니다.

미디어 요소는 고유한 미디어 요소 이벤트 작업 소스를 가집니다.

미디어 요소 element와 일련의 단계 steps에 대해 미디어 요소 작업을 큐에 추가하려면, 요소 작업을 큐에 추가해야 하며, 이는 미디어 요소미디어 요소 이벤트 작업 소스에 대해 elementsteps을 사용하여 수행됩니다.

4.8.11.1 오류 코드

MediaError

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
media.error

HTMLMediaElement/error

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

요소의 현재 오류 상태를 나타내는 MediaError 객체를 반환합니다.

오류가 없으면 null을 반환합니다.

모든 미디어 요소는 관련된 오류 상태를 가지고 있으며, 이 상태는 마지막으로 리소스 선택 알고리즘이 호출된 이후 요소가 겪은 마지막 오류를 기록합니다. error 속성은 마지막 오류에 대해 생성된 MediaError 객체를 반환해야 하며, 오류가 발생하지 않은 경우 null을 반환해야 합니다.

[Exposed=Window]
interface MediaError {
  const unsigned short MEDIA_ERR_ABORTED = 1;
  const unsigned short MEDIA_ERR_NETWORK = 2;
  const unsigned short MEDIA_ERR_DECODE = 3;
  const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;

  readonly attribute unsigned short code;
  readonly attribute DOMString message;
};
media.error.code

MediaError/code

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

아래 목록에서 현재 오류의 오류 코드를 반환합니다.

media.error.message

MediaError/message

모든 현재 엔진에서 지원됩니다.

Firefox52+Safari15+Chrome59+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

발생한 오류 상태에 대한 특정 진단 메시지를 반환합니다. 메시지와 메시지 형식은 사용자 에이전트마다 일반적으로 일관되지 않습니다. 사용 가능한 메시지가 없는 경우 빈 문자열이 반환됩니다.

모든 MediaError 객체에는 문자열 메시지와 아래 값 중 하나인 코드가 있습니다.

MEDIA_ERR_ABORTED (숫자 값 1)
미디어 리소스에 대한 가져오기 프로세스가 사용자 에이전트에 의해 사용자의 요청으로 중단되었습니다.
MEDIA_ERR_NETWORK (숫자 값 2)
일부 네트워크 오류로 인해 리소스가 사용 가능한 것으로 확인된 후 사용자 에이전트가 미디어 리소스 가져오기를 중지했습니다.
MEDIA_ERR_DECODE (숫자 값 3)
리소스가 사용 가능한 것으로 확인된 후 미디어 리소스를 디코딩하는 동안 오류가 발생했습니다.
MEDIA_ERR_SRC_NOT_SUPPORTED (숫자 값 4)
src 속성 또는 할당된 미디어 공급자 객체에서 나타낸 미디어 리소스가 적절하지 않았습니다.

주어진 오류 코드가 위의 값 중 하나인 MediaError생성하려면, 주어진 오류 코드를 가진 새 MediaError 객체를 반환하고, 메시지를 설정해야 합니다. 이 메시지 문자열에는 오류 조건의 원인에 대해 사용자 에이전트가 제공할 수 있는 세부 정보가 포함되어야 하며, 사용자가 그러한 세부 정보를 제공할 수 없는 경우 빈 문자열로 설정해야 합니다. 이 메시지 문자열은 제공된 오류 코드에서 이미 제공된 정보만 포함해서는 안 됩니다. 예를 들어, 코드를 문자열 형식으로 번역하는 것만으로는 충분하지 않습니다. 오류 코드 외에 추가 정보가 제공되지 않는 경우, 메시지는 빈 문자열로 설정해야 합니다.

code의 getter 단계는 this코드를 반환하는 것입니다.

message의 getter 단계는 this메시지를 반환하는 것입니다.

4.8.11.2 미디어 리소스의 위치

미디어 요소src 콘텐츠 속성은 표시할 미디어 리소스(비디오, 오디오)의 URL을 제공합니다. 이 속성이 존재하는 경우, 유효한 빈 URL이 아닌 값이 공백으로 둘러싸여 있을 수 있는 URL을 포함해야 합니다.

미디어 요소itemprop 속성이 지정된 경우, src 속성도 반드시 지정되어야 합니다.

미디어 요소crossorigin 콘텐츠 속성은 CORS 설정 속성입니다.

만약 미디어 요소src 속성과 함께 생성되면, 사용자 에이전트는 미디어 요소리소스 선택 알고리즘즉시 호출해야 합니다.

미디어 요소src 속성이 설정되거나 변경된 경우, 사용자 에이전트는 미디어 요소미디어 요소 로드 알고리즘을 호출해야 합니다. (src 속성을 제거하는 것은, source 요소가 존재하더라도, 이를 수행하지 않습니다.)

HTMLMediaElement/src

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

미디어 요소src IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

HTMLMediaElement/crossOrigin

모든 현재 엔진에서 지원됩니다.

Firefox22+Safari10+Chrome33+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

crossOrigin IDL 속성은 반영되어야 하며, crossorigin 콘텐츠 속성을 반영하되, 알려진 값으로만 제한됩니다.

미디어 공급자 객체미디어 리소스를 나타낼 수 있는 객체로, URL과는 별개입니다. MediaStream 객체, MediaSource 객체, Blob 객체는 모두 미디어 공급자 객체입니다.

미디어 요소할당된 미디어 공급자 객체를 가질 수 있으며, 이는 미디어 공급자 객체입니다. 미디어 요소가 생성될 때, 할당된 미디어 공급자 객체가 없습니다.

media.srcObject [ = source ]

HTMLMediaElement/srcObject

단일 엔진에서만 지원됩니다.

Firefox🔰 42+Safari11+🔰 108+
Opera?Edge🔰 108+
Edge (Legacy)?Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

미디어 요소미디어 공급자 객체를 할당할 수 있습니다.

media.currentSrc

HTMLMediaElement/currentSrc

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

현재 미디어 리소스URL을 반환합니다.

미디어 리소스가 없거나, URL이 없으면 빈 문자열을 반환합니다.

currentSrc IDL 속성은 초기에는 빈 문자열로 설정되어야 합니다. 이 값은 아래에 정의된 리소스 선택 알고리즘에 의해 변경됩니다.

srcObject IDL 속성은, 얻을 때, 요소의 할당된 미디어 제공자 객체를 반환해야 하며, 없으면 null을 반환해야 합니다. 설정할 때는, 요소의 할당된 미디어 제공자 객체를 새로운 값으로 설정한 다음, 요소의 미디어 요소 로드 알고리즘을 호출해야 합니다.

미디어 리소스를 지정하는 방법은 세 가지가 있습니다: srcObject IDL 속성, src 콘텐츠 속성, 그리고 source 요소입니다. IDL 속성이 우선되며, 그 다음은 콘텐츠 속성, 마지막으로 요소가 우선됩니다.

4.8.11.3 MIME 타입

미디어 리소스타입으로 설명될 수 있으며, 특히 MIME 타입으로 설명될 수 있습니다. 일부 경우에는 codecs 매개변수가 포함될 수 있습니다. (codecs 매개변수가 허용되는지 여부는 MIME 타입에 따라 다릅니다.) [RFC6381]

타입은 보통 다소 불완전한 설명입니다. 예를 들어 "video/mpeg"는 컨테이너 타입 외에는 아무 정보도 제공하지 않으며, "video/mp4; codecs="avc1.42E01E, mp4a.40.2""와 같은 타입도 실제 비트레이트(최대 비트레이트만 표시됨)와 같은 정보를 포함하지 않습니다. 따라서 사용자 에이전트는 주어진 타입이 재생할 수 있을지 (확신 정도에 따라 다름) 또는 재생할 수 없을지 여부만을 알 수 있습니다.

사용자 에이전트가 렌더링할 수 없음을 아는 타입이란, 컨테이너 타입을 인식하지 못하거나 나열된 코덱을 지원하지 않기 때문에 사용자 에이전트가 확실히 지원하지 않는 리소스를 설명하는 타입을 의미합니다.

MIME 타입 "application/octet-stream"에 파라미터가 없는 경우, 이 타입은 결코 사용자 에이전트가 렌더링할 수 없음을 아는 타입이 아닙니다. 사용자 에이전트는 이 타입을 명시적인 Content-Type 메타데이터가 없는 것과 동등하게 취급해야 합니다. 이 타입이 잠재적인 미디어 리소스를 나타낼 때 사용됩니다.

여기서 특별히 취급되는 것은 파라미터가 없는 "MIME 타입" "application/octet-stream"뿐입니다. 파라미터가 함께 나타나는 경우, 이는 다른 MIME 타입처럼 취급됩니다. 이는 알려지지 않은 MIME 타입 파라미터는 무시해야 한다는 규칙에서 벗어나는 것입니다.

media.canPlayType(type)

HTMLMediaElement/canPlayType

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

사용자 에이전트가 주어진 타입의 미디어 리소스를 재생할 수 있다고 확신하는 정도에 따라 빈 문자열(부정적 응답), "maybe" 또는 "probably"를 반환합니다.

canPlayType(type) 메서드는 type사용자 에이전트가 렌더링할 수 없음을 아는 타입이거나 "application/octet-stream" 타입인 경우 빈 문자열을 반환해야 합니다. 사용자 에이전트가 이 타입이 미디어 리소스를 나타내며 오디오 또는 video 요소와 함께 사용될 수 있다고 확신하는 경우 "probably"를 반환해야 하며, 그렇지 않은 경우 "maybe"를 반환해야 합니다. 구현자는 타입이 지원되는지 여부를 확신할 수 없는 경우 "maybe"를 반환하는 것이 권장됩니다. 일반적으로, 사용자 에이전트는 codecs 매개변수를 허용하는 타입의 경우, 해당 매개변수가 존재하지 않으면 "probably"를 반환해서는 안 됩니다.

이 스크립트는 사용자 에이전트가 (가상의) 새로운 포맷을 지원하는지 테스트하여 video 요소를 사용할지 여부를 동적으로 결정합니다:

<section id="video">
 <p><a href="playing-cats.nfv">Download video</a></p>
</section>
<script>
 const videoSection = document.getElementById('video');
 const videoElement = document.createElement('video');const support = videoElement.canPlayType('video/x-new-fictional-format;codecs="kittens,bunnies"');if (support === "probably") {videoElement.setAttribute("src", "playing-cats.nfv");videoSection.replaceChildren(videoElement);}
</script>

type 속성은 source 요소의 속성으로, 사용자 에이전트가 렌더링할 수 없는 포맷을 사용하는 리소스의 다운로드를 피할 수 있도록 합니다.

4.8.11.4 네트워크 상태
media.networkState

HTMLMediaElement/networkState

모든 최신 엔진에서 지원됨.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

요소의 네트워크 활동의 현재 상태를 아래 목록에 있는 코드에서 반환합니다.

미디어 요소들이 네트워크와 상호작용할 때, 현재 네트워크 활동은 networkState 속성으로 나타납니다. 가져올 때, 요소의 현재 네트워크 상태를 반환해야 하며, 다음 값 중 하나여야 합니다:

NETWORK_EMPTY (숫자 값 0)
요소가 아직 초기화되지 않았습니다. 모든 속성은 초기 상태에 있습니다.
NETWORK_IDLE (숫자 값 1)
요소의 리소스 선택 알고리즘이 활성 상태이며, 리소스를 선택했지만, 현재 네트워크를 실제로 사용하지는 않습니다.
NETWORK_LOADING (숫자 값 2)
사용자 에이전트가 데이터를 다운로드하려고 적극적으로 시도 중입니다.
NETWORK_NO_SOURCE (숫자 값 3)
요소의 리소스 선택 알고리즘이 활성 상태이지만, 아직 사용할 리소스를 찾지 못했습니다.

리소스 선택 알고리즘은 아래에 정의되어 있으며, networkState 속성 값이 변경되는 시점과 이 상태에서 변화를 나타내기 위해 어떤 이벤트가 발생하는지를 설명합니다.

4.8.11.5 미디어 리소스 로드
media.load()

HTMLMediaElement/load

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

이 요소가 초기화되고 새로운 미디어 리소스 를 선택하고 로드하는 작업을 시작하게 합니다.

모든 미디어 요소자동 재생 가능 플래그를 가지고 있으며, 이는 true 상태에서 시작해야 하며, 로드 이벤트 지연 플래그는 false 상태에서 시작해야 합니다. 로드 이벤트 지연 플래그가 true인 동안 문서의 로드 이벤트를 지연시켜야 합니다.

load() 메서드가 미디어 요소에서 호출되면, 사용자 에이전트는 미디어 요소 로드 알고리즘을 실행해야 합니다.

미디어 요소는 연관된 boolean 현재 멈춤 상태를 가지며, 초기값은 false입니다.

미디어 요소 로드 알고리즘은 다음 단계를 포함합니다.

  1. 이 요소의 현재 멈춤 상태를 false로 설정합니다.

  2. 이 요소에 대해 이미 실행 중인 리소스 선택 알고리즘의 실행을 중단합니다.

  3. pending tasks작업의 목록으로 설정합니다. 미디어 요소미디어 요소 이벤트 작업 소스에서 작업 대기열 중 하나에 있는 모든 작업을 포함합니다.

  4. pending tasks에 있는 각 작업에 대해 보류 중인 재생 약속을 해결하거나 보류 중인 재생 약속을 거부할 때, 해당 작업이 대기열에 추가된 순서대로 즉시 약속을 해결하거나 거부합니다.

  5. pending tasks에 있는 각 작업을 해당 작업 대기열에서 제거합니다.

    기본적으로, 미디어 요소가 새로운 리소스를 로드하기 시작할 때 보류 중인 이벤트와 콜백이 삭제되고, 처리 중인 약속이 즉시 해결 또는 거부됩니다.

  6. 미디어 요소networkStateNETWORK_LOADING이나 NETWORK_IDLE로 설정된 경우, 미디어 요소 작업을 대기열에 추가하고, 미디어 요소에서 abort라는 이름의 이벤트를 발생시킵니다.

  7. 미디어 요소networkStateNETWORK_EMPTY로 설정되지 않은 경우:

    1. 미디어 요소 작업을 대기열에 추가하고 이벤트를 발생시킵니다. emptied라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

    2. 해당 미디어 요소에 대해 가져오기 프로세스가 진행 중인 경우, 사용자 에이전트는 이를 중지해야 합니다.

    3. 미디어 요소지정된 미디어 공급자 객체MediaSource인 경우, 이를 분리합니다.

    4. 미디어 요소의 미디어 리소스별 트랙 잊기.

    5. readyStateHAVE_NOTHING으로 설정되지 않은 경우, 해당 상태로 설정합니다.

    6. paused속성이 false로 설정된 경우:

      1. paused속성을 true로 설정합니다.

      2. 보류 중인 재생 약속을 가져와서 재생 약속을 거부합니다 결과와 함께 "AbortError" DOMException과 함께 거부합니다.

    7. seeking이 true인 경우, 이를 false로 설정합니다.

    8. 현재 재생 위치를 0으로 설정합니다.

      공식 재생 위치를 0으로 설정합니다.

      이 작업이 공식 재생 위치를 변경한 경우, 미디어 요소 작업을 대기열에 추가하고 이벤트를 발생시킵니다. timeupdate라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

    9. 타임라인 오프셋을 Not-a-Number (NaN)로 설정합니다.

    10. duration속성을 Not-a-Number (NaN)로 업데이트합니다.

      사용자 에이전트는 이 특정 변경에 대해 durationchange이벤트를 발생시키지 않습니다.

  8. playbackRate속성을 defaultPlaybackRate속성의 값으로 설정합니다.

  9. error속성을 null로 설정하고 자동 재생 가능 플래그를 true로 설정합니다.

  10. 미디어 요소리소스 선택 알고리즘을 호출합니다.

  11. 이 요소에 대해 이전에 재생 중이던 미디어 리소스의 재생이 중지됩니다.

리소스 선택 알고리즘미디어 요소에 대해 다음과 같이 작동합니다. 이 알고리즘은 항상 작업의 일부로 호출되지만, 알고리즘의 첫 번째 단계 중 하나는 반환하고 나머지 단계를 병렬로 계속 실행하는 것입니다. 또한 이 알고리즘은 이벤트 루프 메커니즘과 밀접하게 상호 작용합니다. 특히, 이 알고리즘은 동기화 섹션을 포함하며, 이는 이벤트 루프 알고리즘의 일부로 트리거됩니다. 이러한 섹션의 단계는 ⌛로 표시됩니다.

  1. 이 요소의 networkState속성을 NETWORK_NO_SOURCE값으로 설정합니다.

  2. 이 요소의 포스터 표시 플래그를 true로 설정합니다.

  3. 미디어 요소로드 이벤트 지연 플래그를 true로 설정합니다 (이것은 로드 이벤트를 지연시킵니다).

  4. 안정적인 상태를 기다립니다, 이 작업을 호출한 작업을 계속하도록 합니다. 동기화 섹션은 이 알고리즘의 나머지 모든 단계를 포함하며, 알고리즘이 동기화 섹션이 끝났다고 말할 때까지 계속됩니다. (동기화 섹션의 단계는 ⌛로 표시됩니다.)

  5. 미디어 요소파서에 의해 차단됨 플래그가 false인 경우, 보류 중인 텍스트 트랙 목록을 채웁니다.

  6. 미디어 요소지정된 미디어 공급자 객체를 가지고 있는 경우, modeobject로 설정합니다.

    ⌛ 그렇지 않고, 미디어 요소지정된 미디어 공급자 객체를 가지고 있지 않지만 src 속성을 가지고 있는 경우, modeattribute로 설정합니다.

    ⌛ 그렇지 않고, 미디어 요소지정된 미디어 공급자 객체를 가지고 있지 않으며, src 속성도 가지고 있지 않지만 source 요소 자식을 가지고 있는 경우, modechildren으로 설정하고 candidate를 해당 source 요소 자식 중 첫 번째로 설정합니다. 트리 순서로.

    ⌛ 그렇지 않은 경우, 미디어 요소에는 지정된 미디어 공급자 객체가 없고, src 속성도 source요소 자식도 없습니다:

    1. networkStateNETWORK_EMPTY로 설정합니다.

    2. ⌛ 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

    3. 동기화 섹션을 끝내고 반환합니다.

  7. 미디어 요소networkStateNETWORK_LOADING으로 설정합니다.

  8. 미디어 요소 작업을 대기열에 추가하고 미디어 요소에서 이벤트를 발생시킵니다. loadstart라는 이름의 이벤트를 미디어 요소에서.

  9. 다음 목록에서 적절한 단계를 실행합니다:

    modeobject인 경우
    1. currentSrc속성을 빈 문자열로 설정합니다.

    2. 동기화 섹션을 끝내고, 나머지 단계를 병렬로 계속합니다.

    3. 리소스 가져오기 알고리즘지정된 미디어 공급자 객체와 함께 실행합니다. 해당 알고리즘이 이 알고리즘을 중단하지 않고 반환되면, 로드에 실패한 것입니다.

    4. 미디어 공급자로 인해 실패: 이 단계에 도달하면 미디어 리소스 로드에 실패한 것으로 간주됩니다. 보류 중인 재생 약속을 가져오고 미디어 요소 작업을 대기열에 추가하고 미디어 요소에서 전용 미디어 소스 실패 단계를 결과와 함께 실행합니다.

    5. 이전 단계에서 대기열에 추가된 작업이 실행될 때까지 기다립니다.

    6. 반환합니다. 이 알고리즘이 다시 호출되기 전까지 이 요소는 다른 리소스를 로드하려고 하지 않습니다.

    modeattribute인 경우
    1. src 속성의 값이 빈 문자열인 경우, 동기화 섹션을 끝내고, 아래의 속성으로 실패 단계로 건너뜁니다.

    2. urlRecordURL 인코딩-파싱의 결과로 설정합니다. src 속성의 값을 기준으로, 미디어 요소노드 문서에 상대적으로 적용됩니다.

    3. urlRecord가 실패가 아닌 경우, currentSrc속성을 URL 직렬화urlRecord에 적용한 결과로 설정합니다.

    4. 동기화 섹션을 끝내고, 나머지 단계를 병렬로 계속합니다.

    5. urlRecord가 실패가 아닌 경우, 리소스 가져오기 알고리즘urlRecord와 함께 실행합니다. 해당 알고리즘이 이 알고리즘을 중단하지 않고 반환되면, 로드에 실패한 것입니다.

    6. 속성으로 실패: 이 단계에 도달하면 미디어 리소스 로드에 실패한 것으로 간주되거나 urlRecord가 실패로 간주됩니다. 보류 중인 재생 약속을 가져오고 미디어 요소 작업을 대기열에 추가하고 미디어 요소에서 전용 미디어 소스 실패 단계를 결과와 함께 실행합니다.

    7. 이전 단계에서 대기열에 추가된 작업이 실행될 때까지 기다립니다.

    8. 반환합니다. 이 알고리즘이 다시 호출되기 전까지 이 요소는 다른 리소스를 로드하려고 하지 않습니다.

    그 외 (modechildren인 경우)
    1. pointer미디어 요소의 자식 목록에서 두 인접 노드로 정의된 위치로 설정합니다. 리스트의 시작 (리스트의 첫 번째 자식 전, 있는 경우)과 리스트의 끝 (리스트의 마지막 자식 후, 있는 경우)을 각각의 노드로 간주합니다. 한 노드는 pointer 전의 노드이며, 다른 노드는 pointer 후의 노드입니다. 초기에는 pointercandidate 노드와 그 다음 노드 사이의 위치로 설정합니다. 만약 마지막 노드라면 리스트의 끝으로 설정합니다.

      노드가 삽입되고 제거되면서, 미디어 요소, pointer는 다음과 같이 업데이트되어야 합니다:

      두 노드를 정의하는 pointer 사이에 새 노드가 삽입된 경우
      pointerpointer 전의 노드와 새 노드 사이의 지점으로 설정합니다. 즉, pointer에서 삽입은 pointer 이후에 발생합니다.
      pointer 전의 노드가 제거된 경우
      pointerpointer 후의 노드와 pointer 전의 노드 사이의 지점으로 설정합니다. 즉, pointer는 남아있는 노드에 대해 상대적으로 이동하지 않습니다.
      pointer 후의 노드가 제거된 경우
      pointerpointer 전의 노드와 pointer 전의 노드 후의 노드 사이의 지점으로 설정합니다. 마찬가지로, pointer는 남아있는 노드에 대해 상대적으로 이동하지 않습니다.

      다른 변경 사항은 pointer에 영향을 주지 않습니다.

    2. 후보 처리: candidatesrc 속성을 가지고 있지 않거나, 해당 src속성의 값이 빈 문자열인 경우, 동기화 섹션을 끝내고, 아래의 요소로 실패 단계로 건너뜁니다.

    3. candidatemedia 속성이 있고 해당 속성의 값이 환경과 일치하지 않는 경우, 동기화 섹션을 끝내고, 아래의 요소로 실패 단계로 건너뜁니다.

    4. urlRecordURL 인코딩-파싱의 결과로 설정합니다. candidatesrc 속성의 값을 기준으로, candidate노드 문서에 상대적으로 적용됩니다.

    5. urlRecord가 실패인 경우, 동기화 섹션을 끝내고, 아래의 요소로 실패 단계로 건너뜁니다.

    6. candidatetype 속성이 있고 해당 값이 MIME 타입(해당 파라미터를 정의하는 타입의 경우 codecs 파라미터에 의해 설명된 코덱을 포함하여)으로 파싱되었을 때, 사용자 에이전트가 렌더링할 수 없음을 알고 있는 타입을 나타내면, 동기화 섹션을 끝내고, 아래의 요소로 실패 단계로 건너뜁니다.

    7. currentSrc속성을 URL 직렬화urlRecord에 적용한 결과로 설정합니다.

    8. 동기화 섹션을 끝내고, 나머지 단계를 병렬로 계속합니다.

    9. 리소스 가져오기 알고리즘urlRecord와 함께 실행합니다. 해당 알고리즘이 이 알고리즘을 중단하지 않고 반환되면, 로드에 실패한 것입니다.

    10. 요소로 실패: 미디어 요소 작업을 대기열에 추가하고 미디어 요소에서 이벤트를 발생시킵니다. error라는 이름의 이벤트를 candidate에서 발생시킵니다.

    11. 안정적인 상태를 기다립니다. 동기화 섹션은 이 알고리즘의 나머지 모든 단계를 포함하며, 알고리즘이 동기화 섹션이 끝났다고 말할 때까지 계속됩니다. (동기화 섹션의 단계는 ⌛로 표시됩니다.)

    12. 미디어 요소의 미디어 리소스별 트랙 잊기.

    13. 다음 후보 찾기: candidate를 null로 설정합니다.

    14. 탐색 루프: pointer 후의 노드가 리스트의 끝인 경우, 아래의 대기 중 단계로 건너뜁니다.

    15. pointer 후의 노드가 source요소인 경우, candidate를 해당 요소로 설정합니다.

    16. pointer를 앞으로 이동시켜 pointer 전의 노드가 이제 pointer 후의 노드가 되도록 하고, pointer 후의 노드가 이전에 pointer 후의 노드였던 노드 후의 노드가 되도록 합니다.

    17. candidate가 null인 경우, 탐색 루프 단계로 돌아갑니다. 그렇지 않은 경우, 후보 처리 단계로 돌아갑니다.

    18. 대기 중: 요소의 networkState속성을 NETWORK_NO_SOURCE값으로 설정합니다.

    19. ⌛ 요소의 포스터 표시 플래그를 true로 설정합니다.

    20. 미디어 요소 작업을 대기열에 추가하고 미디어 요소에서 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

    21. 동기화 섹션을 끝내고, 나머지 단계를 병렬로 계속합니다.

    22. pointer 후의 노드가 리스트의 끝이 아닌 노드가 될 때까지 기다립니다. (이 단계는 영원히 대기할 수 있습니다.)

    23. 안정적인 상태를 기다립니다. 동기화 섹션은 이 알고리즘의 나머지 모든 단계를 포함하며, 알고리즘이 동기화 섹션이 끝났다고 말할 때까지 계속됩니다. (동기화 섹션의 단계는 ⌛로 표시됩니다.)

    24. ⌛ 요소의 로드 이벤트 지연 플래그를 다시 true로 설정합니다 (이것은 아직 발생하지 않은 경우 로드 이벤트를 지연시킵니다).

    25. networkStateNETWORK_LOADING으로 다시 설정합니다.

    26. ⌛ 위의 다음 후보 찾기 단계로 다시 점프합니다.

    promises 목록과 함께 전용 미디어 소스 실패 단계를 실행하려면 다음 단계를 따르십시오:

    1. 요소의 error속성을 미디어 오류 MediaError를 생성한 결과로 설정하고 MEDIA_ERR_SRC_NOT_SUPPORTED로 설정합니다.

    2. 미디어 요소의 미디어 리소스별 트랙 잊기.

    3. 요소의 networkState속성을 NETWORK_NO_SOURCE값으로 설정합니다.

    4. 요소의 포스터 표시 플래그를 true로 설정합니다.

    5. 이벤트를 발생시킵니다. error라는 이름의 이벤트를 미디어 요소에서.

    6. 보류 중인 재생 약속을 거부하고 promises"NotSupportedError" DOMException과 함께 거부합니다.

    7. 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

미디어 응답을 검증하기 위해 다음 요소를 고려하세요: 응답 response, 미디어 리소스 resource, 그리고 "전체 리소스" 또는 (number, number 또는 "끝까지") 튜플 byteRange:

  1. response네트워크 오류인 경우, false를 반환합니다.

  2. byteRange가 "전체 리소스"인 경우, true를 반환합니다.

  3. internalResponseresponse안전하지 않은 응답으로 설정합니다.

  4. internalResponse상태가 200인 경우, true를 반환합니다.

  5. internalResponse상태가 206이 아닌 경우, false를 반환합니다.

  6. internalResponse에서 컨텐츠 범위 값 추출의 결과가 실패하면 false를 반환합니다.

    추출된 값들은 사용되지 않으며, 특히 byteRange와 비교되지 않습니다. 이 단계는 `Content-Range` 헤더의 구문 검증 역할을 하지만, 응답의 `Content-Range` 값이 요청의 `Range` 값과 일치하지 않는 경우, 이는 실패로 간주되지 않습니다.

  7. internalResponseURL이 null인 경우 origin을 "재작성됨"으로 설정합니다; 그렇지 않으면 internalResponseURL원본으로 설정합니다.

  8. previousOriginresource원본으로 설정합니다.

  9. 다음 중 하나가 참인 경우:

    이 경우 resource원본origin으로 설정합니다.

    그렇지 않으면, responseCORS 크로스-원본인 경우, false를 반환합니다.

    그렇지 않으면, resource원본을 "다중"으로 설정합니다.

    이렇게 하면 범위 헤더가 있는 불투명 응답이 다른 원본의 다른 응답과 패치되지 않아 정보가 유출되는 것을 방지합니다.

  10. true를 반환합니다.

미디어 자원 로드 알고리즘미디어 요소 및 주어진 URL 기록 또는 미디어 제공자 객체에 대해 다음과 같이 정의됩니다:

  1. 이 알고리즘이 미디어 제공자 객체 또는 URL 기록blob URL 항목blob URL 항목이며, 객체미디어 제공자 객체인 경우, 모드로컬로 설정합니다. 그렇지 않으면 모드원격으로 설정합니다.

  2. 모드원격인 경우, 현재 미디어 자원을 이 알고리즘에 전달된 URL 기록으로 설정합니다. 그렇지 않으면 현재 미디어 자원미디어 제공자 객체에서 제공한 자원으로 설정합니다. 어느 쪽이든 현재 미디어 자원이 이제 요소의 미디어 자원이 됩니다.

  3. 모든 미디어 자원에 특정한 텍스트 트랙미디어 요소보류 중인 텍스트 트랙 목록에서 제거합니다.

  4. 적절한 단계를 다음 목록에서 실행합니다:

    만약 모드가 원격인 경우
    1. 선택적으로 다음 하위 단계를 실행합니다. 사용자 에이전트가 자원을 명시적으로 요청할 때까지 자원 가져오기를 시도하지 않으려는 경우(예: preload 속성의 none 키워드를 구현하는 방법으로서) 예상되는 동작입니다.

      1. networkStateNETWORK_IDLE로 설정합니다.

      2. 미디어 요소 작업을 큐에 추가하고 미디어 요소에서 suspend라는 이름의 이벤트를 발생시킵니다.

      3. 미디어 요소 작업을 큐에 추가하고 미디어 요소로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

      4. 작업이 실행될 때까지 기다립니다.

      5. 구현 정의된 이벤트(예: 사용자가 미디어 요소의 재생을 시작하도록 요청하는 경우)를 기다립니다.

      6. 요소의 로드 이벤트 지연 플래그를 다시 true로 설정합니다. (이것은 아직 로드 이벤트가 발생하지 않은 경우 로드 이벤트 지연을 다시 시작합니다.)

      7. networkStateNETWORK_LOADING으로 설정합니다.

    2. 만약 미디어 요소오디오 요소인 경우 destination을 "audio"로 설정하고, 그렇지 않으면 "video"로 설정합니다.

    3. 잠재적 CORS 요청을 생성한 결과를 현재 미디어 자원의 URL 기록, destination, 그리고 미디어 요소의 현재 상태와 함께 crossorigin 콘텐츠 속성으로 설정합니다.

    4. request클라이언트미디어 요소노드 문서관련 설정 객체로 설정합니다.

    5. request시작자 유형destination으로 설정합니다.

    6. byteRange을 "전체 자원" 또는 미디어 데이터의 누락된 데이터를 충족하기 위해 필요한 바이트 범위로 설정합니다. 이 값은 구현 정의이며, 코덱, 네트워크 상태 또는 기타 휴리스틱에 따라 달라질 수 있습니다. 사용자 에이전트는 자원을 전체로 가져오기로 결정할 수 있으며, 이 경우 byteRange은 "전체 자원"이 될 것이며, 바이트 오프셋에서 끝까지 가져오기로 결정할 수 있으며, 이 경우 byteRange는 (숫자, "끝까지")가 될 것이며, 두 바이트 오프셋 사이의 범위를 가져오기로 결정할 수 있으며, 이 경우 byteRange는 두 오프셋을 나타내는 (숫자, 숫자) 튜플이 될 것입니다.

    7. 만약 byteRange이 "전체 자원"이 아닌 경우:

      1. 만약 byteRange[1]이 "끝까지"라면 범위 헤더를 추가하여 request를 설정합니다.

      2. 그렇지 않으면, 범위 헤더를 추가하여 request를 설정합니다.

    8. 요청을 가져오고, processResponse를 설정하여 다음 단계로 설정합니다:

      1. 미디어 요소노드 문서관련 글로벌 객체global로 설정합니다.

      2. 미디어 요소 작업을 큐에 추가하고, 미디어 요소의 첫 번째 적절한 단계를 실행합니다. (이 작업은 네트워킹 작업 소스 대신 미디어 요소 이벤트 작업 소스에 상대적으로 발생하는 작업이 아래에 설명된 작업과 비교해 적절한 단계에서 발생하도록 하기 위해 사용됩니다.)

      3. 만약 네트워크 액세스 없이 모든 데이터를 사용할 수 있게 되었고, 미디어 데이터를 디코딩하는 작업이 오류 없이 완료되었다면, 사용자 에이전트는 아래의 최종 단계로 이동해야 합니다.

      4. 만약 미디어 응답을 검증한 결과가 현재 미디어 자원byteRange에 대해 거짓이라면, 이러한 단계를 중지합니다.

      5. 그렇지 않으면, 점진적으로 응답의 본문을 읽어 updateMedia, processEndOfMedia, 빈 알고리즘, global을 주어진 대로 설정합니다.

      6. 미디어 데이터를 이 방식으로 얻은 응답의 안전하지 않은 응답의 내용으로 업데이트합니다. 응답은 CORS-동일 출처일 수도 있고 CORS-교차 출처일 수도 있으며, 이것은 API에서 참조되는 자막이 노출되는지 여부에 영향을 미칩니다. 비디오 요소의 경우, 비디오가 그려진 캔버스가 오염될 수 있습니다.

      미디어 요소 정지 시간 초과구현 정의된 기간으로, 약 3초 정도이어야 합니다. 미디어 요소미디어 데이터를 적극적으로 얻으려고 시도 중일 때 미디어 요소 작업을 큐에 추가하여 다음을 수행합니다:

      1. 이벤트를 발생시켜 요소에서 stalled라는 이름의 이벤트를 발생시킵니다.

      2. 요소의 현재 정지 상태를 true로 설정합니다.

      사용자 에이전트는 사용자가 미디어 데이터 다운로드를 선택적으로 차단하거나 속도를 늦출 수 있도록 허용할 수 있습니다. 미디어 요소의 다운로드가 완전히 차단된 경우, 사용자 에이전트는 연결이 끊어진 것처럼 작동하는 대신 정지된 것처럼 작동해야 합니다. 다운로드 속도는 같은 대역폭을 공유하는 다른 연결과 균형을 맞추기 위해 자동으로 제한될 수도 있습니다.

      사용자 에이전트는 언제든지 콘텐츠 다운로드를 중지할 수 있습니다. 예를 들어, 사용자 에이전트가 자원의 일부를 버퍼링한 후 사용자가 재생을 시작할 때까지 더 이상 콘텐츠를 다운로드하지 않거나, 사용자가 상호작용 자원에서 입력을 기다리는 동안 또는 사용자가 페이지에서 벗어날 때 다운로드를 중지할 수 있습니다. 미디어 요소의 다운로드가 일시 중단된 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 미디어 요소networkStateNETWORK_IDLE로 설정하고 이벤트를 발생시켜 suspend라는 이름의 이벤트를 요소에 발생시켜야 합니다. 자원의 다운로드가 다시 시작되면, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 미디어 요소networkStateNETWORK_LOADING로 설정해야 합니다. 이러한 작업들이 큐에 추가되는 동안, 로드는 일시 중단됩니다(따라서 위에서 설명한 것처럼 progress 이벤트가 발생하지 않습니다).

      preload 속성은 저자가 적절하다고 생각하는 버퍼링 양에 대한 힌트를 제공합니다. autoplay 속성이 없는 경우에도 마찬가지입니다.

      사용자 에이전트가 다운로드를 완전히 중지하기로 결정한 경우, 예를 들어 사용자가 재생을 시작할 때까지 추가 콘텐츠를 다운로드하지 않기로 결정한 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 미디어 요소로드 이벤트 지연 플래그를 false로 설정해야 합니다. 이것은 로드 이벤트 지연을 중지합니다.

      위의 단계는 요청을 발행하기 위한 알고리즘을 제공하지만, 사용자 에이전트는 특히 오류 조건에 직면했을 때 정확히 그 방법 외에도 다른 수단을 사용할 수 있습니다. 예를 들어, 사용자 에이전트는 서버에 다시 연결하거나 스트리밍 프로토콜로 전환할 수 있습니다. 사용자 에이전트는 자원을 오류로 간주하고, 위의 단계의 오류 지점으로 진행하는 경우에만 자원을 가져오려는 시도를 포기해야 합니다.

      미디어 자원의 형식을 결정하기 위해, 사용자 에이전트는 오디오 및 비디오를 특정하는 sniffing 규칙을 사용해야 합니다.

      로드가 일시 중단되지 않은 경우(아래 참조), 350ms(±200ms)마다 또는 수신된 각 바이트마다, 둘 중 더 빈번하지 않은 경우 미디어 요소 작업을 큐에 추가하고 미디어 요소를 다음과 같이 설정합니다:

      1. 이벤트를 발생시켜 요소에서 progress라는 이름의 이벤트를 발생시킵니다.

      2. 요소의 현재 정지 상태를 false로 설정합니다.

      사용자 에이전트가 미디어 자원의 일부를 얻기 위해 여전히 네트워크 액세스가 필요할 수 있지만, 사용자 에이전트는 이 단계에 머물러야 합니다.

      예를 들어, 사용자 에이전트가 비디오의 첫 번째 절반을 폐기한 경우, 재생이 종료된 후에도 사용자 에이전트는 이 단계에 머물러야 합니다. 왜냐하면 사용자가 처음으로 돌아가려고 할 가능성이 항상 있기 때문입니다. 사실, 이 상황에서, 재생이 종료된 후, 사용자 에이전트는 이전에 설명된 것처럼 suspend 이벤트를 발생시키게 될 것입니다.

    그렇지 않은 경우 (모드로컬)

    현재 미디어 자원미디어 데이터를 포함하고 있습니다. 이는 CORS-동일 출처입니다.

    만약 현재 미디어 자원이 원시 데이터 스트림(예: 파일 객체)인 경우, 사용자 에이전트는 오디오 및 비디오를 특정하는 sniffing 규칙을 사용하여 미디어 자원의 형식을 결정해야 합니다. 그렇지 않으면, 데이터 스트림이 사전 디코딩된 경우, 형식은 관련 명세에서 제공된 형식입니다.

    언제든지 현재 미디어 자원에 대한 새로운 데이터가 사용 가능해지면, 미디어 요소 작업을 큐에 추가하여 미디어 요소에서 미디어 데이터 처리 단계 목록의 첫 번째 적절한 단계를 실행합니다.

    현재 미디어 자원이 영구적으로 소진된 경우(예: Blob의 모든 바이트가 처리된 경우), 디코딩 오류가 없었다면 사용자 에이전트는 아래의 최종 단계로 이동해야 합니다. 현재 미디어 자원MediaStream인 경우, 이 단계는 절대로 발생하지 않을 수 있습니다.

    미디어 데이터 처리 단계 목록은 다음과 같습니다:

    네트워크 오류로 인해 미디어 데이터를 전혀 가져올 수 없는 경우, 사용자 에이전트가 자원을 가져오려는 시도를 포기하게 됩니다
    미디어 데이터를 가져올 수 있지만, 검사 결과 지원되지 않는 형식이거나 렌더링할 수 없는 경우

    사용자 에이전트가 자원이 사용 가능한지 여부를 확인하기 전의 DNS 오류, HTTP 4xx 및 5xx 오류(및 기타 프로토콜의 동등한 오류)와 같은 치명적인 네트워크 오류뿐만 아니라 파일이 지원되지 않는 컨테이너 형식을 사용하거나 모든 데이터에 대해 지원되지 않는 코덱을 사용하는 경우, 사용자 에이전트는 다음 단계를 실행해야 합니다:

    1. 사용자 에이전트는 가져오기 프로세스를 취소해야 합니다.

    2. 이 하위 알고리즘을 중단하고 자원 선택 알고리즘으로 돌아갑니다.

    미디어 자원에서 오디오 트랙을 발견한 경우
    1. AudioTrack 객체를 생성하여 오디오 트랙을 나타냅니다.

    2. 미디어 요소audioTracks 속성을 AudioTrackList 객체로 업데이트하여 새 AudioTrack 객체를 초기화합니다.

    3. enable알 수 없음으로 설정합니다.

    4. 만약 미디어 자원 또는 URL이 특정 오디오 트랙을 활성화해야 함을 나타내거나, 사용자 에이전트가 특정 오디오 트랙을 선택하여 사용자의 경험을 개선할 수 있는 정보를 가지고 있다면, 이 오디오 트랙이 활성화해야 하는 트랙 중 하나인 경우 enabletrue로 설정하고, 그렇지 않으면 enablefalse로 설정합니다.

      이것은 미디어 조각 구문에 의해 트리거될 수 있지만, 예를 들어 5.1 서라운드 사운드 오디오 트랙을 스테레오 오디오 트랙보다 선택하는 사용자 에이전트에 의해 트리거될 수도 있습니다.

    5. enable이 여전히 알 수 없음인 경우, 미디어 요소에 아직 활성화된 오디오 트랙이 없는 경우 enabletrue로 설정하고, 그렇지 않으면 enablefalse로 설정합니다.

    6. 만약 enabletrue인 경우 이 오디오 트랙을 활성화하고, 그렇지 않으면 이 오디오 트랙을 활성화하지 않습니다.

    7. 이벤트를 발생시켜 addtrack이라는 이름의 이벤트를 AudioTrackList 객체에서 발생시키고, TrackEvent를 사용하여 트랙 속성을 새 AudioTrack 객체로 초기화합니다.

    미디어 자원에서 비디오 트랙을 발견한 경우
    1. VideoTrack 객체를 생성하여 비디오 트랙을 나타냅니다.

    2. 미디어 요소videoTracks 속성을 VideoTrackList 객체로 업데이트하여 새 VideoTrack 객체를 초기화합니다.

    3. enable알 수 없음으로 설정합니다.

    4. 만약 미디어 자원 또는 URL이 특정 비디오 트랙을 활성화해야 함을 나타내거나, 사용자 에이전트가 특정 비디오 트랙을 선택하여 사용자의 경험을 개선할 수 있는 정보를 가지고 있다면, 이 비디오 트랙이 첫 번째로 활성화해야 하는 트랙인 경우 enabletrue로 설정하고, 그렇지 않으면 enablefalse로 설정합니다.

      이것은 다시 미디어 조각 구문에 의해 트리거될 수 있습니다.

    5. enable이 여전히 알 수 없음인 경우, 미디어 요소에 아직 선택된 비디오 트랙이 없는 경우 enabletrue로 설정하고, 그렇지 않으면 enablefalse로 설정합니다.

    6. 만약 enabletrue인 경우 이 트랙을 선택하고 이전에 선택된 비디오 트랙을 선택 해제합니다. 그렇지 않으면 이 비디오 트랙을 선택하지 않습니다. 다른 트랙이 선택 해제된 경우 change 이벤트가 발생합니다.

    7. 이벤트를 발생시켜 addtrack라는 이름의 이벤트를 VideoTrackList 객체에서 발생시키고, TrackEvent를 사용하여 트랙 속성을 새 VideoTrack 객체로 초기화합니다.

    미디어 데이터의 지속 시간을 결정할 수 있을 정도로 충분한 데이터가 가져와진 경우

    이는 자원이 사용 가능하다는 것을 나타냅니다. 사용자 에이전트는 다음 하위 단계를 따라야 합니다:

    1. 미디어 타임라인을 설정하여 현재 재생 위치가장 빠른 위치를 결정합니다. 이것은 미디어 데이터를 기반으로 합니다.

    2. 타임라인 오프셋을 미디어 자원의 0초에 해당하는 날짜 및 시간으로 업데이트합니다. 명시된 날짜와 시간이 없는 경우 타임라인 오프셋은 NaN(Not-a-Number)로 설정되어야 합니다.

    3. 현재 재생 위치공식 재생 위치가장 빠른 위치로 설정합니다.

    4. 미디어 타임라인에서 알려진 마지막 프레임의 시간으로 duration 속성을 업데이트합니다. 만약 알려지지 않은 경우(예: 무한한 스트림), duration 속성을 양의 무한대로 업데이트합니다.

      사용자 에이전트는 durationChange 이벤트를 발생시키기 위해 미디어 요소 작업을 큐에 추가하여 미디어 요소에서 이벤트를 발생시켜 durationchange라는 이름의 이벤트를 요소에 발생시킵니다.

    5. 비디오 요소의 경우, videoWidthvideoHeight 속성을 설정하고 미디어 요소 작업을 큐에 추가하여 이벤트를 발생시켜 resize라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

      그 이후 크기가 변경될 경우 추가 resize 이벤트가 발생할 것입니다.

    6. readyState 속성을 HAVE_METADATA로 설정합니다.

      loadedmetadata DOM 이벤트가 readyState 속성이 새 값으로 설정될 때 발생할 것입니다.

    7. jumped를 false로 설정합니다.

    8. 미디어 요소기본 재생 시작 위치가 0보다 큰 경우 해당 시간으로 탐색하고 jumped를 true로 설정합니다.

    9. 미디어 요소기본 재생 시작 위치를 0으로 설정합니다.

    10. 초기 재생 위치를 0으로 설정합니다.

    11. 만약 미디어 자원 또는 URL이 특정 시작 시간을 나타내는 경우, 초기 재생 위치를 해당 시간으로 설정하고, 만약 jumped가 여전히 false인 경우 해당 시간으로 탐색합니다.

      예를 들어, 미디어 조각 구문을 지원하는 미디어 형식의 경우, 조각을 사용하여 시작 위치를 나타낼 수 있습니다.

    12. 활성화된 오디오 트랙이 없는 경우 오디오 트랙을 활성화합니다. 이것은 change 이벤트가 발생할 것입니다.

    13. 선택된 비디오 트랙이 없는 경우 비디오 트랙을 선택합니다. 이것은 change 이벤트가 발생할 것입니다.

    readyState 속성이 HAVE_CURRENT_DATA에 도달한 후 loadeddata 이벤트가 발생한 후, 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

    사용자 에이전트가 각각의 미디어 자원의 메타데이터를 가져오는 동안 네트워크 사용을 줄이려고 시도하는 경우, 이전에 설명한 규칙에 따라 버퍼링을 중지하게 되며, 여기에는 networkState 속성이 NETWORK_IDLE 값으로 전환되고 suspend 이벤트가 발생하는 것이 포함됩니다.

    사용자 에이전트는 미디어 자원의 지속 시간을 결정하고 재생 전에 이 단계를 거쳐야 합니다.

    전체 미디어 자원이 가져와진 경우(그러나 잠재적으로 그 일부가 디코딩되기 전일 수 있음)

    이벤트를 발생시켜 미디어 요소에서 progress라는 이름의 이벤트를 발생시킵니다.

    networkStateNETWORK_IDLE로 설정하고 이벤트를 발생시켜 suspend라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

    만약 사용자 에이전트가 미디어 데이터를 버리고 다시 얻어야 하는 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 미디어 요소networkStateNETWORK_LOADING로 설정해야 합니다.

    사용자 에이전트가 미디어 자원을 로드 상태로 유지할 수 있다면, 알고리즘은 아래의 최종 단계로 계속되어 알고리즘이 중지됩니다.

    일부 미디어 데이터가 수신된 후 연결이 중단되고 사용자 에이전트가 자원을 가져오려는 시도를 포기하게 되는 경우

    사용자 에이전트가 미디어 요소readyState 속성이 더 이상 HAVE_NOTHING이 아닌 경우에만 자원이 사용 가능한지 여부를 결정한 후 발생한 치명적인 네트워크 오류는 사용자 에이전트가 다음 단계를 실행하게 해야 합니다:

    1. 사용자 에이전트는 가져오기 프로세스를 취소해야 합니다.

    2. error 속성을 MediaError 생성의 결과로 설정합니다. 이때 MEDIA_ERR_NETWORK을 사용합니다.

    3. 요소의 networkState 속성을 NETWORK_IDLE 값으로 설정합니다.

    4. 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

    5. 이벤트를 발생시켜 미디어 요소에서 error라는 이름의 이벤트를 발생시킵니다.

    6. 전체 자원 선택 알고리즘을 중단합니다.

    미디어 데이터가 손상된 경우

    사용자 에이전트가 미디어 요소readyState 속성이 더 이상 HAVE_NOTHING이 아닌 경우에만 자원이 사용 가능한지 여부를 결정한 후 발생한 미디어 데이터 디코딩의 치명적인 오류는 사용자 에이전트가 다음 단계를 실행하게 해야 합니다:

    1. 사용자 에이전트는 가져오기 프로세스를 취소해야 합니다.

    2. error 속성을 MediaError 생성의 결과로 설정합니다. 이때 MEDIA_ERR_DECODE을 사용합니다.

    3. 요소의 networkState 속성을 NETWORK_IDLE 값으로 설정합니다.

    4. 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

    5. 이벤트를 발생시켜 미디어 요소에서 error라는 이름의 이벤트를 발생시킵니다.

    6. 전체 자원 선택 알고리즘을 중단합니다.

    사용자가 미디어 데이터 가져오기 프로세스를 중단한 경우

    사용자가 "중지" 버튼을 눌러 가져오기 프로세스를 중단한 경우, 사용자 에이전트는 다음 단계를 실행해야 합니다. 이 단계는 load() 메서드 자체가 실행 중인 동안 이러한 단계를 따르지 않습니다. 이러한 종류의 중단은 위 단계에서 처리됩니다.

    1. 사용자 에이전트는 가져오기 프로세스를 취소해야 합니다.

    2. error 속성을 MediaError 생성의 결과로 설정합니다. 이때 MEDIA_ERR_ABORTED을 사용합니다.

    3. 이벤트를 발생시켜 미디어 요소에서 abort라는 이름의 이벤트를 발생시킵니다.

    4. 미디어 요소readyState 속성이 HAVE_NOTHING 값과 동일한 경우, 요소의 networkState 속성을 NETWORK_EMPTY 값으로 설정하고, 요소의 포스터 표시 플래그를 true로 설정하고 이벤트를 발생시켜 emptied라는 이름의 이벤트를 요소에서 발생시킵니다.

      그렇지 않으면, 요소의 networkState 속성을 NETWORK_IDLE 값으로 설정합니다.

    5. 요소의 로드 이벤트 지연 플래그를 false로 설정합니다. 이것은 로드 이벤트 지연을 중지합니다.

    6. 전체 자원 선택 알고리즘을 중단합니다.

    미디어 데이터를 가져올 수 있지만 비치명적 오류가 발생했거나 부분적으로만 코덱을 사용할 수 있어 사용자 에이전트가 콘텐츠를 완전히 렌더링할 수는 없지만 전체 재생을 방해하지 않는 경우

    서버가 부분적으로 사용할 수 있지만 최적으로 렌더링할 수 없는 데이터를 반환한 경우, 사용자 에이전트는 처리할 수 있는 부분만 렌더링하고 나머지는 무시해야 합니다.

    미디어 자원에서 사용자 에이전트가 지원하는 미디어 자원 전용 텍스트 트랙을 선언한 경우

    만약 미디어 데이터CORS-동일 출처인 경우, 관련 데이터를 사용하여 미디어 자원 전용 텍스트 트랙을 노출하는 단계를 실행합니다.

    교차 출처 비디오에서는 자막이 노출되지 않습니다. 이는 적대적인 사이트가 사용자의 인트라넷에서 비밀 비디오의 자막을 읽는 것과 같은 공격을 허용할 수 있기 때문입니다.

  5. 최종 단계: 사용자 에이전트가 이 단계에 도달한 경우(자원이 완전히 로드되고 사용 가능하게 유지되는 경우): 전체 자원 선택 알고리즘을 중단합니다.

미디어 요소미디어 요소의 미디어 리소스 특정 트랙을 잊어버리기로 설정될 때, 사용자 에이전트는 미디어 요소텍스트 트랙 목록에서 모든 미디어 리소스 특정 텍스트 트랙을 제거해야 하며, 그런 다음 미디어 요소audioTracks 속성의 AudioTrackList 객체를 비워야 합니다. 그런 다음 미디어 요소videoTracks 속성의 VideoTrackList 객체를 비워야 합니다. 이에 대한 이벤트(특히 removetrack 이벤트)는 발생하지 않으며, 대신 이 알고리즘을 호출하는 다른 알고리즘에 의해 발생하는 erroremptied 이벤트를 사용할 수 있습니다.


preload 속성은 다음과 같은 키워드와 상태를 가진 열거형 속성입니다:

키워드 상태 간단한 설명
auto 자동 사용자 에이전트가 서버에 위험을 주지 않으면서 사용자의 필요에 따라 전체 리소스를 낙관적으로 다운로드할 수 있다는 힌트를 제공합니다.
(빈 문자열)
none 없음 작성자가 사용자가 미디어 리소스를 필요로 하지 않을 것이라고 예상하거나, 서버가 불필요한 트래픽을 최소화하려고 한다는 힌트를 사용자 에이전트에 제공합니다. 이 상태는 버퍼링이 시작될 때 미디어 리소스를 얼마나 공격적으로 실제 다운로드해야 하는지에 대한 힌트를 제공하지 않습니다(예: 사용자가 "재생"을 누를 때).
metadata 메타데이터 작성자가 사용자가 미디어 리소스를 필요로 하지 않을 것이라고 예상하지만, 리소스 메타데이터(크기, 트랙 목록, 지속 시간 등)를 가져오고, 어쩌면 첫 몇 프레임까지 가져오는 것이 합리적이라는 힌트를 사용자 에이전트에 제공합니다. 사용자 에이전트가 메타데이터 이상을 정확하게 가져오지 않는다면, 미디어 요소readyState 속성이 HAVE_METADATA로 설정될 것이며, 일반적으로는 몇 프레임이 추가로 가져와져서 HAVE_CURRENT_DATAHAVE_FUTURE_DATA로 설정될 가능성이 높습니다. 미디어 리소스가 재생 중일 때, 사용자 에이전트에게 대역폭을 희소하게 고려해야 한다는 힌트를 제공하며, 예를 들어 일관된 재생을 유지하기 위해 가장 느린 속도로 미디어 데이터를 다운로드하도록 제안합니다.

이 속성의 값이 없는 경우의 기본값잘못된 값의 기본값은 모두 구현 정의이며, 서버 로드를 줄이면서 최적의 사용자 경험을 제공하기 위한 타협으로 메타데이터 상태가 제안됩니다.

이 속성은 미디어 리소스가 버퍼링되거나 재생 중인 경우에도 변경할 수 있습니다. 위 표의 설명은 이를 염두에 두고 해석해야 합니다.

작성자는 속성을 "none" 또는 "metadata"에서 "auto"로 동적으로 변경할 수 있습니다. 예를 들어, 많은 비디오가 있는 페이지에서는 요청하지 않는 한 비디오를 다운로드하지 않도록 설정하지만, 하나가 요청되면 공격적으로 다운로드해야 함을 나타내기 위해 이 방법을 사용할 수 있습니다.

preload 속성은 작성자가 최상의 사용자 경험을 제공한다고 생각하는 것을 사용자 에이전트에게 힌트로 제공하기 위해 설계되었습니다. 이 속성은 예를 들어 명시적인 사용자 설정이나 사용 가능한 연결 상태에 따라 무시될 수 있습니다.

preload IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

autoplay 속성은 preload 속성을 재정의할 수 있습니다(미디어가 재생되면, preload 속성에 의해 제공된 힌트와 관계없이 우선 버퍼링을 해야 하기 때문에). 두 속성을 모두 포함하는 것은 오류가 아닙니다.


media.buffered

HTMLMediaElement/buffered

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

사용자 에이전트가 버퍼링한 미디어 리소스의 범위를 나타내는 TimeRanges 객체를 반환합니다.

buffered 속성은 사용자 에이전트가 버퍼링한 미디어 리소스의 범위를 나타내는 새 정적 정규화된 TimeRanges 객체를 반환해야 합니다. 사용자 에이전트는 이 속성이 평가될 때 버퍼링된 범위를 정확하게 결정해야 하며, 이는 미디어 스트림에 대해 힘든 검사로만 결정될 수 있는 경우에도 마찬가지입니다.

일반적으로 이는 0점에 고정된 단일 범위가 되지만, 예를 들어, 사용자 에이전트가 탐색에 응답하여 HTTP 범위 요청을 사용하는 경우 여러 범위가 있을 수 있습니다.

사용자 에이전트는 이전에 버퍼링된 데이터를 삭제할 수 있습니다.

따라서, 한 시점에 buffered 속성에 의해 반환된 객체의 범위 내에 포함된 시간 위치가 나중에 동일한 속성에 의해 반환된 객체의 범위에서 제외될 수 있습니다.

매번 새 객체를 반환하는 것은 속성 getter에 좋지 않은 패턴이며, 변경 비용이 높기 때문에 여기서는 그대로 유지됩니다. 새로운 API에 복사해서는 안 됩니다.

4.8.11.6 미디어 리소스의 오프셋
media.duration

HTMLMediaElement/duration

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

미디어 리소스의 시작이 시간 0인 경우, 미디어 리소스의 길이를 초 단위로 반환합니다.

지속 시간이 사용 가능하지 않으면 NaN을 반환합니다.

무한 스트림의 경우 Infinity를 반환합니다.

media.currentTime [ = value ]

HTMLMediaElement/currentTime

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

공식 재생 위치를 초 단위로 반환합니다.

지정된 시간으로 탐색할 수 있습니다.

미디어 리소스에는 시간이 (초 단위로) 미디어 리소스 내의 위치에 매핑되는 미디어 타임라인이 있습니다. 타임라인의 원점은 정의된 가장 이른 위치입니다. 타임라인의 지속 시간은 정의된 마지막 위치입니다.

미디어 리소스가 명시적인 타임라인을 지정하고 그 원점이 음수가 아닌 경우(즉, 각 프레임에 특정 시간 오프셋을 부여하고 첫 번째 프레임에 0 또는 양수 오프셋을 부여하는 경우) 미디어 타임라인은 그 타임라인이어야 합니다. 미디어 리소스가 타임라인을 지정할 수 있는지 여부는 미디어 리소스의 형식에 따라 다릅니다. 미디어 리소스가 명시적인 시작 시간 및 날짜를 지정하는 경우 해당 시간과 날짜를 미디어 타임라인의 0점으로 간주해야 하며, 타임라인 오프셋은 getStartDate() 메서드를 사용하여 노출됩니다.

미디어 리소스에 불연속 타임라인이 있는 경우, 사용자 에이전트는 리소스 시작 시 사용된 타임라인을 리소스 전체에 걸쳐 확장해야 하므로, 미디어 리소스의 미디어 타임라인이 정의된 가장 이른 위치에서 시작하여 선형으로 증가해야 합니다. 기본 미디어 데이터가 순서가 뒤섞이거나 겹치는 시간 코드를 가지고 있더라도 마찬가지입니다.

예를 들어, 두 개의 클립을 하나의 비디오 파일로 연결했지만 비디오 형식이 두 클립의 원래 시간을 노출하는 경우, 비디오 데이터는 00:15..00:29 및 00:05..00:38로 타임라인을 노출할 수 있습니다. 그러나 사용자 에이전트는 이러한 시간을 노출하지 않고 00:15..00:29 및 00:29..01:02로 시간을 노출하여 단일 비디오로 표시할 것입니다.

드문 경우지만 명시적인 타임라인이 없는 미디어 리소스의 경우, 미디어 타임라인의 0 시간은 미디어 리소스의 첫 번째 프레임에 해당해야 합니다. 더 드문 경우로, 어떤 종류의 명시적인 타이밍(프레임 지속 시간조차도)이 없는 미디어 리소스의 경우, 사용자 에이전트는 구현 정의된 방식으로 각 프레임의 시간을 결정해야 합니다.

명시적인 타임라인이 없지만 명시적인 프레임 지속 시간이 있는 파일 형식의 예로는 애니메이션 GIF 형식이 있습니다. 명시적인 타이밍이 전혀 없는 파일 형식의 예로는 JPEG-push 형식(multipart/x-mixed-replace에 JPEG 프레임이 포함된 형식, 종종 MJPEG 스트림의 형식으로 사용됨)이 있습니다.

타이밍 정보가 없는 리소스의 경우에도 사용자 에이전트가 서버에서 원래 제공한 첫 번째 프레임보다 이른 지점으로 탐색할 수 있는 경우, 0 시간은 미디어 리소스의 가장 이른 탐색 가능 시간에 해당해야 합니다. 그렇지 않으면, 0 시간은 서버에서 받은 첫 번째 프레임(사용자 에이전트가 스트림을 받기 시작한 미디어 리소스의 지점)에 해당해야 합니다.

이 문서를 작성할 당시에는 명시적인 프레임 시간 오프셋이 없지만 여전히 서버에서 제공한 첫 번째 프레임 이전의 프레임으로 탐색을 지원하는 형식은 알려진 바 없습니다.

TV 방송사로부터의 스트림을 고려해 봅시다. 이 스트림은 10월의 맑은 금요일 오후에 스트리밍을 시작하며, 항상 연결된 사용자 에이전트에 동일한 미디어 타임라인에서 미디어 데이터를 보냅니다. 이 스트림의 0 시간은 이 스트림의 시작으로 설정됩니다. 몇 달 후, 이 스트림에 연결된 사용자 에이전트는 처음 수신한 프레임의 시간이 수백만 초로 되어 있음을 알게 될 것입니다. getStartDate() 메서드는 항상 방송이 시작된 날짜를 반환할 것이며, 이를 통해 컨트롤러는 스크러버에서 방송이 시작된 시점으로부터의 시간이 아닌 실제 시간을 표시할 수 있습니다(예: "오후 2시 30분" 대신 "8개월, 4시간, 12분, 23초").

여러 개의 연결된 조각이 포함된 비디오를 전달하는 스트림을 고려해 봅시다. 이 스트림은 사용자 에이전트가 특정 시간을 요청할 수 없고, 미리 정해진 순서로 비디오 데이터를 스트리밍하며, 첫 번째로 제공된 프레임은 항상 시간 0으로 식별됩니다. 이 스트림에 연결된 사용자 에이전트가 2010-03-20 23:15:00 UTC부터 2010-03-21 00:05:00 UTC까지 및 2010-02-12 14:25:00 UTC부터 2010-02-12 14:35:00 UTC까지 타임스탬프를 포함한 조각을 수신하면, 이 타임라인은 0초에서 시작하여 3600초(1시간)로 확장될 것입니다. 스트리밍 서버가 두 번째 클립이 끝날 때 연결을 끊었다고 가정하면, duration 속성은 3600을 반환할 것입니다. getStartDate() 메서드는 2010-03-20 23:15:00 UTC에 해당하는 시간으로 새로운 Date 객체를 반환할 것입니다. 그러나 다른 사용자 에이전트가 5분 후에 연결되었다면, (아마도) 2010-03-20 23:20:00 UTC부터 2010-03-21 00:05:00 UTC까지 및 2010-02-12 14:25:00 UTC부터 2010-02-12 14:35:00 UTC까지의 타임스탬프를 포함한 조각을 수신하고, 이 타임라인은 0초에서 시작하여 3300초(55분)로 확장될 것입니다. 이 경우, getStartDate() 메서드는 2010-03-20 23:20:00 UTC에 해당하는 시간으로 새로운 Date 객체를 반환할 것입니다.

이 두 예에서 seekable 속성은 컨트롤러가 실제로 UI에 표시하고자 하는 범위를 제공합니다. 일반적으로 서버가 임의의 시간으로의 탐색을 지원하지 않는다면, 이는 사용자 에이전트가 스트림에 연결된 순간부터 사용자가 얻은 최신 프레임까지의 시간 범위가 됩니다. 그러나 사용자 에이전트가 이전 정보를 삭제하기 시작하면 실제 범위는 더 짧아질 수 있습니다.

어떤 경우든 사용자 에이전트는 정의된 미디어 타임라인을 사용하여 가장 이른 위치가 0보다 크거나 같도록 보장해야 합니다.

미디어 타임라인에는 관련된 시계가 있습니다. 어떤 시계를 사용할지는 사용자 에이전트에 의해 정의되며, 미디어 리소스에 따라 다를 수 있지만, 사용자 벽 시계에 가깝도록 해야 합니다.

미디어 요소에는 현재 재생 위치가 있습니다. 이는 처음에(즉, 미디어 데이터가 없는 경우) 0초여야 합니다. 현재 재생 위치는 미디어 타임라인상의 시간입니다.

미디어 요소에는 또한 공식 재생 위치가 있습니다. 이는 처음에 0초로 설정되어야 합니다. 공식 재생 위치는 스크립트가 실행되는 동안 안정적으로 유지되는 현재 재생 위치의 근사치입니다.

미디어 요소에는 기본 재생 시작 위치도 있습니다. 이는 처음에 0초로 설정되어야 합니다. 이 시간은 미디어가 로드되기 전에 요소가 탐색될 수 있도록 하는 데 사용됩니다.

각 미디어 요소에는 포스터 표시 플래그가 있습니다. 미디어 요소가 생성될 때 이 플래그는 true로 설정되어야 합니다. 이 플래그는 사용자 에이전트가 비디오 콘텐츠 대신 비디오 요소에 대한 포스터 프레임을 표시해야 할 시점을 제어하는 데 사용됩니다.

currentTime 속성은 가져올 때 기본 재생 시작 위치를 반환해야 하며, 이 값이 0인 경우 요소의 공식 재생 위치를 반환해야 합니다. 반환된 값은 초 단위로 표현되어야 합니다. 설정할 때, 만약 미디어 요소의 readyState가 HAVE_NOTHING이라면, 새 값을 기본 재생 시작 위치로 설정해야 하며, 그렇지 않으면 공식 재생 위치로 설정한 후 새 값으로 탐색해야 합니다. 새 값은 초 단위로 해석되어야 합니다.

스트리밍 리소스인 경우, 사용자 에이전트는 버퍼에서 만료된 리소스의 일부를 가져올 수 없을 수 있습니다. 마찬가지로 일부 미디어 리소스는 0에서 시작하지 않는 미디어 타임라인을 가질 수 있습니다. 가장 이른 위치는 스트림 또는 리소스에서 사용자 에이전트가 다시 얻을 수 있는 가장 이른 위치입니다. 이 또한 미디어 타임라인상의 시간입니다.

가장 이른 위치는 API에서 명시적으로 노출되지 않으며, seekable 속성의 TimeRanges 객체에서 첫 번째 범위의 시작 시간에 해당합니다. 또는 그렇지 않으면 현재 재생 위치에 해당합니다.

가장 이른 위치가 변경될 때, 만약 현재 재생 위치가 가장 이른 위치보다 이전에 있다면, 사용자 에이전트는 가장 이른 위치로 탐색해야 합니다. 그렇지 않으면, 사용자 에이전트가 지난 15~250ms 동안 요소에서 timeupdate 이벤트를 발생시키지 않았고 그러한 이벤트에 대한 이벤트 핸들러가 여전히 실행 중이 아닌 경우, 사용자 에이전트는 주어진 미디어 요소에 대해 timeupdate라는 이름의 이벤트를 발생시키기 위해 미디어 요소 작업을 큐에 넣어야 합니다.

위 요구 사항과 메타데이터를 알게 되었을 때 리소스 페치 알고리즘이 시작되는 요구 사항 때문에, 현재 재생 위치는 가장 이른 위치보다 작을 수 없습니다.

사용자 에이전트가 오디오 또는 비디오 트랙이 종료되었음을 알고 해당 트랙과 관련된 모든 미디어 데이터가 가장 이른 위치 이전의 미디어 타임라인 부분에 해당하는 경우, 사용자 에이전트는 다음 단계를 실행하기 위해 주어진 미디어 요소에 대해 미디어 요소 작업을 큐에 넣을 수 있습니다:

  1. 트랙을 audioTracks 속성의 AudioTrackList 객체 또는 videoTracks 속성의 VideoTrackList 객체에서 적절하게 제거합니다.
  2. 이벤트를 발생시키며, 이벤트 이름은 removetrack이고, 미디어 요소의 AudioTrackList 또는 VideoTrackList 객체에서 발생합니다. TrackEvent를 사용하며, track 속성은 트랙을 나타내는 AudioTrack 또는 VideoTrack 객체로 초기화됩니다.

duration 속성은 미디어 리소스의 끝 시간을 초 단위로 반환해야 하며, 미디어 타임라인에 해당합니다. 만약 미디어 데이터가 없다면, 이 속성은 NaN 값을 반환해야 합니다. 만약 미디어 리소스가 제한되지 않은 경우(예: 스트리밍 라디오나 종료 시간이 발표되지 않은 라이브 이벤트), 이 속성은 양의 무한대 값을 반환해야 합니다.

사용자 에이전트는 미디어 리소스의 지속 시간을, 미디어 데이터의 일부를 재생하기 전에, 그리고 readyState 값을 HAVE_METADATA 이상으로 설정하기 전에 결정해야 합니다. 이를 위해 여러 부분의 리소스를 가져와야 할 수도 있습니다.

미디어 리소스의 길이가 알려진 값으로 변경될 때(예: 알 수 없는 상태에서 알려진 상태로 변경되거나, 이전에 설정된 길이에서 새로운 길이로 변경될 때) 사용자 에이전트는 미디어 요소 작업을 대기열에 추가해야 하며, 미디어 요소에서 이벤트를 발생 시키고, 그 이름은 durationchange이어야 합니다. (새로운 미디어 리소스를 로드하는 과정에서 지속 시간이 재설정될 때는 이벤트가 발생하지 않습니다.) 만약 지속 시간이 변경되어 현재 재생 위치미디어 리소스의 끝 시간보다 길어진다면, 사용자 에이전트는 또한 끝 시간으로 이동해야 합니다.

예를 들어, "무한" 스트림이 어떤 이유로 종료되면 지속 시간은 양의 무한대에서 스트림의 마지막 프레임 또는 샘플의 시간으로 변경되고, durationchange 이벤트가 발생합니다. 마찬가지로, 사용자 에이전트가 미디어 리소스의 지속 시간을 처음에 정확히 판단하지 않고 추정하여 이후 새로운 정보에 기반하여 추정을 수정하는 경우, 지속 시간이 변경되며 durationchange 이벤트가 발생합니다.

일부 비디오 파일은 미디어 타임라인의 0 시간에 해당하는 명시적 날짜 및 시간을 포함하고 있으며, 이를 타임라인 오프셋이라고 합니다. 초기에는 타임라인 오프셋은 NaN으로 설정되어야 합니다.

getStartDate() 메서드는 현재 타임라인 오프셋을 나타내는 Date 객체를 반환해야 합니다.


loop 속성은 불리언 속성으로, 지정된 경우 미디어 요소미디어 리소스의 끝에 도달했을 때 다시 시작 지점으로 이동함을 나타냅니다.

HTMLMediaElement/loop

현재 모든 엔진에서 지원됨.

Firefox11+ Safari4+ Chrome3+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS3+ Chrome Android? WebView Android37+ Samsung Internet? Opera Android12.1+

loop IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

4.8.11.7 준비 상태
media.readyState

HTMLMediaElement/readyState

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

요소의 현재 상태를 현재 재생 위치와 관련하여 표현하는 값을 반환합니다. 아래 목록의 코드에서 해당 값을 참조할 수 있습니다.

미디어 요소준비 상태를 가지고 있으며, 이는 현재 재생 위치에서 렌더링할 준비가 어느 정도 되어 있는지를 설명합니다. 가능한 값은 다음과 같으며, 특정 시간에 미디어 요소의 준비 상태는 요소의 상태를 설명하는 최대 값입니다:

HAVE_NOTHING (숫자 값 0)

미디어 리소스에 대한 정보가 전혀 없습니다. 현재 재생 위치에 대한 데이터도 없습니다. 미디어 요소networkState 속성이 NETWORK_EMPTY로 설정된 경우 항상 HAVE_NOTHING 상태에 있습니다.

HAVE_METADATA (숫자 값 1)

리소스의 지속 시간이 확인될 만큼 충분한 데이터가 확보되었습니다. 비디오 요소의 경우, 비디오의 크기도 확인됩니다. 그러나 미디어 데이터현재 재생 위치에서 사용할 수 없습니다.

HAVE_CURRENT_DATA (숫자 값 2)

현재 재생 위치에 대한 데이터는 있지만, 해당 데이터를 이용해 재생 방향으로 재생 위치를 성공적으로 진행시킬 수 있을 만큼 충분하지 않거나, 추가적인 데이터를 확보할 수 없는 상황입니다. 예를 들어, 비디오의 경우 현재 프레임의 데이터는 있지만, 다음 프레임의 데이터가 없을 때를 의미합니다. 이 상태에서 재생이 종료된 경우와도 관련이 있습니다.

HAVE_FUTURE_DATA (숫자 값 3)

현재 재생 위치에 대한 데이터뿐만 아니라, 재생 방향으로 재생 위치를 진행시키기에 충분한 데이터도 확보되어 있습니다. 예를 들어, 비디오의 경우 현재 프레임뿐만 아니라 다음 프레임에 대한 데이터도 있습니다. 그러나 재생이 종료된 경우에는 이 상태에 있을 수 없습니다.

HAVE_ENOUGH_DATA (숫자 값 4)

HAVE_FUTURE_DATA 상태의 모든 조건이 충족되며, 추가적으로 다음 조건 중 하나가 충족됩니다:

실제로는 HAVE_METADATAHAVE_CURRENT_DATA 간의 차이는 거의 없습니다. 이 차이가 중요한 경우는 비디오 요소를 캔버스에 그릴 때입니다. 여기서는 어떤 것이 그려질지 (HAVE_CURRENT_DATA 이상)와 그려지지 않을지 (HAVE_METADATA 이하)를 구분합니다. 비슷하게, HAVE_CURRENT_DATA (현재 프레임만)와 HAVE_FUTURE_DATA (현재 프레임과 다음 프레임)이 극히 미미할 때, 이 차이는 프레임 단위로 탐색하는 인터페이스를 제공할 때만 중요합니다.

networkStateNETWORK_EMPTY가 아닌 미디어 요소의 준비 상태가 변경되면, 사용자 에이전트는 아래에 제시된 단계들을 따라야 합니다.

  1. 다음 목록에서 적용 가능한 첫 번째 하위 단계를 적용합니다:

    이전 준비 상태가 HAVE_NOTHING이었고, 새로운 준비 상태가 HAVE_METADATA인 경우

    미디어 요소 작업을 큐에 추가하여 해당 요소에 이벤트를 발생시키고, loadedmetadata라는 이름의 이벤트를 요소에서 발생시킵니다.

    이 작업이 실행되기 전에, 이벤트 루프 메커니즘의 일부로서 렌더링이 업데이트되어 적절한 경우 비디오 요소의 크기가 조정됩니다.

    이전 준비 상태가 HAVE_METADATA였고, 새로운 준비 상태가 HAVE_CURRENT_DATA 또는 그 이상인 경우

    이것이 미디어 요소에 대해 load() 알고리즘이 마지막으로 호출된 이후 처음 발생한 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 해당 요소에서 이벤트를 발생시키고, loadeddata라는 이름의 이벤트를 발생시켜야 합니다.

    새로운 준비 상태가 HAVE_FUTURE_DATA 또는 HAVE_ENOUGH_DATA인 경우, 아래의 관련 단계를 추가로 실행해야 합니다.

    이전 준비 상태가 HAVE_FUTURE_DATA 이상이었고, 새로운 준비 상태가 HAVE_CURRENT_DATA 이하인 경우

    미디어 요소가 잠재적으로 재생 중이었고, readyState 속성이 HAVE_FUTURE_DATA보다 낮은 값으로 변경되었으며, 요소가 재생을 종료하지 않았고, 오류로 인해 재생이 중지되지 않았으며, 사용자 상호작용을 위해 일시정지되지 않았거나, 인밴드 콘텐츠로 인해 일시정지되지 않은 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 해당 요소에서 timeupdate라는 이름의 이벤트를 발생시키고, 미디어 요소 작업을 큐에 추가하여 해당 요소에서 이벤트를 발생시켜 waiting이라는 이름의 이벤트를 발생시켜야 합니다.

    이전 준비 상태가 HAVE_CURRENT_DATA 이하였고, 새로운 준비 상태가 HAVE_FUTURE_DATA인 경우

    사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 해당 요소에서 canplay라는 이름의 이벤트를 발생시켜야 합니다.

    요소의 paused 속성이 false인 경우, 사용자 에이전트는 해당 요소에 대해 재생 알림을 제공해야 합니다.

    새로운 준비 상태가 HAVE_ENOUGH_DATA인 경우

    이전 준비 상태가 HAVE_CURRENT_DATA 이하인 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 해당 요소에서 canplay라는 이름의 이벤트를 발생시켜야 하며, 요소의 paused 속성이 false인 경우, 해당 요소에 대해 재생 알림을 제공해야 합니다.

    사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 해당 요소에서 canplaythrough라는 이름의 이벤트를 발생시켜야 합니다.

    요소가 자동 재생이 가능하지 않은 경우, 사용자 에이전트는 이 하위 단계를 중단해야 합니다.

    사용자 에이전트는 다음 하위 단계를 실행할 수 있습니다:

    1. paused 속성을 false로 설정합니다.
    2. 요소의 포스터 표시 플래그가 true이면, 이를 false로 설정하고 시간이 흐릅니다 단계를 실행합니다.
    3. 미디어 요소 작업을 큐에 추가하여 요소에서 play라는 이름의 이벤트를 발생시킵니다.
    4. 재생 알림을 제공합니다.

    또는 요소가 비디오 요소인 경우, 사용자 에이전트는 요소가 뷰포트와 교차하는지 여부를 관찰하기 시작할 수 있습니다. 요소가 뷰포트와 교차하면, 요소가 여전히 자동 재생 가능한 경우, 위의 하위 단계를 실행합니다. 선택적으로, 요소가 뷰포트와 교차하지 않으면, 자동 재생 플래그가 여전히 true이고, autoplay 속성이 여전히 지정되어 있는 경우, 다음 하위 단계를 실행합니다:

    1. 내부 일시정지 단계를 실행하고 자동 재생 플래그를 true로 설정합니다.
    2. 미디어 요소 작업을 큐에 추가하여 요소에서 pause라는 이름의 이벤트를 발생시킵니다.

    재생 및 일시정지에 대한 하위 단계는 요소가 뷰포트와 교차하는 동안, 자동 재생 플래그가 true인 한 여러 번 실행될 수 있습니다.

    사용자 에이전트는 자동 재생을 지원할 필요가 없으며, 사용자가 설정한 기본 설정을 존중하는 것이 좋습니다. 저자들은 autoplay 속성을 사용하여 비디오를 강제로 재생시키기보다는, 사용자가 원하는 경우 동작을 재정의할 수 있도록 할 것을 권장합니다.

미디어 요소의 준비 상태가 이러한 상태들 사이에서 불연속적으로 이동할 수 있습니다. 예를 들어, 미디어 요소의 상태가 HAVE_METADATA에서 HAVE_ENOUGH_DATA로 바로 점프하여, HAVE_CURRENT_DATAHAVE_FUTURE_DATA 상태를 거치지 않을 수 있습니다.

readyState IDL 속성은, 취득 시, 현재의 미디어 요소의 준비 상태를 설명하는 위에서 설명된 값을 반환해야 합니다.

autoplay 속성은 부울 속성입니다. 존재할 경우, 사용자 에이전트는 (여기에 설명된 알고리즘에 설명된 대로) 미디어 리소스를 중단 없이 자동으로 재생을 시작합니다.

저자들은 자동 재생을 트리거하기 위해 스크립트를 사용하는 것보다, autoplay 속성을 사용할 것을 권장합니다. 이렇게 하면 사용자가 원치 않을 때, 예를 들어 화면 읽기 프로그램을 사용할 때 자동 재생을 중지할 수 있습니다. 또한 저자들은 자동 재생 동작을 전혀 사용하지 않고, 사용자 에이전트가 사용자가 명시적으로 재생을 시작할 때까지 기다리도록 고려하는 것이 좋습니다.

HTMLMediaElement/autoplay

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

autoplay IDL 속성은 같은 이름의 콘텐츠 속성을 반영해야 합니다.

4.8.11.8 미디어 리소스 재생
media.paused

HTMLMediaElement/paused

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

재생이 일시정지되었으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

media.ended

HTMLMediaElement/ended

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

재생이 미디어 리소스의 끝에 도달하면 true를 반환합니다.

media.defaultPlaybackRate [ = value ]

HTMLMediaElement/defaultPlaybackRate

모든 최신 엔진에서 지원됩니다.

Firefox20+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

기본 재생 속도를 반환하며, 사용자가 미디어 리소스를 빨리 감거나 되감지 않는 경우에 해당합니다.

설정할 수 있으며, 기본 재생 속도를 변경합니다.

기본 속도는 재생에 직접적인 영향을 미치지 않지만, 사용자가 빨리 감기 모드로 전환한 후 다시 일반 재생 모드로 돌아갈 때, 재생 속도가 기본 재생 속도로 돌아가게 됩니다.

media.playbackRate [ = value ]

HTMLMediaElement/playbackRate

모든 최신 엔진에서 지원됩니다.

Firefox20+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

현재 재생 속도를 반환하며, 1.0은 정상 속도를 나타냅니다.

설정할 수 있으며, 재생 속도를 변경합니다.

media.preservesPitch

HTMLMediaElement/preservesPitch

Firefox101+🔰 4+Chrome86+
Opera?Edge86+
Edge (Legacy)?Internet Explorer지원하지 않음
Firefox Android?Safari iOS🔰 4+Chrome Android?WebView Android?Samsung Internet?Opera Android?

재생 속도가 1.0이 아닐 때 피치 보정 알고리즘이 사용되면 true를 반환합니다. 기본값은 true입니다.

false로 설정하여 미디어 리소스의 오디오 피치가 재생 속도에 따라 변경되도록 할 수 있습니다. 이는 미적 및 성능상의 이유로 유용할 수 있습니다.

media.played

사용자 에이전트가 재생한 미디어 리소스의 범위를 나타내는 TimeRanges 객체를 반환합니다.

media.play()

HTMLMediaElement/play

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

paused 속성을 false로 설정하고, 필요한 경우 미디어 리소스를 로드하여 재생을 시작합니다. 재생이 종료되었으면 처음부터 다시 시작합니다.

media.pause()

HTMLMediaElement/pause

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

paused 속성을 true로 설정하고, 필요한 경우 미디어 리소스를 로드합니다.

paused 속성은 미디어 요소가 일시정지되었는지를 나타냅니다. 이 속성은 처음에는 true여야 합니다.

미디어 요소는 다음 상태일 때 차단된 미디어 요소라고 합니다: readyState 속성이 HAVE_NOTHING 상태, HAVE_METADATA 상태, 또는 HAVE_CURRENT_DATA 상태에 있거나, 요소가 사용자 상호작용을 위해 일시정지됨 또는 인밴드 콘텐츠를 위해 일시정지됨 경우.

미디어 요소는 다음 조건이 모두 참인 경우 잠재적으로 재생 중이라고 합니다: paused 속성이 false이고, 요소가 재생을 종료하지 않았고, 재생이 오류로 인해 중지되지 않았으며, 요소가 차단된 미디어 요소가 아닌 경우.

DOM 이벤트 waiting은 요소의 readyState 속성이 HAVE_FUTURE_DATA보다 낮은 값으로 변경되어 잠재적으로 재생 중인 요소가 재생을 중지하는 결과로 발생할 수 있습니다.

미디어 요소는 다음 조건이 모두 참인 경우 자동 재생 가능하다고 합니다:

미디어 요소는 현재 컨텍스트에서 사용자 에이전트와 시스템이 미디어 재생을 허용하는 경우 재생 가능하다고 합니다.

예를 들어, 사용자 에이전트는 미디어 요소Window 객체가 일시적인 활성화를 가지고 있을 때만 재생을 허용할 수 있지만, 음소거된 상태에서 재생을 허용하는 예외를 둘 수 있습니다.

미디어 요소는 다음과 같은 경우 재생이 종료됨 상태라고 합니다:

ended 속성은, 마지막으로 이벤트 루프1단계에 도달했을 때, 미디어 요소재생이 종료됨 상태였고 재생 방향이 앞으로였으면 true를 반환하고, 그렇지 않으면 false를 반환해야 합니다.

미디어 요소는 다음과 같은 경우 오류로 인해 중지됨 상태라고 합니다: 요소의 readyState 속성이 HAVE_METADATA 이상이며, 사용자 에이전트가 비치명적인 오류를 만났고 이 오류로 인해 미디어 데이터 처리 중에 콘텐츠를 현재 재생 위치에서 재생할 수 없는 경우.

미디어 요소는 다음과 같은 경우 사용자 상호작용을 위해 일시정지됨 상태라고 합니다: paused 속성이 false이고, readyState 속성이 HAVE_FUTURE_DATA 또는 HAVE_ENOUGH_DATA 중 하나이며, 사용자 에이전트가 사용자로부터 리소스를 계속하기 위한 선택을 받아야 하는 지점에 도달한 경우.

미디어 요소재생이 종료됨 상태와 사용자 상호작용을 위해 일시정지됨 상태를 동시에 가질 수 있습니다.

미디어 요소잠재적으로 재생 중 상태였으나 사용자 상호작용을 위해 일시정지됨 상태로 인해 재생이 중지된 경우, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 이벤트를 발생시키고, 요소에서 timeupdate라는 이름의 이벤트를 발생시켜야 합니다.

미디어 요소는 다음과 같은 경우 인밴드 콘텐츠를 위해 일시정지됨 상태라고 합니다: paused 속성이 false이고, readyState 속성이 HAVE_FUTURE_DATA 또는 HAVE_ENOUGH_DATA 중 하나이며, 사용자 에이전트가 미디어 리소스의 재생을 일시정지하여 해당 리소스에 시간적으로 고정된 콘텐츠를 재생하거나, 해당 리소스의 세그먼트에 시간적으로 고정된 콘텐츠를 재생하는 경우.

미디어 요소인밴드 콘텐츠를 위해 일시정지됨 상태가 될 수 있는 예는, 사용자 에이전트가 외부 WebVTT 파일에서 오디오 설명을 재생하고, 큐의 시작 시간과 종료 시간 사이의 시간이 큐에 생성된 음성보다 짧은 경우입니다.


현재 재생 위치재생 방향이 앞으로일 때 미디어 리소스의 끝에 도달하면, 사용자 에이전트는 다음 단계를 따라야 합니다:

  1. 미디어 요소loop 속성이 지정된 경우, 미디어 리소스의 가장 이른 위치로 이동하고 종료합니다.

  2. 위에서 정의한 대로 ended IDL 속성은 이벤트 루프1단계로 돌아오면 true를 반환하기 시작합니다.

  3. 미디어 요소 작업을 큐에 추가하고 다음 단계를 실행합니다:

    1. 이벤트를 발생시키고 timeupdate라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

    2. 미디어 요소재생이 종료됨 상태이며, 재생 방향이 앞으로이고, paused가 false인 경우:

      1. paused 속성을 true로 설정합니다.

      2. 이벤트를 발생시키고 pause라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

      3. 보류 중인 재생 약속을 취소하고, 보류 중인 재생 약속을 "AbortError" DOMException으로 거부합니다.

    3. 이벤트를 발생시키고 ended라는 이름의 이벤트를 미디어 요소에서 발생시킵니다.

현재 재생 위치재생 방향이 역방향일 때 가장 이른 위치에 도달하면, 사용자 에이전트는 단순히 미디어 요소 작업을 큐에 추가하여 이벤트를 발생시키고, timeupdate라는 이름의 이벤트를 요소에서 발생시켜야 합니다.

여기서 "도달"이라는 단어는 현재 재생 위치가 일반 재생 중에 변경될 필요가 없음을 의미합니다. 예를 들어 탐색을 통해 변경될 수 있습니다.


defaultPlaybackRate 속성은 미디어 리소스가 고유 속도의 배수로 재생될 때 원하는 속도를 나타냅니다. 이 속성은 수정 가능하며, 값을 가져올 때 마지막으로 설정된 값을 반환해야 하고, 아직 설정되지 않은 경우 1.0을 반환해야 합니다. 설정 시 속성은 새 값으로 설정되어야 합니다.

defaultPlaybackRate 속성은 사용자 에이전트가 사용자에게 인터페이스를 노출할 때 사용됩니다.

playbackRate 속성은 미디어 리소스가 고유 속도의 배수로 재생될 때의 실질적인 재생 속도를 나타냅니다. 이 값이 defaultPlaybackRate와 같지 않다면, 사용자가 빨리 감기 또는 슬로 모션 재생과 같은 기능을 사용 중이라는 의미입니다. 이 속성은 수정 가능하며, 값을 가져올 때 마지막으로 설정된 값을 반환해야 하고, 아직 설정되지 않은 경우 1.0을 반환해야 합니다. 설정 시, 사용자 에이전트는 다음 단계를 따라야 합니다:

  1. 주어진 값이 사용자 에이전트에서 지원되지 않으면 "NotSupportedError" DOMException을 발생시킵니다.

  2. playbackRate 속성을 새 값으로 설정하고, 요소가 잠재적으로 재생 중이면 재생 속도를 변경합니다.

defaultPlaybackRate 또는 playbackRate 속성이 값이 변경되면(스크립트에 의해 설정되거나 사용자 에이전트에 의해 직접 변경되는 경우, 예를 들어 사용자 제어에 응답하여) 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 이벤트를 발생시키고, ratechange라는 이름의 이벤트를 미디어 요소에서 발생시켜야 합니다. 사용자 에이전트는 속성 변경을 부드럽게 처리해야 하며, 이에 따라 재생에 눈에 띄는 간격이나 음소거가 발생하지 않도록 해야 합니다.

preservesPitch getter 단계는 재생 중 피치 보정 알고리즘이 적용된 경우 true를 반환하도록 합니다. setter 단계는 피치 보정 알고리즘을 켜거나 끄도록 하고, 이에 따라 재생에 눈에 띄는 간격이나 음소거가 발생하지 않도록 해야 합니다. 기본적으로 이러한 피치 보정 알고리즘이 적용되어야 합니다(즉, getter는 초기 상태에서 true를 반환해야 합니다).


played 속성은 새로운 정적 정규화된 TimeRanges 객체를 반환해야 합니다. 이 객체는 속성이 평가될 때, 일반적인 재생 중에 현재 재생 위치미디어 리소스미디어 타임라인에서 통상적인 단조 증가를 통해 도달한 지점을 나타냅니다(있는 경우).

매번 새로운 객체를 반환하는 것은 속성 getter에 대해 좋지 않은 패턴이며, 변경하는 데 비용이 많이 들기 때문에 여기에서만 유지됩니다. 이 패턴은 새로운 API에 복사해서는 안 됩니다.


미디어 요소보류 중인 재생 약속 목록을 가지고 있으며, 이 목록은 처음에는 비어 있어야 합니다.

미디어 요소보류 중인 재생 약속을 가져오기 위해, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. promises라는 빈 약속 목록을 만듭니다.

  2. 미디어 요소보류 중인 재생 약속 목록promises로 복사합니다.

  3. 미디어 요소보류 중인 재생 약속 목록을 비웁니다.

  4. promises를 반환합니다.

미디어 요소에 대해 promises 목록을 사용하여 보류 중인 재생 약속을 해결하기 위해, 사용자 에이전트는 promises에 있는 각 약속을 undefined로 해결해야 합니다.

미디어 요소에 대해 promises 목록과 예외 이름 error를 사용하여 보류 중인 재생 약속을 거부하기 위해, 사용자 에이전트는 promises에 있는 각 약속을 error로 거부해야 합니다.

미디어 요소에 대해 재생에 대해 알리기 위해, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. 보류 중인 재생 약속을 가져오고 promises를 결과로 사용합니다.

  2. 해당 요소에 대해 미디어 요소 작업을 큐에 추가하고 다음 단계를 수행합니다:

    1. 이벤트를 발생시키고, playing이라는 이름의 이벤트를 요소에서 발생시킵니다.

    2. 보류 중인 재생 약속을 해결하여 promises를 사용합니다.

미디어 요소에 대해 play() 메서드가 호출될 때, 사용자 에이전트는 다음 단계를 수행해야 합니다.

  1. 미디어 요소재생이 허용되지 않은 경우, 다음으로 거부된 약속을 반환합니다: "NotAllowedError" DOMException.

  2. 미디어 요소error 속성이 null이 아니고, 코드MEDIA_ERR_SRC_NOT_SUPPORTED인 경우, 다음으로 거부된 약속을 반환합니다: "NotSupportedError" DOMException.

    이것은 전용 미디어 소스 실패 단계가 실행되었음을 의미합니다. 미디어 요소 로드 알고리즘error 속성을 지우기 전까지 재생이 불가능합니다.

  3. promise라는 새 약속을 만들고, 보류 중인 재생 약속 목록promise를 추가합니다.

  4. 내부 재생 단계를 실행하여 미디어 요소에 대해 실행합니다.

  5. promise를 반환합니다.

미디어 요소에 대한 내부 재생 단계는 다음과 같습니다:

  1. 미디어 요소networkState 속성이 NETWORK_EMPTY 값을 가지면, 미디어 요소리소스 선택 알고리즘을 호출합니다.

  2. 재생이 종료되었고 재생 방향이 앞으로인 경우, 미디어 리소스의 가장 이른 위치로 탐색합니다.

    이것은 사용자 에이전트가 미디어 요소를 위해 미디어 요소 작업을 큐에 추가하고 timeupdate라는 이름의 이벤트를 발생시키는 결과를 가져옵니다.

  3. 미디어 요소paused 속성이 true이면:

    1. paused의 값을 false로 변경합니다.

    2. 포스터 표시 플래그가 true이면, 요소의 포스터 표시 플래그를 false로 설정하고 시간은 흐른다 단계를 실행합니다.

    3. 미디어 요소 작업을 큐에 추가하여 play라는 이름의 이벤트를 요소에서 발생시킵니다.

    4. 미디어 요소readyState 속성이 HAVE_NOTHING, HAVE_METADATA 또는 HAVE_CURRENT_DATA 값을 가지면, 미디어 요소 작업을 큐에 추가하고 waiting이라는 이름의 이벤트를 요소에서 발생시킵니다.

      그렇지 않으면, 미디어 요소readyState 속성이 HAVE_FUTURE_DATA 또는 HAVE_ENOUGH_DATA 값을 가지면, 해당 요소에 대해 재생에 대해 알리기를 수행합니다.

  4. 그렇지 않으면, 미디어 요소readyState 속성이 HAVE_FUTURE_DATA 또는 HAVE_ENOUGH_DATA 값을 가지면, 보류 중인 재생 약속을 가져오고 미디어 요소 작업을 큐에 추가하여 보류 중인 재생 약속을 해결합니다.

    미디어 요소는 이미 재생 중입니다. 그러나, 큐에 추가된 작업이 실행되기 전에 promise거부될 가능성이 있습니다.

  5. 미디어 요소자동 재생 가능 플래그를 false로 설정합니다.


미디어 요소pause() 메서드가 호출되거나 사용자 에이전트가 미디어 요소를 일시정지해야 할 때, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. 미디어 요소networkState 속성이 NETWORK_EMPTY 값을 가지면, 미디어 요소리소스 선택 알고리즘을 호출합니다.

  2. 미디어 요소에 대해 내부 일시정지 단계를 실행합니다.

미디어 요소내부 일시정지 단계는 다음과 같습니다:

  1. 미디어 요소자동 재생 가능 플래그를 false로 설정합니다.

  2. 미디어 요소paused 속성이 false이면, 다음 단계를 실행합니다:

    1. paused 값을 true로 변경합니다.

    2. 보류 중인 재생 약속을 가져옵니다 그리고 그 결과를 promises로 저장합니다.

    3. 미디어 요소 작업을 큐에 추가하고, 다음 단계를 실행합니다:

      1. 이벤트를 발생시키고, timeupdate라는 이름의 이벤트를 요소에서 발생시킵니다.

      2. 이벤트를 발생시키고, pause라는 이름의 이벤트를 요소에서 발생시킵니다.

      3. 보류 중인 재생 약속을 promises와 함께 거부합니다, 그리고 "AbortError" DOMException을 사용합니다.

    4. 공식 재생 위치현재 재생 위치로 설정합니다.


요소의 playbackRate가 양수 또는 0이면, 재생 방향은 앞으로입니다. 그렇지 않으면, 재생 방향은 뒤로입니다.

미디어 요소잠재적으로 재생 중이고 해당 Document완전히 활성화된 Document일 때, 요소의 현재 재생 위치는 요소의 playbackRate 단위로 미디어 타임라인의 시간당 단위 시간당 단조 증가해야 합니다. (이 명세서는 항상 이를 '증가'로 지칭하지만, 요소의 playbackRate가 음수인 경우 실제로는 '감소'가 될 수 있습니다.)

요소의 playbackRate는 0.0일 수 있으며, 이 경우 재생 위치가 이동하지 않지만, 재생이 일시정지되지 않습니다 (paused 상태가 되지 않으며 pause 이벤트도 발생하지 않습니다).

이 명세서는 사용자 에이전트가 적절한 재생 속도를 어떻게 달성하는지 정의하지 않습니다. 프로토콜 및 사용 가능한 미디어에 따라, 사용자 에이전트가 서버와 협상하여 적절한 속도로 미디어 데이터를 제공받아, 클라이언트가 실제로 프레임을 드롭하거나 보간할 필요가 없도록 할 가능성도 있습니다.

사용자 에이전트가 안정된 상태를 제공할 때마다, 공식 재생 위치현재 재생 위치로 설정되어야 합니다.

재생 방향이 뒤로일 때, 해당하는 오디오는 음소거되어야 합니다. 요소의 playbackRate가 너무 낮거나 너무 높아 사용자 에이전트가 오디오를 제대로 재생할 수 없는 경우에도 해당 오디오는 음소거되어야 합니다. 요소의 playbackRate가 1.0이 아니고 preservesPitch가 true인 경우, 사용자 에이전트는 원래의 음정을 유지하도록 피치 조정을 적용해야 합니다. 그렇지 않으면, 사용자 에이전트는 피치 조정 없이 오디오를 빠르게 또는 느리게 재생해야 합니다.

미디어 요소잠재적으로 재생 중일 때, 재생된 오디오 데이터는 요소의 현재 재생 위치와 동기화되어야 하며, 효과적인 미디어 볼륨으로 재생되어야 합니다. 사용자 에이전트는 이벤트 루프가 마지막으로 1단계에 도달했을 때 활성화된 오디오 트랙에서 오디오를 재생해야 합니다.

미디어 요소잠재적으로 재생 중이 아니면, 해당 요소의 오디오는 재생되지 않아야 합니다.

미디어 요소잠재적으로 재생 중이지만, 문서에 포함되지 않은 경우, 비디오는 재생되지 않지만, 오디오 구성 요소는 재생되어야 합니다. 모든 참조가 제거되었더라도 미디어 요소는 재생을 중단해서는 안 됩니다. 미디어 요소가 더 이상 오디오를 재생할 수 없는 상태에 도달했을 때만 해당 요소가 가비지 수집될 수 있습니다.

명시적 참조가 없는 요소가 오디오를 재생하는 경우도 가능합니다. 예를 들어, 일시정지되지 않았지만 콘텐츠 버퍼링을 기다리며 중단된 상태이거나, 여전히 버퍼링 중이지만 suspend 이벤트 리스너가 재생을 시작하는 경우가 있습니다. 오디오 트랙이 없는 미디어 리소스를 가진 미디어 요소도 이벤트 리스너를 통해 미디어 리소스를 변경하면 나중에 다시 오디오를 재생할 수 있습니다.


미디어 요소새로 도입된 큐 목록을 가지며, 이는 처음에는 비어 있어야 합니다. 텍스트 트랙 큐큐 목록에 추가될 때마다, 텍스트 트랙텍스트 트랙 목록에 있는 미디어 요소에 대해, 그 미디어 요소새로 도입된 큐 목록에 추가되어야 합니다. 또한 텍스트 트랙텍스트 트랙 목록에 추가될 때마다, 그 텍스트 트랙의 모든 들은 큐 목록에 있는 모든 큐가 미디어 요소새로 도입된 큐 목록에 추가되어야 합니다. 새 큐가 추가된 경우, 사용자가 미디어 요소포스터 표시 플래그가 설정되지 않은 상태에서 새로 도입된 큐 목록에 새로운 큐가 추가되었을 때, 사용자 에이전트는 시간은 흐른다 단계를 실행해야 합니다.

텍스트 트랙 큐큐 목록에서 제거되거나 텍스트 트랙텍스트 트랙 목록에서 제거될 때마다, 만약 미디어 요소포스터 표시 플래그가 설정되지 않은 경우, 사용자 에이전트는 시간은 흐른다 단계를 실행해야 합니다.

현재 재생 위치미디어 요소의 (예: 재생 또는 탐색으로 인한) 변경될 때, 사용자 에이전트는 시간이 흐른다 단계를 실행해야 합니다. 캡션을 비디오의 장면 전환과 동기화하는 등, 큐 이벤트 실행의 타이밍 정확도에 의존하는 사용 사례를 지원하기 위해 사용자 에이전트는 큐 이벤트를 미디어 타임라인의 위치와 최대한 가깝게, 이상적으로는 20밀리초 이내에 실행해야 합니다. 현재 재생 위치가 단계가 실행되는 동안 변경되면, 사용자 에이전트는 단계가 완료될 때까지 기다렸다가 즉시 단계를 다시 실행해야 합니다. 따라서 이러한 단계는 가능한 한 자주 실행됩니다.

한 번의 반복이 오래 걸리면, 사용자가 서두르는 과정에서 짧은 지속 시간의 가 건너뛰어질 수 있어, 이러한 큐는 activeCues 목록에 나타나지 않을 수 있습니다.

시간이 흐른다 단계는 다음과 같습니다:

  1. current cues 목록으로 설정합니다. 이 목록은 숨김 또는 표시 중인 텍스트 트랙들을 초기화하여 구성됩니다. 단, 비활성화된 큐는 포함되지 않습니다. current cues에 포함될 큐는 현재 재생 위치시작 시간보다 작거나 같고, 종료 시간보다 큰 큐여야 합니다.

  2. other cues 목록으로 설정합니다. 이 목록은 숨김 또는 표시 중인 텍스트 트랙들을 초기화하여 구성됩니다. 단, current cues에 포함되지 않은 큐여야 합니다.

  3. last time을 이 알고리즘이 마지막으로 실행되었을 때의 현재 재생 위치로 설정합니다. 이 알고리즘이 처음 실행되는 것이 아니라면 last time을 설정합니다.

  4. 현재 재생 위치가 마지막으로 이 알고리즘이 실행된 이후로 정상적인 재생 동안의 통상적인 단조 증가를 통해서만 변경된 경우, missed cuesother cues 목록에서 시작 시간last time보다 크거나 같고 종료 시간현재 재생 위치보다 작거나 같은 목록으로 설정합니다. 그렇지 않으면 missed cues를 빈 목록으로 설정합니다.

  5. missed cues 목록에 있는 미디어 요소새로 도입된 큐 목록에 포함된 모든 큐를 제거한 후, 요소의 새로 도입된 큐 목록을 비웁니다.

  6. 정상적인 재생 동안 현재 재생 위치의 통상적인 단조 증가를 통해 시간이 도달되었고, 사용자 에이전트가 지난 15~250ms 동안 해당 요소에서 timeupdate 이벤트를 실행하지 않았으며 그러한 이벤트에 대한 이벤트 핸들러를 아직 실행 중이지 않은 경우, 사용자 에이전트는 해당 미디어 요소에서 timeupdate 이벤트를 큐잉해야 합니다. (다른 경우, 예를 들어 명시적인 탐색(seek)에서는 관련 이벤트가 현재 재생 위치 변경의 전체 과정의 일부로 실행됩니다.)

    따라서 이 이벤트는 약 66Hz보다 빠르게 또는 4Hz보다 느리게 실행되지 않습니다 (이벤트 핸들러가 실행되는 데 250ms 이상 걸리지 않는다고 가정할 때). 사용자 에이전트는 시스템 부하 및 이벤트가 매번 처리되는 평균 비용을 기반으로 이벤트의 빈도를 조정하여, 사용자 에이전트가 비디오를 디코딩하면서 UI 업데이트를 편안하게 처리할 수 있을 때만 빈도가 더 자주 발생하지 않도록 권장됩니다.

  7. 모든 current cues에 있는 경우, 텍스트 트랙 큐 활성 플래그가 설정되고, other cues에 있는 중 어느 것도 텍스트 트랙 큐 활성 플래그가 설정되지 않았으며, missed cues가 비어 있으면 반환합니다.

  8. 정상적인 재생 동안 현재 재생 위치의 통상적인 단조 증가를 통해 시간이 도달되었고, other cues가 있으며 해당 큐가 텍스트 트랙 큐 종료 시 일시정지 플래그가 설정되어 있고, 텍스트 트랙 큐 활성 플래그가 설정되어 있거나 missed cues에도 포함되어 있는 경우, 즉시 미디어 요소의 재생을 일시 중지합니다.

    다른 경우, 예를 들어 명시적인 탐색(seek)에서는 의 종료 시간을 넘어서도 재생이 일시 중지되지 않으며, 설령 그 텍스트 트랙 큐 종료 시 일시정지 플래그가 설정되어 있어도 마찬가지입니다.

  9. events작업 목록으로 설정합니다. 이 목록은 처음에는 비어 있습니다. 이 목록에 있는 각 작업텍스트 트랙, 텍스트 트랙 큐 및 시간을 포함합니다. 이 목록은 작업이 큐잉되기 전에 정렬됩니다.

    affected tracks텍스트 트랙 목록으로 설정합니다. 이 목록은 처음에는 비어 있습니다.

    아래 단계에서 target텍스트 트랙 큐event라는 이름의 이벤트를 준비하라고 할 때, 사용자 에이전트는 다음 단계를 실행해야 합니다:

    1. tracktarget과 연관된 텍스트 트랙으로 설정합니다.

    2. target에서 event라는 이름의 이벤트를 작업을 생성하여 실행합니다.

    3. 생성된 작업time, 텍스트 트랙 track, 텍스트 트랙 큐 target과 연관하여 events에 추가합니다.

    4. trackaffected tracks에 추가합니다.

  10. missed cues에 있는 텍스트 트랙 큐 각각에 대해 이벤트 준비를 하고 enter 라는 이름의 이벤트를 TextTrackCue 객체에서 텍스트 트랙 큐 시작 시간과 함께 실행합니다.

  11. other cues에 있는 텍스트 트랙 큐 각각에 대해 텍스트 트랙 큐 활성 플래그가 설정되었거나 missed cues에 있는 경우, 이벤트 준비를 하고 exit 라는 이름의 이벤트를 TextTrackCue 객체에서 텍스트 트랙 큐 종료 시간텍스트 트랙 큐 시작 시간 중 더 늦은 시간과 함께 실행합니다.

  12. current cues에 있지만 텍스트 트랙 큐 활성 플래그가 설정되지 않은 텍스트 트랙 큐 각각에 대해 이벤트 준비를 하고 enter 라는 이름의 이벤트를 TextTrackCue 객체에서 텍스트 트랙 큐 시작 시간과 함께 실행합니다.

  13. events에 있는 작업을 시간 순서대로 오름차순으로 정렬합니다 (작업은 더 이른 시간이 먼저 옵니다).

    events에 있는 작업 중 시간이 동일한 작업들을 텍스트 트랙 큐 순서에 따라 추가로 정렬합니다. 이 정렬은 텍스트 트랙 큐와 연관된 작업에서 수행됩니다.

    마지막으로, 동일한 시간과 동일한 텍스트 트랙 큐 순서를 가진 작업들을 정렬할 때는 작업 enter 이벤트를 실행하는 경우, exit 이벤트를 실행하는 작업보다 우선 배치합니다.

  14. events에 있는 각 작업에 대해, 미디어 요소미디어 요소 작업을 큐잉합니다. 이 작업은 리스트 순서대로 수행됩니다.

  15. affected tracks미디어 요소텍스트 트랙 목록에 나타나는 순서대로 정렬하고 중복을 제거합니다.

  16. 리스트 순서대로 affected tracks에 있는 각 텍스트 트랙에 대해 미디어 요소미디어 요소 작업을 큐잉하고 이벤트를 실행합니다. 이벤트 이름은 cuechange 이며, TextTrack 객체에서 실행됩니다. 만약 텍스트 트랙에 해당되는 track 요소가 있는 경우, 해당 이벤트를 실행하여, 이름이 cuechange 인 이벤트가 track 요소에서 실행되도록 합니다.

  17. current cues에 있는 모든 텍스트 트랙 큐 활성 플래그를 설정하고, other cues에 있는 모든 텍스트 트랙 큐 활성 플래그를 해제합니다.

  18. affected tracks에 있는 각 텍스트 트랙에 대해 텍스트 트랙 렌더링 업데이트 규칙을 실행합니다. 이때, text track텍스트 트랙 언어가 비어 있지 않으면 이를 대체 언어로 제공합니다. 예를 들어, WebVTT를 기반으로 하는 텍스트 트랙의 경우, WebVTT 텍스트 트랙 표시 업데이트 규칙을 적용합니다. [WEBVTT]

위 알고리즘의 목적을 위해, 텍스트 트랙 큐텍스트 트랙의 일부로 간주되며, 단지 텍스트 트랙과 연관되어 있는 것만으로는 간주되지 않습니다. 오직 텍스트 트랙 큐 목록에 나열되어 있는 경우에만 해당됩니다.

만약 미디어 요소노드 문서완전히 활성화된 문서 상태를 잃으면, 해당 문서가 다시 활성화될 때까지 재생이 중단됩니다.

미디어 요소문서에서 제거될 때, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. 안정된 상태를 기다리고, 작업을 계속하여 미디어 요소 document 에서 제거합니다. 동기화된 섹션은 이 알고리즘의 나머지 단계를 포함합니다. (동기화된 섹션의 단계는 ⌛로 표시됩니다.)

  2. 미디어 요소문서에 있으면, 반환합니다.

  3. 내부 일시정지 단계미디어 요소에 대해 실행합니다.

4.8.11.9 탐색
media.seeking

사용자 에이전트가 현재 탐색 중인 경우 true를 반환합니다.

media.seekable

HTMLMediaElement/seekable

모든 현재 엔진에서 지원.

Firefox8+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

사용자 에이전트가 탐색할 수 있는 미디어 리소스의 범위를 나타내는 TimeRanges 객체를 반환합니다.

media.fastSeek(time)

HTMLMediaElement/fastSeek

Firefox31+Safari8+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

정밀도를 희생하여 가능한 한 빠르게 주어진 time으로 탐색합니다. (정밀하게 탐색하려면 currentTime 속성을 사용하십시오.)

미디어 리소스가 로드되지 않은 경우 이 작업은 아무것도 하지 않습니다.

seeking 속성은 처음에 false 값을 가져야 합니다.

fastSeek(time) 메서드는 time으로 탐색을 수행해야 하며, approximate-for-speed 플래그가 설정되어 있어야 합니다.

사용자 에이전트가 new playback position에서 미디어 리소스탐색을 해야 하는 경우, 선택적으로 approximate-for-speed 플래그가 설정된 경우, 사용자 에이전트는 다음 단계를 실행해야 합니다. 이 알고리즘은 이벤트 루프 메커니즘과 밀접하게 상호 작용합니다. 특히, 이벤트 루프 알고리즘의 일부로서 트리거되는 동기화된 섹션이 있습니다. 이 섹션의 단계는 ⌛로 표시됩니다.

  1. 미디어 요소포스터 표시 플래그를 false로 설정합니다.

  2. 미디어 요소readyStateHAVE_NOTHING이면, 반환합니다.

  3. 요소의 seeking IDL 속성이 true인 경우, 이 알고리즘의 또 다른 인스턴스가 이미 실행 중입니다. 해당 알고리즘 인스턴스를 실행 중인 단계를 기다리지 않고 중단합니다.

  4. seeking IDL 속성을 true로 설정합니다.

  5. 탐색이 DOM 메서드 호출이나 IDL 속성 설정에 응답하여 발생한 경우, 스크립트를 계속 실행합니다. 나머지 단계는 병렬로 실행해야 합니다. ⌛로 표시된 단계를 제외하고, 이 알고리즘의 또 다른 인스턴스가 호출되어 언제든지 중단될 수 있습니다.

  6. 새로운 재생 위치가 미디어 리소스의 끝 이후인 경우, 그 위치를 대신 미디어 리소스의 끝으로 설정합니다.

  7. 새로운 재생 위치가 가장 빠른 가능한 위치보다 이전인 경우, 그 위치를 대신 가장 빠른 가능한 위치로 설정합니다.

  8. (이제 변경되었을 수도 있는) 새로운 재생 위치가 seekable 속성에 제공된 범위 중 하나에 포함되지 않는 경우, 그 위치를 대신 seekable 속성에 제공된 범위 중 새로운 재생 위치에 가장 가까운 위치로 설정합니다. 두 위치 모두 해당 조건을 만족하는 경우(즉, 새로운 재생 위치가 seekable 속성의 두 범위 사이의 정확한 중간에 있는 경우), 현재 재생 위치에 가장 가까운 위치를 사용합니다. seekable 속성에 제공된 범위가 없는 경우, seeking IDL 속성을 false로 설정하고 반환합니다.

  9. approximate-for-speed 플래그가 설정된 경우, 새로운 재생 위치를 재생이 즉시 재개될 수 있는 값으로 조정합니다. 이 단계 이전의 새로운 재생 위치가 현재 재생 위치보다 이전인 경우, 조정된 새로운 재생 위치도 현재 재생 위치 이전이어야 합니다. 마찬가지로, 이 단계 이전의 새로운 재생 위치가 현재 재생 위치 이후인 경우, 조정된 새로운 재생 위치도 현재 재생 위치 이후여야 합니다.

    예를 들어, 사용자 에이전트는 인근의 키 프레임으로 스냅하여 중간 프레임을 디코딩한 다음 폐기하는 데 시간을 소비하지 않고 재생을 재개할 수 있습니다.

  10. 미디어 요소 작업을 대기열에 추가하여 이벤트를 발생시키도록 하고, 요소에 대해 seeking이라는 이름의 이벤트를 발생시킵니다.

  11. 현재 재생 위치를 새로운 재생 위치로 설정합니다.

    미디어 요소가 탐색을 시작하기 직전에 잠재적으로 재생 중이었으나, 탐색으로 인해 readyState 속성이 HAVE_FUTURE_DATA 미만의 값으로 변경된 경우, waiting 이벤트가 요소에서 발생할 것입니다.

    이 단계는 현재 재생 위치를 설정하며, 따라서 사용자 에이전트가 실제로 해당 위치의 미디어 데이터를 렌더링할 수 있는지 여부를 결정하기 전이라도 재생이 "미디어 리소스의 끝에 도달"하는 시점에 관한 규칙과 같은 다른 조건을 즉시 트리거할 수 있습니다(루핑을 처리하는 로직의 일부입니다).

    currentTime 속성은 공식 재생 위치를 반환하며, 현재 재생 위치가 아니므로 이 알고리즘과는 별개로 스크립트 실행 전에 업데이트됩니다.

  12. 사용자 에이전트가 새로운 재생 위치에 대한 미디어 데이터가 사용 가능한지 여부를 확인할 때까지 기다리고, 가능하다면 해당 위치를 재생할 수 있을 정도로 데이터를 디코딩할 때까지 기다립니다.

  13. 안정된 상태를 대기합니다. 동기화된 섹션은 이 알고리즘의 나머지 단계로 구성됩니다. (동기화된 섹션의 단계는 ⌛로 표시됩니다.)

  14. seeking IDL 속성을 false로 설정합니다.

  15. 시간이 흐른다 단계를 실행합니다.

  16. 미디어 요소 작업을 대기열에 추가하여 이벤트를 발생시키도록 하고, 요소에 대해 timeupdate라는 이름의 이벤트를 발생시킵니다.

  17. 미디어 요소 작업을 대기열에 추가하여 이벤트를 발생시키도록 하고, 요소에 대해 seeked라는 이름의 이벤트를 발생시킵니다.


seekable 속성은 사용자 에이전트가 탐색할 수 있는 미디어 리소스의 범위를 나타내는 새로운 정적 정규화된 TimeRanges 객체를 반환해야 하며, 이는 속성이 평가되는 시점에 해당합니다.

사용자 에이전트가 미디어 리소스의 어디에서든 탐색할 수 있는 경우, 예를 들어 단순한 동영상 파일이고 사용자 에이전트와 서버가 HTTP 범위 요청을 지원하기 때문에 이 속성은 하나의 범위를 가진 객체를 반환합니다. 이 범위의 시작은 첫 번째 프레임의 시간(가장 빠른 가능한 위치, 일반적으로 0)이고, 끝은 첫 번째 프레임의 시간에 duration 속성 값(마지막 프레임의 시간과 동일할 수 있으며, 양의 무한대일 수 있음)을 더한 값입니다.

이 범위는 사용자 에이전트가 무한 스트림에서 슬라이딩 윈도우를 버퍼링하는 경우와 같이 지속적으로 변경될 수 있습니다. 예를 들어 DVR이 실시간 TV를 시청할 때 이러한 동작이 나타납니다.

매번 새로운 객체를 반환하는 것은 속성 getter에 대한 나쁜 패턴이며, 변경하는 데 비용이 많이 들기 때문에 여기서만 명시됩니다. 새로운 API에는 이를 복사해서는 안 됩니다.

사용자 에이전트는 탐색 가능성에 대해 매우 자유롭고 낙관적인 견해를 취해야 합니다. 또한 가능한 경우 최근 콘텐츠를 버퍼링하여 탐색을 빠르게 할 수 있도록 해야 합니다.

예를 들어, HTTP 범위 요청을 지원하지 않는 HTTP 서버에서 제공되는 큰 비디오 파일을 고려해 봅시다. 브라우저는 이 파일을 구현할 때 현재 프레임과 이후 프레임의 데이터만 버퍼링하고, 재생을 다시 시작하여 처음으로 돌아가는 것 외에는 탐색을 허용하지 않을 수 있습니다. 그러나 이것은 좋지 않은 구현입니다. 고품질의 구현은 충분한 저장 공간이 있는 경우 최근 몇 분(또는 더 많은) 콘텐츠를 버퍼링하여 사용자가 놀라운 부분을 다시 볼 수 있도록 하고, 필요한 경우 파일을 처음부터 다시 로드하여 임의의 탐색을 허용합니다. 이 경우 속도가 느리겠지만, 비디오를 처음부터 끝까지 다시 시청해야 하는 것보다 여전히 더 편리합니다.

미디어 리소스는 내부적으로 스크립팅되거나 인터랙티브할 수 있습니다. 따라서 미디어 요소는 비선형 방식으로 재생될 수 있습니다. 이 경우, 사용자 에이전트는 현재 재생 위치가 불연속적인 방식으로 변경될 때마다 (관련 이벤트가 발생하도록) 탐색 알고리즘이 사용된 것처럼 동작해야 합니다.

4.8.11.10 여러 미디어 트랙을 가진 미디어 리소스

미디어 리소스는 여러 개의 오디오 및 비디오 트랙을 포함할 수 있습니다. 예를 들어, 주요 비디오 및 오디오 트랙 외에도, 미디어 리소스에는 외국어 더빙 대사, 감독의 해설, 오디오 설명, 대체 각도 또는 수화 오버레이가 있을 수 있습니다.

media.audioTracks

HTMLMediaElement/audioTracks

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

AudioTrackList 객체를 반환하여 미디어 리소스에서 사용할 수 있는 오디오 트랙을 나타냅니다.

media.videoTracks

HTMLMediaElement/videoTracks

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

VideoTrackList 객체를 반환하여 미디어 리소스에서 사용할 수 있는 비디오 트랙을 나타냅니다.

미디어 요소audioTracks 속성은 미디어 요소미디어 리소스에서 사용할 수 있는 오디오 트랙을 나타내는 라이브 AudioTrackList 객체를 반환해야 합니다.

미디어 요소videoTracks 속성은 미디어 요소미디어 리소스에서 사용할 수 있는 비디오 트랙을 나타내는 라이브 VideoTrackList 객체를 반환해야 합니다.

미디어 요소에는 AudioTrackList 객체와 VideoTrackList 객체가 각각 하나씩만 존재하며, 다른 미디어 리소스가 요소에 로드되더라도 이 객체들은 재사용됩니다. (그러나 AudioTrackVideoTrack 객체는 그렇지 않습니다.)

4.8.11.10.1 AudioTrackListVideoTrackList 객체

AudioTrackList

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

VideoTrackList

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

AudioTrackList

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
caniuse.com 표

AudioTrackListVideoTrackList 인터페이스는 이전 섹션에서 정의된 속성에서 사용됩니다.

AudioTrack

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

VideoTrack

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안 됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=Window]
interface AudioTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter AudioTrack (unsigned long index);
  AudioTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

[Exposed=Window]
interface AudioTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean enabled;
};

[Exposed=Window]
interface VideoTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter VideoTrack (unsigned long index);
  VideoTrack? getTrackById(DOMString id);
  readonly attribute long selectedIndex;

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

[Exposed=Window]
interface VideoTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean selected;
};
media.audioTracks.length

AudioTrackList/length

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
media.videoTracks.length

VideoTrackList/length

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

리스트의 트랙 수를 반환합니다.

audioTrack = media.audioTracks[index]
videoTrack = media.videoTracks[index]

지정된 AudioTrack 또는 VideoTrack 객체를 반환합니다.

audioTrack = media.audioTracks.getTrackById(id)

AudioTrackList/getTrackById

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
videoTrack = media.videoTracks.getTrackById(id)

VideoTrackList/getTrackById

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

주어진 식별자를 가진 AudioTrack 또는 VideoTrack 객체를 반환하며, 해당 식별자를 가진 트랙이 없는 경우 null을 반환합니다.

audioTrack.id

AudioTrack/id

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
videoTrack.id

VideoTrack/id

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

주어진 트랙의 ID를 반환합니다. 이 ID는 형식이 프래그먼트를 지원하는 경우 사용할 수 있으며, 미디어 프래그먼트 구문과 함께 사용할 수 있으며, getTrackById() 메서드와 함께 사용할 수 있습니다.

audioTrack.kind

AudioTrack/kind

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
videoTrack.kind

VideoTrack/kind

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

주어진 트랙이 속하는 범주를 반환합니다. 가능한 트랙 범주는 아래에 나와 있습니다.

audioTrack.label

AudioTrack/label

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
videoTrack.label

VideoTrack/label

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지정된 트랙의 레이블을 반환합니다. 알려진 경우에만 반환되며, 그렇지 않으면 빈 문자열을 반환합니다.

audioTrack.language

AudioTrack/language

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
videoTrack.language

VideoTrack/language

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지정된 트랙의 언어를 반환합니다. 알려진 경우에만 반환되며, 그렇지 않으면 빈 문자열을 반환합니다.

audioTrack.enabled [ = value ]

AudioTrack/enabled

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지정된 트랙이 활성화된 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

트랙을 활성화할지 여부를 변경하기 위해 설정할 수 있습니다. 여러 오디오 트랙을 동시에 활성화하면 혼합됩니다.

media.videoTracks.selectedIndex

VideoTrackList/selectedIndex

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 선택된 트랙의 인덱스를 반환하며, 없으면 −1을 반환합니다.

videoTrack.selected [ = value ]

VideoTrack/selected

모든 현재 엔진에서 지원됩니다.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)아니요Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지정된 트랙이 활성화된 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

트랙을 선택할지 여부를 변경하기 위해 설정할 수 있습니다. 하나의 비디오 트랙이 선택됩니다. 이전 트랙을 선택 해제하고 새 트랙을 선택합니다.

AudioTrackList 객체는 하나 이상의 오디오 트랙으로 구성된 동적 목록을 나타내며, 이 중 하나 이상의 트랙이 동시에 활성화될 수 있습니다. 각 오디오 트랙은 AudioTrack 객체로 나타납니다.

VideoTrackList 객체는 하나 이상의 비디오 트랙으로 구성된 동적 목록을 나타내며, 이 중 하나의 트랙만 동시에 선택될 수 있습니다. 각 비디오 트랙은 VideoTrack 객체로 나타납니다.

AudioTrackListVideoTrackList 객체의 트랙들은 일관된 순서로 유지되어야 합니다. 미디어 리소스가 순서를 정의하는 형식인 경우 해당 순서가 사용되어야 하며, 그렇지 않으면 트랙이 미디어 리소스에 선언된 상대적 순서가 사용되어야 합니다. 사용된 순서는 목록의 자연 순서라고 합니다.

이 객체의 각 트랙에는 인덱스가 있으며, 첫 번째 트랙의 인덱스는 0이고 이후의 트랙은 이전 트랙보다 하나씩 더 높은 번호를 가집니다. 미디어 리소스가 동적으로 오디오 또는 비디오 트랙을 추가하거나 제거하면 트랙의 인덱스가 동적으로 변경됩니다. 미디어 리소스가 완전히 변경되면 모든 이전 트랙이 제거되고 새 트랙으로 대체됩니다.

AudioTrackListVideoTrackListlength 속성 게터는 조회 시점에 객체가 나타내는 트랙의 수를 반환해야 합니다.

AudioTrackListVideoTrackList 객체의 지원되는 속성 인덱스는 특정 시점에 해당 객체가 나타내는 트랙의 수에서 1을 뺀 숫자까지의 숫자입니다. 만약 트랙이 없다면 지원되는 속성 인덱스가 없습니다.

지정된 index에 대해 인덱스된 속성의 값을 결정하려면 AudioTrackList 또는 VideoTrackList 객체 list에서 해당 인덱스에 해당하는 AudioTrack 또는 VideoTrack 객체를 반환해야 합니다.

AudioTrackListVideoTrackListgetTrackById(id) 메서드는 지정된 인수와 일치하는 첫 번째 AudioTrack 또는 VideoTrack 객체를 반환해야 합니다. 일치하는 트랙이 없을 경우 메서드는 null을 반환해야 합니다.

AudioTrackVideoTrack 객체는 특정 미디어 리소스의 특정 트랙을 나타냅니다. 각 트랙에는 식별자, 범주, 레이블 및 언어가 있을 수 있습니다. 이러한 트랙의 속성들은 트랙의 생애 동안 유지되며, 트랙이 AudioTrackList 또는 VideoTrackList에서 제거되더라도 속성들은 변경되지 않습니다.

또한, 각 AudioTrack 객체는 활성화되거나 비활성화될 수 있으며, 이것이 오디오 트랙의 활성 상태입니다. AudioTrack이 생성될 때, 그 활성 상태는 false(비활성화)로 설정되어야 합니다. 리소스 가져오기 알고리즘이 이를 무시할 수 있습니다.

유사하게, VideoTrack 객체는 VideoTrackList 내에서 선택될 수 있으며, 이는 비디오 트랙의 선택 상태입니다. VideoTrack이 생성될 때, 그 선택 상태는 false(선택되지 않음)로 설정되어야 합니다. 리소스 가져오기 알고리즘이 이를 무시할 수 있습니다.

AudioTrackidVideoTrackid 속성은 해당 트랙의 식별자를 반환해야 하며, 식별자가 없는 경우 빈 문자열을 반환해야 합니다. 미디어 리소스가 미디어 조각 구문을 지원하는 형식일 경우, 특정 트랙에 대해 반환된 식별자는 해당 구문의 트랙 차원에서 트랙 이름으로 사용될 경우 트랙을 활성화할 수 있는 동일한 식별자가 되어야 합니다. [INBAND]

예를 들어, Ogg 파일에서는 이 식별자가 트랙의 Name 헤더 필드가 될 수 있습니다. [OGGSKELETONHEADERS]

AudioTrackkindVideoTrackkind 속성은 해당 트랙의 범주를 반환해야 하며, 범주가 없는 경우 빈 문자열을 반환해야 합니다.

트랙의 범주는 아래 표의 첫 번째 열에 있는 문자열 중 가장 적절한 것으로, 표의 두 번째 및 세 번째 열에 정의된 내용을 기준으로 합니다. 표의 세 번째 열에 있는 셀은 해당 범주가 어떤 항목에 적용되는지를 설명하며, 범주는 오디오 트랙에 대해 적절한 경우에만 오디오 트랙에 대해 반환되어야 하고, 비디오 트랙에 대해 적절한 경우에만 비디오 트랙에 대해 반환되어야 합니다.

Ogg 파일의 경우, 트랙의 Role 헤더 필드가 관련 메타데이터를 제공합니다. DASH 미디어 리소스의 경우, Role 요소가 정보를 전달합니다. WebM의 경우, 현재 FlagDefault 요소만이 값을 매핑합니다. 미디어 컨테이너에서 HTML로 인밴드 미디어 리소스 트랙 소싱에는 더 자세한 내용이 있습니다. [OGGSKELETONHEADERS] [DASH] [WEBMCG] [INBAND]

AudioTrackkindVideoTrackkind에 대한 반환 값
범주 정의 적용 대상... 예시
"alternative" 주 트랙의 대안으로 사용할 수 있는 트랙, 예: 다른 버전의 노래(오디오) 또는 다른 각도(비디오). 오디오 및 비디오. Ogg: "audio/alternate" 또는 "video/alternate"; DASH: "alternate" 역할, "main" 및 "commentary" 역할 없음, 오디오는 "dub" 역할 없음(다른 역할은 무시됨).
"captions" 캡션이 번인된 주 비디오 트랙의 버전. (레거시 콘텐츠의 경우, 새 콘텐츠는 텍스트 트랙 사용.) 비디오만. DASH: "caption" 및 "main" 역할 함께 사용(다른 역할 무시됨).
"descriptions" 비디오 트랙에 대한 오디오 설명. 오디오만. Ogg: "audio/audiodesc".
"main" 주 오디오 또는 비디오 트랙. 오디오 및 비디오. Ogg: "audio/main" 또는 "video/main"; WebM: "FlagDefault" 요소 설정됨; DASH: "main" 역할, "caption", "subtitle", "dub" 역할 없음(다른 역할은 무시됨).
"main-desc" 오디오 설명이 혼합된 주 오디오 트랙. 오디오만. MPEG-2 TS의 AC3 오디오: bsmod=2 및 full_svc=1.
"sign" 오디오 트랙의 수화 통역. 비디오만. Ogg: "video/sign".
"subtitles" 자막이 번인된 주 비디오 트랙의 버전. (레거시 콘텐츠의 경우, 새 콘텐츠는 텍스트 트랙 사용.) 비디오만. DASH: "subtitle" 및 "main" 역할 함께 사용(다른 역할 무시됨).
"translation" 주 오디오 트랙의 번역된 버전. 오디오만. Ogg: "audio/dub". DASH: "dub" 및 "main" 역할 함께 사용(다른 역할 무시됨).
"commentary" 주 오디오 또는 비디오 트랙에 대한 해설, 예: 감독의 해설. 오디오 및 비디오. DASH: "commentary" 역할, "main" 역할 없음(다른 역할 무시됨).
"" (빈 문자열) 명시된 유형이 없거나 트랙의 메타데이터에 의해 제공된 유형이 사용자 에이전트에 의해 인식되지 않음. 오디오 및 비디오.

AudioTracklabelVideoTracklabel 속성은 해당 트랙의 레이블을 반환해야 하며, 레이블이 없는 경우 빈 문자열을 반환해야 합니다. [INBAND]

AudioTracklanguageVideoTracklanguage 속성은 해당 트랙의 언어를 나타내는 BCP 47 언어 태그를 반환해야 하며, 언어가 없는 경우 빈 문자열을 반환해야 합니다. 사용자가 해당 언어를 BCP 47 언어 태그로 표현할 수 없는 경우(예를 들어, 미디어 리소스의 형식에서 언어 정보가 정의되지 않은 자유 형식 문자열인 경우) 메서드는 트랙에 언어가 없는 것처럼 빈 문자열을 반환해야 합니다. [INBAND]

AudioTrackenabled 속성은 조회 시 트랙이 현재 활성화되어 있으면 true를, 그렇지 않으면 false를 반환해야 합니다. 설정 시, 새로운 값이 true인 경우 트랙을 활성화하고, 그렇지 않으면 트랙을 비활성화해야 합니다. (트랙이 더 이상 AudioTrackList 객체에 포함되어 있지 않다면, 트랙이 활성화되거나 비활성화되는 것이 AudioTrack 객체의 속성 값을 변경하는 것 이외에는 아무런 영향을 미치지 않습니다.)

AudioTrackList에 있는 오디오 트랙이 비활성화되었다가 다시 활성화될 때마다, 또는 활성화된 트랙이 비활성화될 때마다, 사용자 에이전트는 미디어 요소 작업을 대기열에 추가하고, 미디어 요소에서 이벤트change라는 이름으로 AudioTrackList 객체에서 실행해야 합니다.

특정 위치에 대한 데이터가 없거나 해당 위치에 존재하지 않는 오디오 트랙은 타임라인의 해당 지점에서 무음으로 해석되어야 합니다.

VideoTrackListselectedIndex 속성은 현재 선택된 트랙의 인덱스를 반환해야 합니다. 만약 VideoTrackList 객체가 현재 트랙을 나타내지 않거나, 선택된 트랙이 없다면, −1을 반환해야 합니다.

VideoTrackselected 속성은 조회 시 트랙이 현재 선택된 경우 true를, 그렇지 않은 경우 false를 반환해야 합니다. 설정 시, 새로운 값이 true인 경우 트랙을 선택하고, 그렇지 않으면 선택을 해제해야 합니다. VideoTrackList에 트랙이 포함된 경우, 목록의 다른 VideoTrack 객체들은 선택 해제되어야 합니다. (트랙이 더 이상 VideoTrackList 객체에 포함되어 있지 않다면, 트랙이 선택되거나 해제되는 것이 VideoTrack 객체의 속성 값을 변경하는 것 이외에는 아무런 영향을 미치지 않습니다.)

VideoTrackList의 선택되지 않은 트랙이 선택되거나, 선택된 트랙이 선택 해제될 때마다, 사용자 에이전트는 미디어 요소 작업을 대기열에 추가하고, 미디어 요소에서 이벤트change라는 이름으로 VideoTrackList 객체에서 실행해야 합니다. 이 작업resize 이벤트를 실행하는 작업보다 먼저 대기열에 추가되어야 합니다.

특정 위치에 대한 데이터가 없거나 해당 위치에 존재하지 않는 비디오 트랙은 타임라인의 해당 지점에서 투명한 검정으로 해석되어야 하며, 해당 지점 이전의 마지막 프레임과 동일한 크기를 가져야 합니다. 또는 해당 위치가 해당 트랙의 모든 데이터 이전이라면 해당 트랙의 첫 번째 프레임과 동일한 크기를 가져야 합니다. 해당 위치에 전혀 존재하지 않는 트랙은 존재하지만 데이터가 없는 것으로 취급되어야 합니다.

예를 들어, 비디오에 한 시간이 지난 후에만 소개되는 트랙이 있는 경우, 사용자가 해당 트랙을 선택한 후 처음으로 돌아가면, 사용자 에이전트는 해당 트랙이 미디어 리소스의 시작 시점에서 시작되었지만 한 시간까지는 투명했다고 간주할 것입니다.


다음은 이벤트 핸들러와 해당 이벤트 핸들러 이벤트 타입입니다. 모든 AudioTrackListVideoTrackList 인터페이스를 구현하는 객체에서 이벤트 핸들러 IDL 속성으로 지원되어야 합니다:

이벤트 핸들러 이벤트 핸들러 이벤트 타입
onchange

AudioTrackList/change_event

모든 최신 엔진에서 지원됩니다.

Firefox🔰 33+ Safari7+ Chrome🔰 37+
Opera? Edge🔰 79+
Edge (Legacy)No Internet Explorer10+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?
change
onaddtrack

AudioTrackList/addtrack_event

모든 최신 엔진에서 지원됩니다.

Firefox🔰 33+ Safari7+ Chrome🔰 37+
Opera? Edge🔰 79+
Edge (Legacy)No Internet Explorer10+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?
addtrack
onremovetrack

AudioTrackList/removetrack_event

모든 최신 엔진에서 지원됩니다.

Firefox🔰 33+ Safari7+ Chrome🔰 37+
Opera? Edge🔰 79+
Edge (Legacy)No Internet Explorer10+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?
removetrack
4.8.11.10.2 특정 오디오 및 비디오 트랙을 선언적으로 선택

audioTracksvideoTracks 속성은 스크립트로 어떤 트랙을 재생할지 선택할 수 있게 하지만, 또한 프래그먼트에 특정 트랙을 지정하여 선언적으로 트랙을 선택하는 것도 가능합니다. 이러한 프래그먼트의 형식은 MIME 타입에 따라 달라집니다. [RFC2046] [URL]

이 예제에서는 미디어 프래그먼트 구문을 지원하는 형식을 사용하는 비디오를 임베드하여 기본 비디오 트랙 대신 "Alternative"로 레이블된 대체 각도가 활성화되도록 합니다.

<video src="myvideo#track=Alternative"></video>
4.8.11.11 시간에 맞춰 표시되는 텍스트 트랙
4.8.11.11.1 텍스트 트랙 모델

미디어 요소에는 텍스트 트랙의 그룹이 있을 수 있으며, 이를 미디어 요소텍스트 트랙 목록이라고 합니다. 텍스트 트랙은 다음과 같이 정렬됩니다:

  1. 텍스트 트랙track 요소 자식 요소에 해당하는 트랙은 트리 순서대로 정렬됩니다.

  2. addTextTrack() 메서드를 사용해 추가된 텍스트 트랙은 추가된 순서대로, 가장 오래된 것부터 정렬됩니다.

  3. 미디어 리소스에 특정한 텍스트 트랙 (텍스트 트랙미디어 리소스에 해당하는 트랙)은 미디어 리소스의 형식 사양에 따라 정렬됩니다.

텍스트 트랙은 다음으로 구성됩니다:

텍스트 트랙의 종류

이는 트랙이 사용자 에이전트에 의해 어떻게 처리되는지를 결정합니다. 종류는 문자열로 표현되며, 가능한 문자열은 다음과 같습니다:

트랙의 종류텍스트 트랙track 요소에 해당하는 경우 동적으로 변경될 수 있습니다.

라벨

이는 사용자를 위한 사람이 읽을 수 있는 문자열로, 트랙을 식별하는 데 사용됩니다.

트랙의 라벨텍스트 트랙track 요소에 해당하는 경우 동적으로 변경될 수 있습니다.

텍스트 트랙의 라벨이 빈 문자열일 경우, 사용자 에이전트는 사용자 인터페이스에서 사용할 수 있는 적절한 라벨을 텍스트 트랙의 다른 속성(예: 텍스트 트랙의 종류 및 텍스트 트랙의 언어)으로부터 자동으로 생성해야 합니다. 이 자동 생성된 라벨은 API에서 노출되지 않습니다.

인밴드 메타데이터 트랙 디스패치 유형

이것은 인밴드 메타데이터 트랙을 특정 스크립트에 디스패치할 수 있도록 하기 위해 미디어 리소스에서 추출된 문자열입니다.

예를 들어, 웹에서 스트리밍되는 전통적인 TV 방송에 웹 전용 인터랙티브 기능이 추가된 경우, 광고 타겟팅을 위한 메타데이터, 게임쇼 중의 퀴즈 데이터, 스포츠 경기 중의 선수 상태, 요리 프로그램 중의 레시피 정보 등과 같은 텍스트 트랙이 포함될 수 있습니다. 각 프로그램이 시작되고 끝날 때마다 새로운 트랙이 스트림에 추가되거나 제거될 수 있으며, 각 트랙이 추가될 때마다 사용자 에이전트는 이 속성의 값을 사용하여 이를 전용 스크립트 모듈에 바인딩할 수 있습니다.

인밴드 메타데이터 텍스트 트랙 외의 경우, 인밴드 메타데이터 트랙 디스패치 유형은 빈 문자열입니다. 이 값이 다양한 미디어 형식에 대해 어떻게 채워지는지는 미디어 리소스에 특정한 텍스트 트랙을 노출하는 단계에서 설명됩니다.

언어

이것은 텍스트 트랙의 큐에 사용되는 언어를 나타내는 문자열(BCP 47 언어 태그)입니다. [BCP47]

텍스트 트랙의 언어텍스트 트랙track 요소에 해당하는 경우 동적으로 변경될 수 있습니다.

준비 상태

다음 중 하나입니다:

로딩되지 않음

텍스트 트랙의 큐가 아직 얻어지지 않았음을 나타냅니다.

로딩 중

텍스트 트랙이 로딩 중이며, 현재까지 치명적인 오류가 발생하지 않았음을 나타냅니다. 더 많은 큐가 파서에 의해 트랙에 추가될 수 있습니다.

로딩 완료

텍스트 트랙이 치명적인 오류 없이 로딩되었음을 나타냅니다.

로딩 실패

텍스트 트랙이 활성화되었으나, 사용자 에이전트가 이를 얻으려고 시도할 때 어떤 방식으로든 실패했음을 나타냅니다(예: URL파싱할 수 없음, 네트워크 오류, 알 수 없는 텍스트 트랙 형식). 일부 또는 모든 큐가 누락되었으며 더 이상 얻어지지 않을 가능성이 큽니다.

텍스트 트랙의 준비 상태는 트랙이 얻어지면서 동적으로 변경됩니다.

모드

다음 중 하나입니다:

비활성화됨

텍스트 트랙이 활성 상태가 아님을 나타냅니다. DOM에 트랙을 노출하는 목적 외에는 사용자 에이전트가 텍스트 트랙을 무시합니다. 큐가 활성화되지 않고, 이벤트가 발생하지 않으며, 사용자 에이전트는 트랙의 큐를 얻으려 시도하지 않습니다.

숨김

텍스트 트랙이 활성화되었으나, 사용자 에이전트가 큐를 적극적으로 표시하지 않음을 나타냅니다. 트랙의 큐를 얻기 위한 시도가 아직 이루어지지 않은 경우, 사용자 에이전트는 곧 그러한 시도를 할 것입니다. 사용자 에이전트는 활성화된 큐 목록을 유지하고 있으며, 이에 따라 이벤트가 발생합니다.

표시 중

텍스트 트랙이 활성화되었음을 나타냅니다. 트랙의 큐를 얻기 위한 시도가 아직 이루어지지 않은 경우, 사용자 에이전트는 곧 그러한 시도를 할 것입니다. 사용자 에이전트는 활성화된 큐 목록을 유지하고 있으며, 이에 따라 이벤트가 발생합니다. 또한, 종류subtitles 또는 captions인 텍스트 트랙의 경우, 큐가 적절히 비디오에 오버레이됩니다. 종류descriptions인 텍스트 트랙의 경우, 사용자 에이전트는 큐를 비시각적인 방식으로 사용자에게 제공합니다. 종류chapters인 텍스트 트랙의 경우, 사용자 에이전트는 사용자가 큐를 선택하여 미디어 리소스의 임의의 지점으로 이동할 수 있는 메커니즘을 제공합니다.

큐 목록

텍스트 트랙 큐 목록과 텍스트 트랙 렌더링을 업데이트하기 위한 규칙으로 구성됩니다. 예를 들어, WebVTT의 경우, WebVTT 텍스트 트랙의 디스플레이를 업데이트하는 규칙이 있습니다. [WEBVTT]

텍스트 트랙의 큐 목록은 동적으로 변경될 수 있습니다. 이는 텍스트 트랙아직 로딩되지 않았거나 로딩 중이기 때문이거나, DOM 조작으로 인해 발생할 수 있습니다.

텍스트 트랙에는 해당하는 TextTrack 객체가 있습니다.


미디어 요소는 초기에는 비어 있는 보류 중인 텍스트 트랙 목록, 초기 값이 false인 파서에 의해 차단됨 플래그, 초기 값이 false인 자동 트랙 선택 수행 여부 플래그를 가집니다.

사용자 에이전트가 보류 중인 텍스트 트랙 목록을 채워야 할 때, 사용자 에이전트는 해당 미디어 요소보류 중인 텍스트 트랙 목록에 요소의 텍스트 트랙 목록에 있는 각 텍스트 트랙을 추가해야 합니다. 단, 이 텍스트 트랙 모드비활성화됨이 아니고, 텍스트 트랙 준비 상태로딩 중인 경우에 한합니다.

track 요소의 부모 노드가 변경될 때마다, 사용자 에이전트는 해당하는 텍스트 트랙을 포함하는 모든 보류 중인 텍스트 트랙 목록에서 제거해야 합니다.

텍스트 트랙텍스트 트랙 준비 상태로딩 완료 또는 로딩 실패로 변경될 때마다, 사용자 에이전트는 해당 트랙을 포함하는 모든 보류 중인 텍스트 트랙 목록에서 해당 트랙을 제거해야 합니다.

미디어 요소HTML 파서 또는 XML 파서에 의해 생성될 때, 사용자 에이전트는 해당 요소의 파서에 의해 차단됨 플래그를 true로 설정해야 합니다. 미디어 요소열려 있는 요소 스택에서 팝핑될 때, 사용자 에이전트는 자동 텍스트 트랙 선택에 대한 사용자 기본 설정을 존중, 보류 중인 텍스트 트랙 목록을 채우고 요소의 파서에 의해 차단됨 플래그를 false로 설정해야 합니다.

텍스트 트랙미디어 요소준비됨 상태로 있으려면, 해당 요소의 보류 중인 텍스트 트랙 목록이 비어 있고 요소의 파서에 의해 차단됨 플래그가 false여야 합니다.

미디어 요소에는 보류 중인 텍스트 트랙 변경 알림 플래그가 있으며, 이는 초기에는 설정되지 않아야 합니다.

미디어 요소텍스트 트랙 목록에 있는 텍스트 트랙텍스트 트랙 모드가 변경될 때마다, 사용자 에이전트는 해당 미디어 요소에 대해 다음 단계를 실행해야 합니다:

  1. 미디어 요소보류 중인 텍스트 트랙 변경 알림 플래그가 설정된 경우, 반환합니다.

  2. 미디어 요소보류 중인 텍스트 트랙 변경 알림 플래그를 설정합니다.

  3. 미디어 요소 작업을 대기열에 추가하여 미디어 요소에서 이 단계를 실행합니다:

    1. 미디어 요소보류 중인 텍스트 트랙 변경 알림 플래그를 해제합니다.

    2. 이벤트를 발생시켜, 미디어 요소textTracks 속성의 TextTrackList 객체에서 change라는 이름의 이벤트를 발생시킵니다.

  4. 미디어 요소포스터 표시 플래그가 설정되지 않은 경우, 시간은 흘러갑니다 단계를 실행합니다.

이 섹션에 나열된 작업작업의 작업 소스는 DOM 조작 작업 소스입니다.


텍스트 트랙 큐텍스트 트랙에서 시간에 민감한 데이터를 나타내는 단위로, 자막 및 캡션의 경우 특정 시간에 나타났다 다른 시간에 사라지는 텍스트와 해당됩니다.

텍스트 트랙 큐는 다음으로 구성됩니다:

식별자

임의의 문자열입니다.

시작 시간

큐가 적용되는 미디어 데이터 범위의 시작을 나타내는 시간으로, 초와 소수점 이하의 초 단위로 표시됩니다.

종료 시간

큐가 적용되는 미디어 데이터 범위의 끝을 나타내는 시간으로, 초와 소수점 이하의 초 단위로 표시되거나, 무한 텍스트 트랙 큐의 경우 양의 무한대로 설정됩니다.

종료 시 일시정지 플래그

큐가 적용되는 범위의 끝에 도달할 때 미디어 리소스의 재생이 일시정지할지 여부를 나타내는 부울 값입니다.

추가적인 형식별 데이터

형식에 필요한 추가 필드, 예를 들어 WebVTT의 경우 텍스트 트랙 큐 작성 방향 등이 포함됩니다. [WEBVTT]

무한 텍스트 트랙 큐는 종료 시간이 양의 무한대로 설정된 텍스트 트랙 큐입니다. 활성 상태의 무한 텍스트 트랙 큐는 정상적인 재생 중에 현재 재생 위치의 단조 증가를 통해 비활성화될 수 없습니다(예: 종료 시간이 명시되지 않은 라이브 이벤트의 챕터에 대한 메타데이터 큐).

텍스트 트랙 큐의 시작 시간텍스트 트랙 큐의 종료 시간은 음수가 될 수 있습니다(단, 현재 재생 위치는 음수가 될 수 없으므로, 시간 0 이전에 완전히 있는 큐는 활성화될 수 없습니다).

텍스트 트랙 큐는 해당하는 TextTrackCue 객체(또는 더 구체적으로는 TextTrackCue에서 상속된 객체, 예를 들어 WebVTT 큐의 경우 VTTCue 인터페이스를 사용함)가 있습니다. 텍스트 트랙 큐의 메모리 내 표현은 이 TextTrackCue API를 통해 동적으로 변경될 수 있습니다. [WEBVTT]

텍스트 트랙 큐는 특정 텍스트 트랙 큐 유형에 대한 사양에서 정의된 텍스트 트랙 렌더링을 업데이트하기 위한 규칙과 연관됩니다. 이 규칙은 객체를 TextTrack 객체에 addCue() 메서드를 사용하여 추가할 때 사용됩니다.

또한, 각 텍스트 트랙 큐에는 두 가지 동적 정보가 있습니다:

활성 플래그

이 플래그는 초기에는 설정되지 않아야 합니다. 이 플래그는 큐가 활성화되거나 비활성화될 때 적절하게 이벤트가 발생하도록 하고, 올바른 큐가 렌더링되도록 보장하기 위해 사용됩니다.

사용자 에이전트는 텍스트 트랙 큐텍스트 트랙텍스트 트랙 큐 목록에서 제거될 때마다, 텍스트 트랙 자체가 미디어 요소텍스트 트랙 목록에서 제거되거나, 텍스트 트랙 모드비활성화됨으로 변경될 때마다, 미디어 요소readyState가 다시 HAVE_NOTHING으로 변경될 때마다 이 플래그를 동기적으로 해제해야 합니다. 큐가 이러한 방식으로 비활성화되는 경우, 사용자 에이전트는 영향을 받은 모든 큐의 플래그를 해제한 후, 해당 텍스트 트랙텍스트 트랙 렌더링을 업데이트하기 위한 규칙을 적용해야 합니다. 예를 들어, WebVTT 기반 텍스트 트랙의 경우, WebVTT 텍스트 트랙의 표시를 업데이트하기 위한 규칙을 따릅니다. [WEBVTT]

표시 상태

이 상태는 렌더링 모델의 일부로, 큐를 일관된 위치에 유지하기 위해 사용됩니다. 초기에는 비어 있어야 합니다. 텍스트 트랙 큐 활성 플래그가 해제될 때마다, 사용자 에이전트는 텍스트 트랙 큐 표시 상태를 비워야 합니다.

텍스트 트랙 큐미디어 요소텍스트 트랙 내에서 텍스트 트랙 큐 순서에 따라 서로 정렬됩니다. 이 순서는 다음과 같이 결정됩니다: 먼저 를 해당 텍스트 트랙별로 그룹화하고, 그룹은 미디어 요소텍스트 트랙 목록에 나타나는 순서대로 정렬됩니다. 그런 다음, 각 그룹 내에서 시작 시간을 기준으로 가장 이른 것부터 정렬됩니다. 동일한 시작 시간을 가진 종료 시간을 기준으로 가장 늦은 것부터 정렬됩니다. 마지막으로 동일한 종료 시간을 가진 는 각각의 텍스트 트랙 큐 목록에 마지막으로 추가된 순서대로 정렬되며, 가장 오래된 것이 먼저 옵니다. 예를 들어, WebVTT 파일의 경우, 초기에는 큐가 파일에 나열된 순서로 정렬됩니다. [WEBVTT]

4.8.11.11.2 인밴드 텍스트 트랙 소싱

미디어 리소스별 텍스트 트랙텍스트 트랙으로, 미디어 리소스에서 발견된 데이터에 해당합니다.

이러한 데이터의 처리 및 렌더링 규칙은 관련 사양에 정의되어 있습니다. 예를 들어, 미디어 리소스가 비디오인 경우 해당 비디오 포맷의 사양에 정의됩니다. 일부 레거시 포맷에 대한 세부 정보는 미디어 컨테이너에서 HTML로 인밴드 미디어 리소스 트랙 소싱에서 찾을 수 있습니다. [INBAND]

사용자 에이전트가 미디어 리소스에 포함된 데이터를 텍스트 트랙과 동등한 것으로 인식하고 지원하는 경우, 사용자 에이전트는 다음과 같이 관련 데이터로 미디어 리소스별 텍스트 트랙 노출 단계를 실행합니다.

  1. 해당 데이터를 새로운 텍스트 트랙과 그에 해당하는 새로운 TextTrack 객체에 연결합니다. 이 텍스트 트랙미디어 리소스별 텍스트 트랙입니다.

  2. 새로운 텍스트 트랙종류, 라벨, 그리고 언어를 관련 사양에서 정의된 데이터의 의미에 따라 설정합니다. 데이터에 라벨이 없는 경우, 라벨은 빈 문자열로 설정해야 합니다.

  3. 새로운 텍스트 트랙 큐 목록을 해당 포맷에 적합한 텍스트 트랙 렌더링 업데이트 규칙에 따라 연결합니다.

  4. 새로운 텍스트 트랙종류chapters 또는 metadata인 경우, 텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입을 미디어 리소스의 종류에 따라 다음과 같이 설정합니다:

    만약 미디어 리소스가 Ogg 파일이라면
    텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입은 Name 헤더 필드의 값으로 설정해야 합니다. [OGGSKELETONHEADERS]
    만약 미디어 리소스가 WebM 파일이라면
    텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입은 CodecID 요소의 값으로 설정해야 합니다. [WEBMCG]
    만약 미디어 리소스가 MPEG-2 파일이라면
    stream type을 파일의 프로그램 맵 섹션에서 텍스트 트랙 유형을 설명하는 "stream_type" 필드의 값으로 설정합니다. 이 값을 8비트 부호 없는 정수로 해석합니다. length를 동일한 프로그램 맵 섹션에서 트랙에 대한 "ES_info_length" 필드의 값으로 설정합니다. 이 값을 움직이는 그림과 관련된 오디오 정보의 일반 코딩에서 정의한 정수로 해석합니다. descriptor bytes를 "ES_info_length" 필드 뒤의 length 바이트로 설정합니다. 텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입stream type 바이트와 0개 이상의 descriptor bytes 바이트를 16진수로 연결하여 설정합니다. [MPEG2]
    만약 미디어 리소스가 MPEG-4 파일이라면
    파일의 첫 번째 stsd 박스가 stsd 박스입니다. 파일에 stsd 박스가 없거나 stsd 박스mett 또는 metx 박스가 없으면, 텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입은 빈 문자열로 설정해야 합니다. stsd 박스mett 박스가 있는 경우, 텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입은 문자열 "mett", U+0020 SPACE 문자 및 mett 박스의 첫 번째 mime_format 필드의 값을 연결하여 설정해야 합니다. stsd 박스mett 박스는 없고 metx 박스가 있는 경우, 텍스트 트랙 인밴드 메타데이터 트랙 디스패치 타입은 문자열 "metx", U+0020 SPACE 문자 및 metx 박스의 첫 번째 namespace 필드의 값을 연결하여 설정해야 합니다. [MPEG4]
  5. 지금까지 구문 분석된 큐로 새로운 텍스트 트랙텍스트 트랙 큐 목록을 채우고, 필요한 경우 동적으로 업데이트를 시작합니다.

  6. 새로운 텍스트 트랙준비 상태로드됨으로 설정합니다.

  7. 새로운 텍스트 트랙모드를 사용자의 선호와 데이터에 대한 관련 사양의 요구 사항에 일치하도록 설정합니다.

    예를 들어, 다른 활성 자막이 없고 이것이 강제 자막 트랙인 경우(오디오 트랙의 주요 언어로 된 자막을 제공하지만 실제로는 다른 언어로 된 오디오에 대해서만 자막을 제공하는 자막 트랙), 이러한 자막이 여기에 활성화될 수 있습니다.

  8. 새로운 텍스트 트랙미디어 요소텍스트 트랙 목록에 추가합니다.

  9. 이벤트addtrack으로 미디어 요소textTracks 속성의 TextTrackList 객체에서 사용하여 발생시킵니다. TrackEvent로, track 속성은 텍스트 트랙TextTrack 객체로 초기화됩니다.

4.8.11.11.3 밴드 외 텍스트 트랙 소싱

track 요소가 생성될 때, 그것은 새로운 텍스트 트랙 (그 값은 아래 정의된 대로 설정됨) 및 해당하는 새로운 TextTrack 객체와 연관되어야 합니다.

텍스트 트랙 종류는 요소의 kind 속성의 상태에 따라 다음 표에서 결정됩니다. 첫 번째 열의 상태에 따라 종류는 두 번째 열에 주어진 문자열이 됩니다:

상태 문자열
Subtitles subtitles
Captions captions
Descriptions descriptions
Chapters metadata chapters
Metadata metadata

텍스트 트랙 라벨은 요소의 트랙 라벨입니다.

텍스트 트랙 언어는 요소의 트랙 언어이며, 없을 경우 빈 문자열로 설정됩니다.

kind, label, 및 srclang 속성이 설정, 변경, 또는 제거될 때마다 텍스트 트랙은 위에서 정의한 대로 업데이트되어야 합니다.

트랙 URL 변경은 아래의 알고리즘에서 처리됩니다.

텍스트 트랙 준비 상태는 처음에는 로드되지 않음으로 설정되며, 텍스트 트랙 모드는 처음에는 비활성화됨으로 설정됩니다.

텍스트 트랙 큐 목록은 처음에는 비어 있으며, 참조된 파일이 구문 분석될 때 동적으로 수정됩니다. 이 목록과 관련된 규칙은 해당 포맷에 적합한 텍스트 트랙 렌더링 업데이트 규칙입니다; WebVTT의 경우, 이는 WebVTT 텍스트 트랙 디스플레이 업데이트 규칙입니다. [WEBVTT]

track 요소의 상위 요소가 변경되고 새로운 상위 요소가 미디어 요소인 경우, 사용자 에이전트는 track 요소의 해당 텍스트 트랙미디어 요소텍스트 트랙 목록에 추가한 후, 미디어 요소 작업을 큐에 추가하여, 이벤트addtrack 이름으로 미디어 요소textTracks 속성의 TextTrackList 객체에서 발생시킵니다. 이때 TrackEvent를 사용하며, track 속성은 텍스트 트랙TextTrack 객체로 초기화됩니다.

track 요소의 상위 요소가 변경되고 이전 상위 요소가 미디어 요소였던 경우, 사용자 에이전트는 track 요소의 해당 텍스트 트랙미디어 요소텍스트 트랙 목록에서 제거한 후, 미디어 요소 작업을 큐에 추가하여, 이벤트removetrack 이름으로 미디어 요소textTracks 속성의 TextTrackList 객체에서 발생시킵니다. 이때 TrackEvent를 사용하며, track 속성은 텍스트 트랙TextTrack 객체로 초기화됩니다.


텍스트 트랙 요소에 해당하는 텍스트 트랙미디어 요소텍스트 트랙 목록에 추가되면, 사용자 에이전트는 미디어 요소 작업을 큐에 추가하여 미디어 요소에 대해 다음 단계를 실행해야 합니다:

  1. 요소의 파서에 의해 차단됨 플래그가 true인 경우, 반환하십시오.

  2. 요소의 자동 트랙 선택 수행 플래그가 true인 경우, 반환하십시오.

  3. 이 요소에 대해 자동 텍스트 트랙 선택에 대한 사용자 기본 설정 준수를 수행하십시오.

사용자 에이전트가 미디어 요소에 대해 자동 텍스트 트랙 선택에 대한 사용자 기본 설정 준수를 수행해야 하는 경우, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. 자동 텍스트 트랙 선택자막캡션에 대해 수행하십시오.

  2. 자동 텍스트 트랙 선택설명에 대해 수행하십시오.

  3. 만약 미디어 요소텍스트 트랙 목록텍스트 트랙이 있고, 그 텍스트 트랙 종류 또는 메타데이터에 해당하는 트랙 요소와 연결된 경우, 기본값 속성이 설정되어 있으며 텍스트 트랙 모드비활성화됨으로 설정된 모든 트랙의 텍스트 트랙 모드숨김으로 설정하십시오.

  4. 요소의 자동 트랙 선택 수행 플래그를 true로 설정하십시오.

위의 단계에서 한 가지 이상의 텍스트 트랙 종류에 대해 자동 텍스트 트랙 선택 수행을 지시하는 경우, 다음 단계를 실행해야 합니다:

  1. candidates미디어 요소텍스트 트랙 목록에 있는 텍스트 트랙으로 구성된 목록이며, 해당 목록의 텍스트 트랙 종류는 알고리즘에 전달된 종류 중 하나로 설정되어야 합니다. (해당 목록의 순서는 텍스트 트랙 목록에 주어진 순서대로 설정됩니다.)

  2. candidates가 비어 있는 경우, 반환하십시오.

  3. candidates에 있는 텍스트 트랙 중 하나라도 텍스트 트랙 모드표시됨으로 설정된 경우, 반환하십시오.

  4. 사용자가 candidates에서 텍스트 트랙 종류, 텍스트 트랙 언어, 또는 텍스트 트랙 라벨에 기반하여 트랙을 활성화하려는 의사를 표시한 경우, 해당 트랙의 텍스트 트랙 모드표시됨으로 설정하십시오.

    예를 들어, 사용자가 "가능할 때마다 프랑스어 자막을 원합니다" 또는 "제목에 '해설'이 포함된 자막 트랙이 있으면 활성화하십시오", 또는 "오디오 설명 트랙이 있으면 하나를 활성화하십시오, 가능하면 스위스 독일어로, 그렇지 않으면 표준 스위스 독일어나 표준 독일어로"와 같은 브라우저 기본 설정을 설정했을 수 있습니다.

    그렇지 않은 경우, candidates트랙 요소와 연결된 텍스트 트랙이 있는 경우, 그 기본값 속성이 설정되어 있고 텍스트 트랙 모드비활성화됨으로 설정된 첫 번째 트랙의 텍스트 트랙 모드표시됨으로 설정하십시오.

텍스트 트랙 요소에 해당하는 텍스트 트랙이 다음 상황 중 하나를 겪을 때, 사용자 에이전트는 해당 텍스트 트랙트랙 요소에 대해 트랙 처리 모델을 시작해야 합니다:

사용자 에이전트가 텍스트 트랙과 그 트랙 요소에 대해 트랙 처리 모델을 시작해야 할 때, 다음 알고리즘을 실행해야 합니다. 이 알고리즘은 이벤트 루프 메커니즘과 밀접하게 연관되어 있으며, 특히 동기 섹션이 포함됩니다. (이 섹션은 이벤트 루프 알고리즘의 일부로 트리거됩니다.) 이 섹션의 단계는 ⌛로 표시됩니다.

  1. 이 알고리즘의 다른 인스턴스가 이미 이 텍스트 트랙과 그 트랙 요소에 대해 실행 중인 경우, 반환하고 해당 알고리즘이 이 요소를 처리하도록 합니다.

  2. 만약 텍스트 트랙텍스트 트랙 모드숨김 또는 표시됨으로 설정되지 않은 경우, 반환하십시오.

  3. 만약 텍스트 트랙트랙 요소가 부모로 미디어 요소를 가지고 있지 않은 경우, 반환하십시오.

  4. 나머지 단계를 병렬로 실행하여, 이러한 단계를 실행하게 만든 원인이 계속될 수 있도록 합니다.

  5. Top: 안정적인 상태를 기다립니다. 동기 섹션은 다음 단계로 구성됩니다. (이 섹션의 단계는 ⌛로 표시됩니다.)

  6. 텍스트 트랙 준비 상태로드 중으로 설정하십시오.

  7. URL트랙 URL로 설정하십시오.

  8. ⌛ 만약 트랙 요소의 부모가 미디어 요소인 경우, corsAttributeState를 부모 미디어 요소crossorigin 콘텐츠 속성의 상태로 설정하십시오. 그렇지 않은 경우, corsAttributeState아무 CORS도 없음으로 설정하십시오.

  9. 동기 섹션을 종료하고, 나머지 단계를 병렬로 계속하십시오.

  10. URL이 빈 문자열이 아닌 경우:

    1. URL, "track", 및 corsAttributeState를 주어진 값으로 하여 잠재적인 CORS 요청을 생성하고, same-origin fallback flag를 설정하십시오.

    2. request클라이언트트랙 요소의 노드 문서관련 설정 객체로 설정하십시오.

    3. request시작자 유형을 "track"로 설정하십시오.

    4. Fetch request.

    데이터가 페치되면서 처리하도록 작업큐에 추가한 후, 리소스 유형을 결정해야 합니다. 만약 리소스 유형이 지원되지 않는 텍스트 트랙 형식이라면 로드는 실패할 것이며, 이는 아래에 설명된 대로입니다. 그렇지 않으면 리소스 데이터는 WebVTT 파서와 같은 적절한 파서로 전달되어야 하며, 이 데이터는 수신된 대로 텍스트 트랙 큐 목록을 사용하여 파싱됩니다. [WEBVTT]

    적절한 파서는 이러한 네트워킹 작업 소스에서 작업이 실행될 때마다 수신된 데이터로 텍스트 트랙 큐 목록을 점진적으로 업데이트합니다.

    이 명세는 현재 텍스트 트랙의 MIME 유형을 확인하는 방법이나 실제 파일 데이터를 사용하여 파일 형식 감지(sniffing)를 수행하는 방법에 대해 명시하지 않습니다. 구현자들은 이 문제에 대해 서로 다른 의도를 가지고 있으며, 따라서 올바른 해결책이 무엇인지 불분명합니다. 이와 관련한 요구 사항이 없는 경우, HTTP 명세서의 엄격한 요구 사항이 우선됩니다("Content-Type은 기본 데이터의 미디어 유형을 지정합니다."... "미디어 유형이 Content-Type 필드에 의해 주어지지 않은 경우에만, 수신자는 리소스의 내용 및/또는 리소스를 식별하는 데 사용된 URI의 이름 확장자 등을 검사하여 미디어 유형을 추측할 수 있습니다.").

    만약 어떤 이유로든 페치가 실패하면(네트워크 오류, 서버에서 오류 코드 반환, CORS 실패 등), 또는 URL이 빈 문자열인 경우, 요소 작업을 큐에 추가하여 DOM 조작 작업 소스미디어 요소를 주어, 먼저 텍스트 트랙 준비 상태로드 실패로 변경한 다음 이벤트를 발생시킵니다.

    만약 페치가 실패하지 않고, 파일이 성공적으로 처리되었다면, 마지막 작업요소 작업을 큐에 추가하고, 네트워킹 작업 소스에서 데이터를 파싱한 후, 텍스트 트랙 준비 상태로드 완료로 변경하고 이벤트를 발생시킵니다.

    페치가 진행 중일 때 다음 중 하나가 발생하면:

    ...사용자 에이전트는 페칭을 중단하고, 해당 알고리즘에서 생성된 모든 대기 중인 작업을 취소하며(특히 URL이 변경된 순간 이후에 텍스트 트랙 큐 목록에 추가된 큐는 제외), 요소 작업을 큐에 추가하여 DOM 조작 작업 소스트랙 요소를 주고, 먼저 텍스트 트랙 준비 상태로드 실패로 변경한 후 이벤트를 발생시킵니다.

  11. 텍스트 트랙 준비 상태가 더 이상 로드 중으로 설정되지 않을 때까지 기다립니다.

  12. 트랙 URL이 더 이상 URL과 같지 않게 되고, 동시에 텍스트 트랙 모드숨김 또는 표시됨으로 설정될 때까지 기다립니다.

  13. top으로 이동합니다.

언제든지 트랙 요소가 src 속성을 설정, 변경, 또는 제거하면, 사용자 에이전트는 즉시 해당 요소의 텍스트 트랙텍스트 트랙 큐 목록을 비워야 합니다. (이 또한 위 알고리즘이 이전에 제공된 URL을 사용하여 얻어진 리소스에서 큐를 추가하는 것을 중지시킵니다.)

4.8.11.11.4 다양한 형식에서 큐를 텍스트 트랙 큐로 노출하기 위한 가이드라인

HTML 사용자 에이전트에 의해 처리되기 위해 특정 형식의 텍스트 트랙 큐가 어떻게 해석되어야 하는지는 해당 형식에 의해 정의됩니다. 이러한 사양이 없는 경우, 이 섹션은 구현이 일관되게 이러한 형식을 노출하려고 시도할 수 있는 제약을 제공합니다.

HTML의 텍스트 트랙 모델을 지원하기 위해, 각 타이밍 데이터 단위는 텍스트 트랙 큐로 변환됩니다. 해당 형식의 기능과 이 사양에 정의된 텍스트 트랙 큐의 각 측면 간의 매핑이 정의되지 않은 경우, 구현은 이러한 매핑이 앞서 정의된 텍스트 트랙 큐의 측면 정의와 일치하도록 해야 하며, 다음 제약 조건과도 일치하도록 해야 합니다:

텍스트 트랙 큐 식별자

해당 형식에 명확한 큐별 식별자가 없는 경우, 이를 빈 문자열로 설정해야 합니다.

텍스트 트랙 큐 종료 시 일시정지 플래그

False로 설정해야 합니다.

4.8.11.11.5 텍스트 트랙 API

TextTrackList

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface TextTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter TextTrack (unsigned long index);
  TextTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
media.textTracks.length

HTMLMediaElement/textTracks

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet1.0+Opera Android12.1+

미디어 요소에 연결된 텍스트 트랙의 수를 반환합니다. (예: track 요소에서). 이는 텍스트 트랙의 수입니다. 미디어 요소텍스트 트랙 목록.

media.textTracks[ n ]

n번째 텍스트 트랙을 나타내는 TextTrack 객체를 반환합니다. 미디어 요소텍스트 트랙 목록.

textTrack = media.textTracks.getTrackById(id)

TextTrackList/getTrackById

모든 최신 엔진에서 지원.

Firefox31+Safari8+Chrome33+
Opera?Edge79+
Edge (Legacy)18Internet Explorer지원하지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지정된 식별자를 가진 TextTrack 객체를 반환하거나, 해당 식별자를 가진 트랙이 없으면 null을 반환합니다.

TextTrackList 객체는 주어진 순서에 따라 텍스트 트랙의 동적으로 업데이트되는 목록을 나타냅니다.

textTracks 속성은 미디어 요소TextTrackList 객체를 반환해야 합니다. TextTrack 객체를 텍스트 트랙에 대해, 미디어 요소텍스트 트랙 목록에서 반환합니다. 이는 텍스트 트랙 목록의 동일한 순서로 반환됩니다.

TextTrackList/length

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

length 속성은 TextTrackList 객체가 나타내는 목록에 있는 텍스트 트랙의 수를 반환해야 합니다.

지원되는 속성 인덱스TextTrackList 객체의 현재 순간에 0부터 텍스트 트랙 수까지의 숫자입니다. 목록에 텍스트 트랙이 없으면 지원되는 속성 인덱스는 없습니다.

인덱스 속성의 값을 결정하려면 주어진 인덱스 index에 대해 TextTrackList 객체가 나타내는 목록의 index번째 텍스트 트랙을 반환해야 합니다.

getTrackById(id) 메서드는 TextTrackTextTrackList 객체에서 첫 번째 id IDL 속성이 인자 id와 같은 값을 반환하는 트랙을 반환해야 합니다. 일치하는 트랙이 없을 경우 메서드는 null을 반환해야 합니다.


TextTrack

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
enum TextTrackMode { "disabled",  "hidden",  "showing" };
enum TextTrackKind { "subtitles",  "captions",  "descriptions",  "chapters",  "metadata" };

[Exposed=Window]
interface TextTrack : EventTarget {
readonly attribute TextTrackKind kind;
readonly attribute DOMString label;
readonly attribute DOMString language;

readonly attribute DOMString id;
readonly attribute DOMString inBandMetadataTrackDispatchType;

attribute TextTrackMode mode;

readonly attribute TextTrackCueList? cues;
readonly attribute TextTrackCueList? activeCues;

undefined addCue(TextTrackCue cue);
undefined removeCue(TextTrackCue cue);

attribute EventHandler oncuechange;
};
textTrack = media.addTextTrack(kind [, label [, language ] ])

새로운 TextTrack 객체를 생성하고 반환하며, 이 객체는 또한 미디어 요소텍스트 트랙 목록에 추가됩니다.

textTrack.kind

TextTrack/kind

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

텍스트 트랙의 종류 문자열을 반환합니다.

textTrack.label

TextTrack/label

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

텍스트 트랙 라벨을 반환합니다(있는 경우). 그렇지 않으면 빈 문자열을 반환합니다. (이는 객체가 사용자에게 노출될 경우 다른 속성에서 맞춤 라벨을 생성해야 함을 나타냅니다.)

textTrack.language

TextTrack/language

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

텍스트 트랙 언어 문자열을 반환합니다.

textTrack.id

TextTrack/id

모든 최신 엔진에서 지원.

Firefox31+Safari8+Chrome33+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

주어진 트랙의 ID를 반환합니다.

인밴드 트랙의 경우, 형식이 미디어 프래그먼트 구문을 지원하는 경우, 해당 ID는 프래그먼트와 함께 사용할 수 있습니다. 이 값은 getTrackById() 메서드와 함께 사용할 수 있습니다.

TextTrack 객체에 해당하는 track 요소의 경우, 이는 track 요소의 ID입니다.

textTrack.inBandMetadataTrackDispatchType

TextTrack/inBandMetadataTrackDispatchType

Firefox31+Safari8+ChromeNo
Opera?EdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

텍스트 트랙 인밴드 메타데이터 트랙 디스패치 유형 문자열을 반환합니다.

textTrack.mode [ = value ]

TextTrack/mode

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

텍스트 트랙 모드 문자열을 반환합니다. 다음 목록에서:

"disabled"

텍스트 트랙 비활성화 모드.

"hidden"

텍스트 트랙 숨김 모드.

"showing"

텍스트 트랙 표시 모드.

모드를 변경하기 위해 설정할 수 있습니다.

textTrack.cues

TextTrack/cues

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

텍스트 트랙 큐 목록TextTrackCueList 객체로 반환합니다.

textTrack.activeCues

TextTrack/activeCues

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

텍스트 트랙 큐 중 현재 활성화된 큐를 텍스트 트랙 큐 목록에서 TextTrackCueList 객체로 반환합니다. (즉, 현재 재생 위치 전후에 시작하고 끝나는 큐).

textTrack.addCue(cue)

TextTrack/addCue

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

주어진 큐를 textTrack텍스트 트랙 큐 목록에 추가합니다.

textTrack.removeCue(cue)

TextTrack/removeCue

모든 최신 엔진에서 지원.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

주어진 큐를 textTrack텍스트 트랙 큐 목록에서 제거합니다.

addTextTrack(kind, label, language) 메서드를 미디어 요소에서 호출하면 다음 단계를 수행해야 합니다:

  1. 새로운 TextTrack 객체를 생성합니다.

  2. 텍스트 트랙을 생성하고, 그 객체에 해당하는 트랙의 텍스트 트랙 종류kind로 설정합니다. 텍스트 트랙 라벨label로, 텍스트 트랙 언어language로 설정하고, 텍스트 트랙 준비 상태텍스트 트랙 로드됨 상태로, 텍스트 트랙 모드텍스트 트랙 숨김 모드로, 그리고 텍스트 트랙 큐 목록을 빈 목록으로 설정합니다.

    초기에는 텍스트 트랙 큐 목록텍스트 트랙 렌더링 업데이트 규칙과 연결되지 않습니다. 텍스트 트랙 큐가 추가되면, 텍스트 트랙 큐 목록에 규칙이 영구적으로 설정됩니다.

  3. 텍스트 트랙미디어 요소텍스트 트랙 목록에 추가합니다.

  4. 미디어 요소 작업 큐미디어 요소에서 주어졌을 때, 이벤트를 발생시키는 작업을 수행합니다. 이 이벤트는 addtrack이라는 이름의 이벤트로, 미디어 요소textTracks 속성의 TextTrackList 객체에서 발생하며, TrackEvent를 사용하여, track 속성이 새 텍스트 트랙TextTrack 객체로 초기화됩니다.

  5. TextTrack 객체를 반환합니다.


kind 속성은 텍스트 트랙 종류를 반환해야 하며, 이는 TextTrack 객체가 나타내는 텍스트 트랙에 해당합니다.

label 속성은 텍스트 트랙 레이블을 반환해야 하며, 이는 TextTrack 객체가 나타내는 텍스트 트랙에 해당합니다.

language 속성은 텍스트 트랙 언어를 반환해야 하며, 이는 TextTrack 객체가 나타내는 텍스트 트랙에 해당합니다.

id 속성은 트랙의 식별자를 반환합니다. 만약 식별자가 없다면 빈 문자열을 반환합니다. track 요소에 해당하는 트랙의 경우, 트랙의 식별자는 해당 요소의 id 속성 값입니다. 인밴드 트랙의 경우, 트랙의 식별자는 미디어 리소스에 의해 지정됩니다. 만약 미디어 리소스가 미디어 프래그먼트 구문을 지원하는 형식이라면, 특정 트랙에 대해 반환되는 식별자는 해당 트랙을 활성화하는 데 사용될 수 있는 동일한 식별자여야 합니다.

inBandMetadataTrackDispatchType 속성은 인밴드 메타데이터 트랙 디스패치 타입을 반환해야 하며, 이는 TextTrack 객체가 나타내는 텍스트 트랙에 해당합니다.

mode 속성은 텍스트 트랙 모드에 해당하는 문자열을 반환해야 하며, 이는 TextTrack 객체가 나타내는 텍스트 트랙에 정의된 목록에 따라 반환됩니다:

"disabled"
텍스트 트랙 비활성화 모드입니다.
"hidden"
텍스트 트랙 숨김 모드입니다.
"showing"
텍스트 트랙 표시 모드입니다.

설정 시, 새로운 값이 현재 속성이 반환하는 값과 다르다면, 새로운 값은 다음과 같이 처리되어야 합니다:

새로운 값이 "disabled"인 경우
텍스트 트랙TextTrack 객체에 해당하는 텍스트 트랙 모드비활성화 모드로 설정합니다.
새로운 값이 "hidden"인 경우
텍스트 트랙TextTrack 객체에 해당하는 텍스트 트랙 모드숨김 모드로 설정합니다.
새로운 값이 "showing"인 경우
텍스트 트랙TextTrack 객체에 해당하는 텍스트 트랙 모드표시 모드로 설정합니다.

만약 TextTrack 객체가 나타내는 텍스트 트랙텍스트 트랙 모드비활성화 모드가 아닌 경우, cues 속성은 TextTrackCueList 객체를 반환해야 하며, 이는 해당 TextTrack 객체가 나타내는 텍스트 트랙의 특정 종료 시간 이후에 발생하는 자막을 포함하는 목록을 나타냅니다. 그렇지 않으면 null을 반환해야 합니다. 각 TextTrack 객체에 대해 객체가 반환될 때마다 동일한 TextTrackCueList 객체가 반환되어야 합니다.

스크립트가 시작된 시점의 가능한 가장 이른 위치는 마지막으로 이벤트 루프가 1단계에 도달했을 때의 가능한 가장 이른 위치입니다.

만약 TextTrack 객체가 나타내는 텍스트 트랙텍스트 트랙 모드비활성화 모드가 아닌 경우, activeCues 속성은 TextTrackCueList 객체를 반환해야 하며, 이는 해당 TextTrack 객체가 나타내는 텍스트 트랙의 현재 활성화된 자막 목록을 나타냅니다. 그렇지 않으면 null을 반환해야 합니다. 각 TextTrack 객체에 대해 객체가 반환될 때마다 동일한 TextTrackCueList 객체가 반환되어야 합니다.

텍스트 트랙 자막활성 플래그가 스크립트가 시작된 시점에 설정된 경우는 마지막으로 이벤트 루프1단계에 도달했을 때 텍스트 트랙 자막 활성 플래그가 설정된 경우입니다.


TextTrack 객체의 addCue(cue) 메서드는 다음 단계를 실행해야 합니다:

  1. 만약 텍스트 트랙 자막 목록이 아직 텍스트 트랙 렌더링 업데이트 규칙과 연결되지 않았다면, cue에 적합한 규칙과 연결합니다.

  2. 만약 텍스트 트랙 자막 목록과 연결된 규칙이 cue에 적합한 규칙과 다르다면, InvalidStateError DOMException을 발생시킵니다.

  3. 주어진 cue가 이미 텍스트 트랙 자막 목록에 있는 경우, 해당 목록에서 cue를 제거합니다.

  4. cueTextTrack 객체의 텍스트 트랙에 추가합니다.

TextTrack 객체의 removeCue(cue) 메서드는 다음 단계를 실행해야 합니다:

  1. 주어진 cueTextTrack 객체의 텍스트 트랙텍스트 트랙 자막 목록에 없는 경우, NotFoundError DOMException을 발생시킵니다.

  2. cueTextTrack 객체의 텍스트 트랙텍스트 트랙 자막 목록에서 제거합니다.

이 예제에서는 audio 요소를 사용하여 여러 사운드 효과가 포함된 사운드 파일에서 특정 사운드 효과를 재생합니다. 스크립트를 실행 중인 브라우저에서 클립이 끝나는 시점에 오디오가 정확하게 일시 정지되도록 하기 위해 자막을 사용합니다. 페이지가 스크립트에 의존하여 오디오를 일시 정지시켰다면, 브라우저가 정확한 시간에 스크립트를 실행하지 못했을 경우 다음 클립의 시작 부분이 들릴 수 있습니다.

var sfx = new Audio('sfx.wav'); 
var sounds = sfx.addTextTrack('metadata');

// 관심 있는 사운드를 추가합니다.
function addFX(start, end, name) { 
  var cue = new VTTCue(start, end, ''); 
  cue.id = name; 
  cue.pauseOnExit = true; 
  sounds.addCue(cue); 
} 
addFX(12.783, 13.612, 'dog bark'); 
addFX(13.612, 15.091, 'kitten mew');

function playSound(id) { 
  sfx.currentTime = sounds.getCueById(id).startTime; 
  sfx.play(); 
}

// 가능한 빨리 짖는 소리를 재생합니다.
sfx.oncanplaythrough = function () { 
  playSound('dog bark'); 
} 
// 사용자가 떠나려 할 때 고양이 울음 소리를 재생하고, 브라우저가 그들에게 머물도록 요청하게 합니다.
window.onbeforeunload = function (e) { 
  playSound('kitten mew'); 
  e.preventDefault(); 
}

TextTrackCueList

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface TextTrackCueList {
  readonly attribute unsigned long length;
  getter TextTrackCue (unsigned long index);
  TextTrackCue? getCueById(DOMString id);
};
cuelist.length

목록의 수를 반환합니다.

cuelist[index]

목록의 index에 있는 텍스트 트랙 큐를 반환합니다. 큐는 텍스트 트랙 큐 순서로 정렬되어 있습니다.

cuelist.getCueById(id)

id로 식별되는 첫 번째 텍스트 트랙 큐텍스트 트랙 큐 순서에서 반환합니다.

주어진 식별자가 없거나 인수가 빈 문자열일 경우 null을 반환합니다.

TextTrackCueList 객체는 지정된 순서로 텍스트 트랙 큐의 동적으로 업데이트되는 목록을 나타냅니다.

TextTrackCueList/length

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

length 속성은 TextTrackCueList 객체가 나타내는 목록의 수를 반환해야 합니다.

TextTrackCueList 객체의 지원되는 속성 인덱스는 TextTrackCueList 객체가 나타내는 목록의 수에서 하나를 뺀 값입니다. 목록에 가 없는 경우 지원되는 속성 인덱스는 없습니다.

주어진 index에 대해 인덱스된 속성의 값을 결정하기 위해 사용자 에이전트는 목록에서 index번째 텍스트 트랙 큐를 반환해야 합니다.

TextTrackCueList/getCueById

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

getCueById(id) 메서드는 빈 문자열이 아닌 인수를 사용하여 호출될 때, 목록에서 첫 번째 텍스트 트랙 큐를 반환해야 하며, id가 일치하는 경우 null을 반환해야 합니다. 인수가 빈 문자열인 경우 이 메서드는 null을 반환해야 합니다.


TextTrackCue

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface TextTrackCue : EventTarget {
  readonly attribute TextTrack? track;

  attribute DOMString id;
  attribute double startTime;
  attribute unrestricted double endTime;
  attribute boolean pauseOnExit;

  attribute EventHandler onenter;
  attribute EventHandler onexit;
};
cue.track

텍스트 트랙 큐가 속한 TextTrack 객체를 반환하며, 그렇지 않으면 null을 반환합니다.

cue.id [ = value ]

텍스트 트랙 큐 식별자를 반환합니다.

설정할 수 있습니다.

cue.startTime [ = value ]

초 단위로 텍스트 트랙 큐 시작 시간을 반환합니다.

설정할 수 있습니다.

cue.endTime [ = value ]

초 단위로 텍스트 트랙 큐 종료 시간을 반환합니다.

설정할 수 있습니다.

cue.pauseOnExit [ = value ]

텍스트 트랙 큐의 종료 시간에 도달했을 때 미디어 재생이 일시 중지되어야 하는지 여부를 나타내는 플래그를 반환합니다.

설정할 수 있습니다.

TextTrackCue/track

모든 현재 엔진에서 지원됩니다.

Firefox31+ Safari6+ Chrome23+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer10+
Firefox Android? Safari iOS7+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

track 속성은 가져올 때 TextTrack 객체를 반환해야 합니다. 이 객체는 텍스트 트랙 중에서 큐 목록에 속한 텍스트 트랙 큐를 나타내는 TextTrackCue 객체를 나타냅니다. 해당하는 것이 없으면 null을 반환합니다.

TextTrackCue/id

모든 현재 엔진에서 지원됩니다.

Firefox31+ Safari6+ Chrome23+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer10+
Firefox Android? Safari iOS7+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

id 속성은 가져올 때 텍스트 트랙 큐 식별자를 반환해야 합니다. 이는 텍스트 트랙 큐를 나타내며, TextTrackCue 객체에 의해 나타내어집니다. 설정할 때, 텍스트 트랙 큐 식별자는 새로운 값으로 설정되어야 합니다.

TextTrackCue/startTime

모든 현재 엔진에서 지원됩니다.

Firefox31+ Safari6+ Chrome23+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer10+
Firefox Android? Safari iOS7+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

startTime 속성은 가져올 때 텍스트 트랙 큐 시작 시간을 반환해야 합니다. 이는 텍스트 트랙 큐를 나타내며, TextTrackCue 객체에 의해 나타내어집니다. 설정할 때, 텍스트 트랙 큐 시작 시간은 새로운 값으로 설정되어야 하며, 이는 초 단위로 해석됩니다. 그런 다음, TextTrackCue 객체의 텍스트 트랙 큐텍스트 트랙큐 목록에 있고, 그 트랙이 미디어 요소텍스트 트랙 목록에 있으며, 미디어 요소포스터 표시 플래그가 설정되어 있지 않은 경우, 해당 미디어 요소에 대한 시간은 흐릅니다 단계를 실행합니다.

TextTrackCue/endTime

모든 현재 엔진에서 지원됩니다.

Firefox31+ Safari6+ Chrome23+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer10+
Firefox Android? Safari iOS7+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

endTime 속성은 가져올 때 텍스트 트랙 큐 종료 시간을 반환해야 합니다. 이는 텍스트 트랙 큐를 나타내며, TextTrackCue 객체에 의해 나타내어집니다. 설정할 때, 만약 새 값이 음의 무한대이거나 NaN(숫자가 아님) 값이면, TypeError 예외를 던집니다. 그렇지 않으면, 텍스트 트랙 큐 종료 시간은 새 값으로 설정됩니다. 그런 다음, TextTrackCue 객체의 텍스트 트랙 큐텍스트 트랙큐 목록에 있고, 그 트랙이 미디어 요소텍스트 트랙 목록에 있으며, 미디어 요소포스터 표시 플래그가 설정되어 있지 않은 경우, 해당 미디어 요소에 대한 시간은 흐릅니다 단계를 실행합니다.

TextTrackCue/pauseOnExit

모든 현재 엔진에서 지원됩니다.

Firefox31+ Safari6+ Chrome23+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer10+
Firefox Android? Safari iOS7+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

pauseOnExit 속성은 가져올 때 true를 반환해야 합니다. 이는 텍스트 트랙 큐 종료 시 중지 플래그가 설정되어 있는 경우입니다. 그렇지 않은 경우에는 false를 반환해야 합니다. 설정할 때, 새 값이 true이면 텍스트 트랙 큐 종료 시 중지 플래그를 설정하고, 그렇지 않으면 플래그를 해제해야 합니다.

4.8.11.11.6 텍스트 트랙 API 객체의 이벤트 핸들러

다음은 모든 TextTrackList 인터페이스를 구현하는 객체에서 이벤트 핸들러 IDL 속성으로 지원되어야 하는 이벤트 핸들러와 이에 대응하는 이벤트 핸들러 이벤트 유형입니다:

이벤트 핸들러 이벤트 핸들러 이벤트 유형
onchange change
onaddtrack addtrack
onremovetrack removetrack

다음은 모든 TextTrack 인터페이스를 구현하는 객체에서 이벤트 핸들러 IDL 속성으로 지원되어야 하는 이벤트 핸들러와 이에 대응하는 이벤트 핸들러 이벤트 유형입니다:

이벤트 핸들러 이벤트 핸들러 이벤트 유형
oncuechange

TextTrack/cuechange_event

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
cuechange

다음은 모든 TextTrackCue 인터페이스를 구현하는 객체에서 이벤트 핸들러 IDL 속성으로 지원되어야 하는 이벤트 핸들러와 이에 대응하는 이벤트 핸들러 이벤트 유형입니다:

이벤트 핸들러 이벤트 핸들러 이벤트 유형
onenter

TextTrackCue/enter_event

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
enter
onexit

TextTrackCue/exit_event

모든 현재 엔진에서 지원됩니다.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
exit
4.8.11.11.7 메타데이터 텍스트 트랙에 대한 모범 사례

이 섹션은 비규범적입니다.

텍스트 트랙은 미디어 데이터와 관련된 데이터를 저장하는 데 사용될 수 있으며, 상호작용 또는 증강된 뷰를 위한 정보를 제공할 수 있습니다.

예를 들어, 스포츠 방송을 보여주는 페이지에는 현재 점수에 대한 정보가 포함될 수 있습니다. 로봇 대회가 실시간으로 스트리밍되고 있다고 가정해봅시다. 이미지 위에 점수가 다음과 같이 오버레이될 수 있습니다:

사용자가 비디오의 임의의 지점으로 탐색할 때 점수 표시가 올바르게 렌더링되도록 하려면 메타데이터 텍스트 트랙 큐의 길이가 점수에 적합하도록 설정되어야 합니다. 예를 들어, 위의 프레임에서는 매치 번호를 표시하는 큐는 경기 시간 동안 지속되고, 블루 얼라이언스의 점수가 변경될 때까지 지속되는 큐가 하나 있으며, 레드 얼라이언스의 점수가 변경될 때까지 지속되는 큐가 하나 있을 수 있습니다. 비디오가 라이브 이벤트의 스트림일 경우, 오른쪽 하단의 시간은 아마도 큐를 기반으로 하지 않고 현재 비디오 시간에서 자동으로 유도될 것입니다. 그러나 비디오가 하이라이트만을 포함하는 경우, 이러한 정보도 큐에 포함될 수 있습니다.

다음은 이와 같은 내용이 WebVTT 파일에서 어떻게 나타날 수 있는지 보여줍니다:

WEBVTT

...

05:10:00.000 --> 05:12:15.000
matchtype:qual
matchnumber:37

...

05:11:02.251 --> 05:11:17.198
red:78

05:11:03.672 --> 05:11:54.198
blue:66

05:11:17.198 --> 05:11:25.912
red:80

05:11:25.912 --> 05:11:26.522
red:83

05:11:26.522 --> 05:11:26.982
red:86

05:11:26.982 --> 05:11:27.499
red:89

...

여기서 중요한 점은 관련 이벤트가 적용되는 시간 동안 정보를 제공하는 큐가 설정된다는 것입니다. 만약 점수가 05:11:17.198에 "red+2", 05:11:25.912에 "red+3" 등으로 변경될 때, 0길이(또는 매우 짧은 거의 0길이)의 큐로 설정된다면 문제점이 발생합니다. 주로 탐색을 구현하기가 훨씬 어려워지며, 스크립트가 모든 큐 목록을 순회하여 놓친 알림이 없는지 확인해야 하기 때문입니다. 또한 큐가 짧으면 스크립트가 이를 활성화된 상태로 인식하지 못할 수 있습니다.

이와 같은 방식으로 큐를 사용할 때, 작성자는 현재 주석을 업데이트하기 위해 cuechange 이벤트를 사용하는 것이 좋습니다. 특히, timeupdate 이벤트를 사용하는 것은 적절하지 않을 수 있습니다. 이는 큐가 변경되지 않았을 때에도 작업을 수행해야 하며, 더 중요한 것은 timeupdate 이벤트가 속도 제한을 받기 때문에 메타데이터 큐가 활성화된 시점과 디스플레이가 업데이트되는 시점 사이에 더 높은 지연을 초래할 수 있기 때문입니다.

4.8.11.12 URL을 통해 트랙 종류 식별하기

다른 명세서나 포맷에서 AudioTrack kind 또는 VideoTrack kind IDL 속성의 반환 값을 식별하거나 텍스트 트랙의 종류를 식별하기 위해 URL이 필요한 경우, about:html-kind URL을 사용해야 합니다.

4.8.11.13 사용자 인터페이스

controls 속성은 불리언 속성입니다. 이 속성이 존재할 경우, 저자가 스크립트로 제어할 수 없는 컨트롤러를 제공하지 않았음을 나타내며, 사용자 에이전트가 자체 컨트롤 세트를 제공하기를 원한다는 의미입니다.

이 속성이 존재하거나 스크립트가 비활성화된 경우 미디어 요소에 대해 사용자 에이전트는 사용자에게 사용자 인터페이스를 노출해야 합니다. 이 인터페이스는 재생 시작, 일시 정지, 콘텐츠에서 임의의 위치로 탐색, 볼륨 변경, 닫힌 자막이나 내장된 수화 트랙의 표시 변경, 다른 오디오 트랙 선택 또는 오디오 설명 켜기, 전체 화면 비디오나 독립된 크기 조절 가능한 창 등 사용자에게 더 적합한 방식으로 미디어 콘텐츠를 표시하는 기능을 포함해야 합니다. 또한 다른 컨트롤도 제공될 수 있습니다.

그러나 이 속성이 없더라도 사용자 에이전트는 미디어 리소스 재생에 영향을 미치는 컨트롤(예: 재생, 일시 정지, 탐색, 트랙 선택, 볼륨 조절)을 제공할 수 있습니다. 이러한 기능은 페이지의 정상적인 렌더링을 방해하지 않아야 합니다. 예를 들어, 이러한 기능은 미디어 요소의 컨텍스트 메뉴, 플랫폼 미디어 키 또는 리모컨에 노출될 수 있습니다. 사용자 에이전트는 이 기능을 간단히 사용자에게 사용자 인터페이스를 노출함으로써 구현할 수 있습니다(예를 들어 controls 속성이 존재하는 것처럼).

사용자 에이전트가 사용자 인터페이스를 사용자에게 노출하여 미디어 요소에 대해 컨트롤을 표시하는 경우, 사용자 에이전트가 이 인터페이스와 상호작용할 때 모든 사용자 상호작용 이벤트를 억제해야 합니다. (예를 들어, 사용자가 비디오의 재생 컨트롤을 클릭할 때, mousedown 이벤트 등이 페이지의 다른 요소에서 동시에 발생하지 않아야 합니다.)

가능한 경우(특히 재생 시작, 정지, 일시 정지, 재개, 탐색, 재생 속도 변경, 빠른 감기 또는 되감기, 텍스트 트랙 나열, 활성화 및 비활성화, 음소거 또는 오디오 볼륨 변경) 사용자 에이전트가 노출하는 사용자 인터페이스 기능은 위에서 설명한 DOM API를 통해 구현되어야 하며, 예를 들어 동일한 이벤트가 모두 발생해야 합니다.

빠른 감기나 되감기와 같은 기능은 playbackRate 속성만 변경하여 구현해야 하며, defaultPlaybackRate 속성은 변경하지 않아야 합니다.

탐색은 탐색을 통해 요청된 위치로 미디어 요소미디어 타임라인에서 탐색해야 합니다. 임의의 위치로의 탐색이 느린 미디어 리소스의 경우, 사용자 에이전트는 탐색 막대와 같은 근사 위치 인터페이스를 사용자가 조작할 때 속도를 위한 근사 플래그를 사용하는 것이 좋습니다.

HTMLMediaElement/controls

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

controls IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.


media.volume [ = value ]

HTMLMediaElement/volume

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS🔰 3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

현재 재생 볼륨을 반환합니다. 반환 값은 0.0에서 1.0 범위의 숫자로, 0.0이 가장 조용하고 1.0이 가장 큽니다.

설정할 수 있으며, 볼륨을 변경합니다.

새 값이 0.0에서 1.0 범위 내에 없을 경우, "IndexSizeError" DOMException 예외가 발생합니다.

media.muted [ = value ]

HTMLMediaElement/muted

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

오디오가 음소거된 경우 true를 반환하며, 이는 volume 속성을 무시하게 됩니다. 음소거되지 않은 경우 volume 속성이 반영됩니다.

설정할 수 있으며, 오디오가 음소거된 상태를 변경할 수 있습니다.

미디어 요소는 0.0(무음)에서 1.0(가장 큰 소리) 범위의 비율로 표현되는 재생 볼륨을 가지고 있습니다. 초기 볼륨은 1.0이어야 하지만, 사용자 에이전트는 세션 간 또는 사이트별로 마지막 설정 값을 기억하여 다른 값으로 시작할 수 있습니다.

volume IDL 속성은 재생 볼륨을 반환해야 합니다. 설정 시, 새로운 값이 0.0에서 1.0 범위 내에 있다면 미디어 요소재생 볼륨을 해당 값으로 설정해야 합니다. 새로운 값이 0.0에서 1.0 범위 밖에 있다면, 설정 시 "IndexSizeError" DOMException 예외를 발생시켜야 합니다.

미디어 요소음소거될 수도 있습니다. 어떤 요소가 요소를 음소거하고 있다면, 그 요소는 음소거됩니다. (예를 들어, 재생 방향이 역방향일 때, 해당 요소는 음소거됩니다.)

muted IDL 속성은 마지막으로 설정된 값을 반환해야 합니다. 미디어 요소가 생성될 때, 요소에 muted 콘텐츠 속성이 지정되어 있으면, muted IDL 속성을 true로 설정해야 합니다. 그렇지 않은 경우, 사용자 에이전트는 사용자의 선호도에 따라 값을 설정할 수 있습니다(예: 세션 간 또는 사이트별로 마지막 설정 값을 기억). muted IDL 속성이 true로 설정된 동안 미디어 요소음소거되어야 합니다.

volumemuted IDL 속성이 반환하는 값이 변경될 때마다, 사용자 에이전트는 미디어 요소 작업을 큐에 추가해야 하며, 미디어 요소에서 이벤트를 발생시켜야 합니다. 그런 다음, 미디어 요소재생이 허용되지 않는 경우, 사용자 에이전트는 내부 일시 정지 단계를 수행해야 합니다.

사용자 에이전트는 볼륨 잠금(불리언)을 가지고 있습니다. 이 값은 구현 정의이며, 재생 볼륨이 적용되는지 여부를 결정합니다.

요소의 유효한 미디어 볼륨은 다음과 같이 결정됩니다:

  1. 사용자가 사용자 에이전트가 요소의 볼륨을 재정의하도록 지정한 경우, 사용자가 원하는 볼륨을 반환합니다.

  2. 사용자 에이전트의 볼륨 잠금이 true인 경우, 시스템 볼륨을 반환합니다.

  3. 요소의 오디오 출력이 음소거된 경우, 0을 반환합니다.

  4. volume재생 볼륨으로 설정합니다. 이 값은 미디어 요소의 오디오 부분에서 0.0(무음)에서 1.0(가장 큰 소리) 범위 내에 있습니다.

  5. volume 값을 반환합니다. 이 값은 0.0(무음)에서 1.0(가장 큰 소리) 범위 내에서 해석됩니다. 0.0은 무음이고 1.0은 가장 큰 소리이며, 그 사이의 값은 음량이 증가합니다. 이 범위는 선형일 필요는 없습니다. 가장 큰 소리는 시스템의 가장 큰 가능한 설정보다 낮을 수 있습니다. 예를 들어, 사용자가 최대 볼륨을 설정했을 수 있습니다.

muted 콘텐츠 속성은 미디어 요소에 있으며, 불리언 속성으로 미디어 리소스의 오디오 출력을 기본적으로 음소거할지를 제어하며, 사용자 선호도를 무시할 수 있습니다.

HTMLMediaElement/defaultMuted

모든 최신 엔진에서 지원됩니다.

Firefox11+Safari6+Chrome15+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

defaultMuted IDL 속성은 반영해야 합니다. muted 콘텐츠 속성을 반영합니다.

이 속성은 동적 효과가 없습니다(요소의 기본 상태만 제어합니다).

이 비디오(광고)는 자동으로 재생되지만, 사용자에게 불쾌감을 주지 않기 위해 소리를 끄고 재생되며, 사용자가 소리를 켤 수 있습니다. 사용자 에이전트는 사용자가 상호작용하지 않은 상태에서 소리가 켜지면 비디오를 일시 정지할 수 있습니다.

<video src="adverts.cgi?kind=video" controls autoplay loop muted></video>
4.8.11.14 시간 범위

TimeRanges

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

TimeRanges 인터페이스를 구현하는 객체는 시간의 범위(기간) 목록을 나타냅니다.

[Exposed=Window]
interface TimeRanges {
  readonly attribute unsigned long length;
  double start(unsigned long index);
  double end(unsigned long index);
};
media.length

TimeRanges/length

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

객체 내의 범위 수를 반환합니다.

time = media.start(index)

TimeRanges/start

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 인덱스의 범위 시작 시간을 반환합니다.

인덱스가 범위를 벗어나면 "IndexSizeError" DOMException을 발생시킵니다.

time = media.end(index)

TimeRanges/end

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 인덱스의 범위 끝 시간을 반환합니다.

인덱스가 범위를 벗어나면 "IndexSizeError" DOMException을 발생시킵니다.

length IDL 속성은 객체가 나타내는 범위의 수를 반환해야 합니다.

start(index) 메서드는 객체가 나타내는 index번째 범위의 시작 위치를 반환해야 합니다. 이 위치는 객체가 포함하는 타임라인의 시작부터 초 단위로 측정됩니다.

end(index) 메서드는 객체가 나타내는 index번째 범위의 끝 위치를 반환해야 합니다. 이 위치는 객체가 포함하는 타임라인의 시작부터 초 단위로 측정됩니다.

이 메서드들은 index 인자가 객체가 나타내는 범위 수보다 크거나 같은 값으로 호출될 경우 "IndexSizeError" DOMException을 발생시켜야 합니다.

TimeRanges 객체가 정규화된 TimeRanges 객체로 정의될 때, 그 객체가 나타내는 범위는 다음 기준을 충족해야 합니다:

즉, 이러한 객체 내의 범위는 정렬되어 있으며, 겹치지 않고, 서로 맞닿지 않습니다(인접한 범위는 하나의 더 큰 범위로 통합됩니다). 범위는 비어 있을 수 있습니다(단일 시간 순간만 참조). 예를 들어, 사용자 에이전트가 미디어 요소가 일시 정지된 상태에서 현재 프레임을 제외한 모든 미디어 리소스를 삭제한 경우, 현재 프레임만이 버퍼링된 경우를 나타낼 수 있습니다.

TimeRanges 객체의 범위는 포함적이어야 합니다.

따라서 범위의 끝은 다음 인접 범위(겹치지 않지만 맞닿아 있는)의 시작과 같아야 합니다. 마찬가지로, 타임라인 전체를 포함하는 범위가 0에서 시작되는 경우, 시작은 0이고 끝은 타임라인의 지속 시간과 같아야 합니다.

buffered, seekable, 및 played IDL 속성에 의해 반환되는 객체들이 사용하는 타임라인은 해당 요소의 미디어 타임라인이어야 합니다.

4.8.11.15 TrackEvent 인터페이스

TrackEvent

모든 최신 엔진에서 지원됩니다.

Firefox27+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
    interface TrackEvent : Event {
      constructor(DOMString type, optional TrackEventInit eventInitDict = {});
    
      readonly attribute (VideoTrack or AudioTrack or TextTrack)? track;
    };
    
    dictionary TrackEventInit : EventInit {
      (VideoTrack or AudioTrack or TextTrack)? track = null;
    };
event.track

TrackEvent/track

모든 최신 엔진에서 지원됩니다.

Firefox27+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이벤트와 관련된 트랙 객체(TextTrack, AudioTrack, 또는 VideoTrack)를 반환합니다.

track 속성은 초기화된 값을 반환해야 합니다. 이 속성은 이벤트에 대한 컨텍스트 정보를 나타냅니다.

4.8.11.16 이벤트 요약

이 섹션은 규범적이지 않습니다.

다음 이벤트는 위에서 설명한 처리 모델의 일부로서 미디어 요소에서 발생합니다:

이벤트 이름 인터페이스 발생 조건 선행 조건
loadstart

HTMLMediaElement/loadstart_event

모든 최신 엔진에서 지원됩니다.

Firefox6+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
이벤트 사용자 에이전트가 미디어 데이터를 찾기 시작할 때, 리소스 선택 알고리즘의 일부로. networkState 값이 NETWORK_LOADING일 때
progress

HTMLMediaElement/progress_event

모든 최신 엔진에서 지원됩니다.

Firefox6+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
이벤트 사용자 에이전트가 미디어 데이터를 가져오고 있을 때. networkState 값이 NETWORK_LOADING일 때
suspend

HTMLMediaElement/suspend_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 사용자 에이전트가 의도적으로 현재 미디어 데이터를 가져오지 않고 있을 때. networkState 값이 NETWORK_IDLE일 때
abort

HTMLMediaElement/abort_event

모든 최신 엔진에서 지원됩니다.

Firefox9+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
이벤트 사용자 에이전트가 미디어 데이터를 완전히 다운로드하지 않고 중단할 때, 그러나 오류로 인한 것은 아닙니다. error는 코드가 MEDIA_ERR_ABORTED인 객체입니다. networkState 값은 NETWORK_EMPTYNETWORK_IDLE 중 하나입니다, 다운로드가 중단된 시점에 따라 다릅니다.
error

HTMLMediaElement/error_event

모든 최신 엔진에서 지원됩니다.

Firefox6+Safari3.1+Chrome3+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
이벤트 미디어 데이터를 가져오는 중에 오류가 발생하거나 리소스의 형식이 지원되지 않는 미디어 형식일 때. error는 코드가 MEDIA_ERR_NETWORK 이상인 객체입니다. networkState 값은 NETWORK_EMPTYNETWORK_IDLE 중 하나입니다, 다운로드가 중단된 시점에 따라 다릅니다.
emptied

HTMLMediaElement/emptied_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 이전에 NETWORK_EMPTY 상태가 아니었던 미디어 요소가 해당 상태로 전환될 때 (로드 중에 치명적인 오류가 발생했거나 리소스 선택 알고리즘이 이미 실행 중일 때 load() 메서드가 호출된 경우). networkState 값은 NETWORK_EMPTY; 모든 IDL 속성은 초기 상태에 있습니다.
stalled

HTMLMediaElement/stalled_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 사용자 에이전트가 미디어 데이터를 가져오려고 시도하지만 데이터가 예상치 않게 제공되지 않을 때. networkState 값이 NETWORK_LOADING일 때
loadedmetadata

HTMLMediaElement/loadedmetadata_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 사용자 에이전트가 미디어 리소스의 지속 시간 및 차원을 결정했고, 텍스트 트랙이 준비된 상태일 때. readyState 값이 처음으로 HAVE_METADATA 이상이 된 경우.
loadeddata

HTMLMediaElement/loadeddata_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 사용자 에이전트가 처음으로 미디어 데이터를 렌더링할 수 있을 때, 현재 재생 위치에서. readyState 값이 처음으로 HAVE_CURRENT_DATA 이상으로 증가했을 때.
canplay

HTMLMediaElement/canplay_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 사용자 에이전트가 미디어 데이터를 재생할 수 있지만, 현재 재생 속도로 콘텐츠를 추가 버퍼링 없이 끝까지 렌더링할 수 없다고 판단될 때. readyState 값이 HAVE_FUTURE_DATA 이상으로 새로 증가했을 때.
canplaythrough

HTMLMediaElement/canplaythrough_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 사용자 에이전트가 현재 재생 속도로 끝까지 렌더링할 수 있을 만큼 충분한 데이터를 로드했다고 판단될 때 콘텐츠를 추가 버퍼링 없이 재생할 수 있습니다. readyState 값이 HAVE_ENOUGH_DATA로 새로 설정되었을 때.
playing

HTMLMediaElement/playing_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 미디어 데이터가 부족하여 일시 중지되거나 지연된 후 재생이 시작될 준비가 되었을 때. readyState 값이 새로 HAVE_FUTURE_DATA 이상이 되며, paused 값이 false인 경우 또는 paused 값이 새로 false가 되었고 readyState 값이 새로 HAVE_FUTURE_DATA 이상이 되었을 때. 이 이벤트가 발생하더라도 요소가 잠재적으로 재생 중이 아닐 수도 있습니다. 예를 들어, 요소가 사용자 상호작용으로 인해 일시 중지된 경우 또는 인밴드 콘텐츠로 인해 일시 중지된 경우에 해당할 수 있습니다.
waiting

HTMLMediaElement/waiting_event

모든 최신 엔진에서 지원됩니다.

Firefox6+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
이벤트 다음 프레임을 사용할 수 없어서 재생이 중지되었지만, 사용자 에이전트는 그 프레임이 곧 사용 가능할 것으로 예상할 때. readyState 값이 HAVE_CURRENT_DATA 이하이고, paused 값이 false일 때. seeking 값이 true이거나 현재 재생 위치buffered의 범위에 포함되지 않은 경우입니다. paused 값이 false가 아닌 다른 이유로 재생이 중지될 수도 있지만, 이러한 이유는 이 이벤트를 발생시키지 않습니다. (그리고 이러한 상황이 해결되면 별도의 재생 중 이벤트가 발생하지 않습니다): 예를 들어, 재생이 종료되었거나, 재생이 오류로 인해 중지되었거나, 요소가 사용자 상호작용으로 인해 일시 중지되었거나 또는 인밴드 콘텐츠로 인해 일시 중지된 경우에 해당할 수 있습니다.
seeking

HTMLMediaElement/seeking_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 seeking IDL 속성이 true로 변경되고, 사용자 에이전트가 새 위치로 탐색을 시작했을 때.
seeked

HTMLMediaElement/seeked_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 seeking IDL 속성이 false로 변경된 후, 현재 재생 위치가 변경되었을 때.
ended

HTMLMediaElement/ended_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 미디어 리소스의 끝에 도달하여 재생이 중지되었을 때. currentTime 값이 미디어 리소스의 끝에 도달했으며, ended 값이 true일 때.
durationchange

HTMLMediaElement/durationchange_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 duration 속성이 업데이트되었을 때.
timeupdate

HTMLMediaElement/timeupdate_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 현재 재생 위치가 정상적인 재생의 일부로서 또는 불연속적으로 변경되었을 때.
play

HTMLMediaElement/play_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 요소가 더 이상 일시 중지되지 않음. play() 메서드가 반환된 후 또는 autoplay 속성이 재생을 시작하도록 했을 때. paused 속성이 새롭게 false로 설정됨.
pause

HTMLMediaElement/pause_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 요소가 일시 중지됨. pause() 메서드가 반환된 후 발생. paused 속성이 새롭게 true로 설정됨.
ratechange

HTMLMediaElement/ratechange_event

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
이벤트 defaultPlaybackRate 또는 playbackRate 속성이 업데이트되었을 때.
resize 이벤트 videoWidth 또는 videoHeight 속성 중 하나 이상이 업데이트되었을 때. 미디어 요소비디오 요소일 때, readyStateHAVE_NOTHING이 아닐 때.
volumechange

HTMLMediaElement/volumechange_event

모든 최신 엔진에서 지원됩니다.

Firefox6+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
이벤트 volume 속성 또는 muted 속성이 변경되었을 때 발생. 관련 속성의 setter가 반환된 후 발생.

다음 이벤트는 source 요소에서 발생합니다:

이벤트 이름 인터페이스 발생 조건
error Event 미디어 데이터를 가져오는 동안 오류가 발생하거나 리소스 형식이 지원되지 않는 미디어 형식일 때.

다음 이벤트는 AudioTrackList, VideoTrackList, 그리고 TextTrackList 객체에서 발생합니다:

이벤트 이름 인터페이스 발생 조건
change

AudioTrackList/change_event

모든 현재 엔진에서 지원됨.

Firefox🔰 33+Safari7+🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

TextTrackList/change_event

모든 현재 엔진에서 지원됨.

Firefox31+Safari7+Chrome33+
Opera?Edge79+
Edge (Legacy)18Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4+Samsung Internet?Opera Android?

VideoTrackList/change_event

모든 현재 엔진에서 지원됨.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event 트랙 목록의 하나 이상의 트랙이 활성화되거나 비활성화될 때.
addtrack

AudioTrackList/addtrack_event

모든 현재 엔진에서 지원됨.

Firefox🔰 33+Safari7+🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

TextTrackList/addtrack_event

모든 현재 엔진에서 지원됨.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

VideoTrackList/addtrack_event

모든 현재 엔진에서 지원됨.

Firefox🔰 33+Safari7+🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
TrackEvent 트랙이 트랙 목록에 추가될 때.
removetrack

AudioTrackList/removetrack_event

모든 현재 엔진에서 지원됨.

Firefox🔰 33+Safari7+🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

TextTrackList/removetrack_event

모든 현재 엔진에서 지원됨.

Firefox31+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)18Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4+Samsung Internet?Opera Android20+

VideoTrackList/removetrack_event

모든 현재 엔진에서 지원됨.

Firefox🔰 33+Safari7+🔰 37+
Opera?Edge🔰 79+
Edge (Legacy)지원 안됨Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
TrackEvent 트랙이 트랙 목록에서 제거될 때.

다음 이벤트는 TextTrack 객체와 track 요소에서 발생합니다:

이벤트 이름 인터페이스 발생 조건
cuechange

HTMLTrackElement/cuechange_event

모든 현재 엔진에서 지원됨.

Firefox68+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)14+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android19+

TextTrack/cuechange_event

모든 현재 엔진에서 지원됨.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
Event 트랙의 하나 이상의 큐가 활성화되거나 비활성화될 때.

다음 이벤트는 track 요소에서 발생합니다:

이벤트 이름 인터페이스 발생 조건
error Event 트랙 데이터를 가져오는 동안 오류가 발생하거나 리소스 형식이 지원되지 않는 텍스트 트랙 형식일 때.
load Event 트랙 데이터를 가져와 성공적으로 처리했을 때.

다음 이벤트는 TextTrackCue 객체에서 발생합니다:

이벤트 이름 인터페이스 발생 조건
enter

TextTrackCue/enter_event

모든 현재 엔진에서 지원됨.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
Event 큐가 활성화될 때.
exit

TextTrackCue/exit_event

모든 현재 엔진에서 지원됨.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
Event 큐가 더 이상 활성화되지 않을 때.
4.8.11.17 보안 및 개인정보 보호 고려사항

videoaudio 요소의 주요 보안 및 개인정보 보호 영향은 크로스 오리진 미디어를 임베드할 수 있는 기능에서 비롯됩니다. 위협은 두 가지 방향으로 발생할 수 있습니다: 악성 콘텐츠에서 피해자 페이지로, 또는 악성 페이지에서 피해자 콘텐츠로.


피해자 페이지가 악성 콘텐츠를 임베드할 경우, 콘텐츠가 임베드된 document(Document)와 상호작용하려는 스크립트 코드가 포함될 수 있다는 위협이 있습니다. 이를 방지하기 위해, 사용자 에이전트는 콘텐츠가 임베드된 페이지에 접근하지 못하도록 해야 합니다. DOM 개념을 사용하는 미디어 콘텐츠의 경우, 임베드된 콘텐츠는 독립적인 최상위 탐색 가능 항목(top-level traversable)에 있는 것처럼 취급되어야 합니다.

예를 들어, SVG 애니메이션이 video 요소에 임베드된 경우, 사용자 에이전트는 해당 애니메이션이 외부 페이지의 DOM에 접근하지 못하도록 합니다. SVG 리소스 내의 스크립트 관점에서 보면, SVG 파일은 부모가 없는 단독 최상위 탐색 가능 항목에 있는 것처럼 보일 것입니다.


악성 페이지가 피해자 콘텐츠를 임베드할 경우, 임베드된 페이지는 원래 접근할 수 없었던 콘텐츠의 정보를 얻을 수 있다는 위협이 존재합니다. API는 미디어의 존재 여부, 유형, 길이, 크기 및 호스트의 성능 특성 등의 정보를 노출합니다. 이러한 정보는 이미 잠재적으로 문제가 될 수 있지만, 실제로는 img 요소를 사용하여 거의 동일한 정보를 얻을 수 있기 때문에 수용 가능한 것으로 간주되었습니다.

그러나, 사용자 에이전트가 콘텐츠 내의 메타데이터(예: 자막)를 추가로 노출하면 훨씬 더 민감한 정보를 얻을 수 있습니다. 따라서 이러한 정보는 비디오 리소스가 CORS를 사용하는 경우에만 노출됩니다. crossorigin 속성을 통해 작성자는 CORS를 활성화할 수 있습니다. [FETCH]

이 제한이 없다면, 공격자는 사용자를 속여 회사 네트워크 내에서 유출된 위치에서 비디오를 로드하려고 시도하는 사이트를 방문하게 할 수 있습니다. 해당 비디오에 새로운 제품의 기밀 계획이 포함된 자막이 있다면, 자막을 읽을 수 있게 되는 것은 심각한 기밀 유출을 초래할 수 있습니다.

4.8.11.18 미디어 요소를 사용하는 작성자를 위한 모범 사례

이 섹션은 비규범적입니다.

셋톱박스나 모바일 폰과 같은 소형 기기에서 오디오 및 비디오 리소스를 재생하는 것은 종종 기기의 제한된 하드웨어 자원으로 인해 제약을 받습니다. 예를 들어, 어떤 기기는 세 개의 동시 비디오만 지원할 수 있습니다. 이러한 이유로, 미디어 요소가 재생을 마쳤을 때, 요소에 대한 모든 참조를 제거하여 요소가 가비지 수집될 수 있도록 하거나, 더 나은 방법으로는 요소의 src 속성을 빈 문자열로 설정하여 리소스를 해제하는 것이 좋은 습관입니다. srcObject가 설정된 경우, srcObject를 null로 설정하십시오.

마찬가지로, 재생 속도가 정확히 1.0이 아닐 때, 하드웨어, 소프트웨어 또는 포맷의 제한으로 인해 비디오 프레임이 드롭되거나 오디오가 끊기거나 음소거될 수 있습니다.

4.8.11.19 미디어 요소 구현자를 위한 모범 사례

이 섹션은 비규범적입니다.

미디어 요소 API의 다양한 측면이 얼마나 정확하게 구현되는지는 구현 품질 문제로 간주됩니다.

예를 들어, buffered 속성을 구현할 때, 버퍼된 범위의 정확성을 보고하는 방법은 사용자 에이전트가 데이터를 얼마나 신중하게 검사하는지에 따라 달라집니다. API는 범위를 시간으로 보고하지만, 데이터는 바이트 스트림으로 얻어지므로, 가변 비트레이트 스트림을 수신하는 사용자 에이전트는 모든 데이터를 실제로 디코딩해야만 정확한 시간을 결정할 수 있을 수도 있습니다. 그러나 사용자 에이전트가 이를 반드시 수행해야 하는 것은 아니며, 대신 지금까지 관찰된 평균 비트레이트를 기반으로 한 추정치를 반환하고 더 많은 정보가 제공되면 이를 수정할 수 있습니다.

일반적으로 사용자 에이전트는 낙관적이기보다는 보수적인 태도를 취할 것을 권장합니다. 예를 들어, 모든 것이 버퍼링되었음을 보고했지만 실제로는 그렇지 않은 경우, 이는 좋지 않습니다.

또 다른 구현 품질 문제는 코덱이 전방 재생만을 위해 설계된 경우(예: 키 프레임이 많지 않고, 이들이 멀리 떨어져 있으며, 중간 프레임은 이전 프레임에서의 델타만 포함) 비디오를 역방향으로 재생하는 것입니다. 사용자 에이전트는 예를 들어 키 프레임만 보여주는 등의 저품질 작업을 수행할 수 있지만, 더 나은 구현은 실제로 비디오의 일부를 전방으로 디코딩하고, 전체 프레임을 저장한 후 프레임을 역방향으로 재생하는 등 더 많은 작업을 수행할 것입니다.

마찬가지로, 구현은 언제든지 버퍼된 데이터를 삭제할 수 있으며(미디어 요소의 수명 동안 모든 미디어 데이터를 유지할 필요는 없음), 이것도 다시 구현 품질 문제입니다. 충분한 자원을 가진 사용자 에이전트는 가능한 모든 데이터를 유지하여 더 나은 사용자 경험을 제공할 것을 권장합니다. 예를 들어, 사용자가 라이브 스트림을 시청하는 경우, 사용자 에이전트는 사용자에게 라이브 비디오만 볼 수 있도록 할 수 있지만, 더 나은 사용자 에이전트는 모든 것을 버퍼링하여 사용자가 이전 자료를 탐색하고, 일시 정지하고, 앞뒤로 재생하는 등의 기능을 허용할 것입니다.


일시 정지된 미디어 요소가 문서에서 제거되고 다음에 이벤트 루프1단계에 도달하기 전에 다시 삽입되지 않는 경우, 자원이 제한된 구현은 그 기회를 이용하여 미디어 요소가 사용하는 모든 하드웨어 자원(예: 비디오 평면, 네트워크 자원 및 데이터 버퍼)을 해제하는 것이 좋습니다. (사용자 에이전트는 나중에 재생이 다시 시작될 경우를 대비해 재생 위치 등을 계속 추적해야 합니다.)

4.8.12 map 요소

Element/map

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (레거시)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLMapElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
명시적 콘텐츠.
이 요소가 사용될 수 있는 문맥:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
투명.
text/html에서 태그 생략:
태그를 생략할 수 없음.
콘텐츠 속성:
전역 속성
name이미지 맵의 이름을 정의하여 usemap 속성에서 참조할 수 있음.
접근성 고려사항:
작성자를 위한 안내.
구현자를 위한 안내.
DOM 인터페이스:
[Exposed=Window]
        interface HTMLMapElement : HTMLElement {
          [HTMLConstructor] constructor();
        
          [CEReactions] attribute DOMString name;
          [SameObject] readonly attribute HTMLCollection areas;
        };

map 요소는 img 요소 및 area 요소와 결합하여 이미지 맵을 정의합니다. 이 요소는 자식 요소를 대표합니다.

name 속성은 맵에 이름을 부여하여 참조할 수 있도록 합니다. 이 속성은 존재해야 하며 ASCII 공백이 없는 비어 있지 않은 값을 가져야 합니다. name 속성의 값은 동일한 name 속성을 가진 다른 map 요소와 같아서는 안 됩니다. 트리 내에서 id 속성도 지정된 경우, 두 속성의 값이 같아야 합니다.

map.areas

HTMLCollection을 반환하며, 이 컬렉션은 area 요소들로 구성됩니다.

areas 속성은 HTMLCollection을 반환하며, 이 컬렉션은 map 요소에서 루팅되고 필터는 오직 area 요소들만을 일치시킵니다.

IDL 속성 name은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

이미지 맵은 페이지의 다른 콘텐츠와 결합하여 정의될 수 있으며, 유지 관리를 용이하게 합니다. 이 예시는 페이지 상단에 이미지 맵이 있고 하단에 해당 텍스트 링크 세트가 있는 페이지의 예입니다.

<!DOCTYPE HTML>
<HTML LANG="EN">
<TITLE>Babies™: Toys</TITLE>
<HEADER>
 <H1>Toys</H1>
 <IMG SRC="/images/menu.gif"
      ALT="Babies™ navigation menu. Select a department to go to its page."
      USEMAP="#NAV">
</HEADER>
 ...
<FOOTER>
 <MAP NAME="NAV">
  <P>
   <A HREF="/clothes/">Clothes</A>
   <AREA ALT="Clothes" COORDS="0,0,100,50" HREF="/clothes/"> |
   <A HREF="/toys/">Toys</A>
   <AREA ALT="Toys" COORDS="100,0,200,50" HREF="/toys/"> |
   <A HREF="/food/">Food</A>
   <AREA ALT="Food" COORDS="200,0,300,50" HREF="/food/"> |
   <A HREF="/books/">Books</A>
   <AREA ALT="Books" COORDS="300,0,400,50" HREF="/books/">
  </P>
 </MAP>
</FOOTER>

4.8.13 area 요소

Element/area

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLAreaElement

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
흐름 콘텐츠.
구 콘텐츠.
이 요소가 사용할 수 있는 컨텍스트:
어디에서 구 콘텐츠가 예상됩니다. 하지만 map 요소 조상이 있는 경우에만 그렇습니다.
콘텐츠 모델:
없음.
text/html에서의 태그 생략:
아니요 종료 태그.
콘텐츠 속성:
전역 속성
alt — 이미지가 없을 때 사용할 대체 텍스트
coords — 이미지 맵에서 생성할 모양의 좌표
shape — 이미지 맵에서 생성할 모양의 종류
href — 하이퍼링크의 주소
target네비게이션 하이퍼링크 내비게이션에 대한
download — 리소스를 탐색하는 대신 다운로드할지 여부와 파일 이름이 그럴 경우
pingURL을 ping하기 위해
rel — 하이퍼링크가 포함된 문서 위치와 대상 리소스 사이의 관계
referrerpolicy리퍼러 정책은 요소에 의해 시작된 가져오기에 대한
접근성 고려 사항:
요소에 href 속성이 있는 경우: 저자를 위해; 구현자를 위해.
그렇지 않으면: 저자를 위해; 구현자를 위해.
DOM 인터페이스:
[Exposed=Window]
interface HTMLAreaElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] 속성 DOMString alt;
  [CEReactions] 속성 DOMString coords;
  [CEReactions] 속성 DOMString shape;
  [CEReactions] 속성 DOMString target;
  [CEReactions] 속성 DOMString download;
  [CEReactions] 속성 USVString ping;
  [CEReactions] 속성 DOMString rel;
  [SameObject, PutForwards=value] 읽기 전용 속성 DOMTokenList relList;
  [CEReactions] 속성 DOMString referrerPolicy;

  // 이전 멤버도 포함됩니다
};
HTMLAreaElement 포함합니다 HTMLHyperlinkElementUtils;

area 요소는 하이퍼링크를 사용하여 이미지 맵에서 지정된 영역과 연결된 텍스트를 나타내거나 이미지 맵에서 선택할 수 없는 영역을 나타냅니다.

부모 노드를 가진 area 요소는 map 요소의 조상을 가져야 합니다.

area 요소에 href 속성이 있는 경우, area 요소는 하이퍼링크를 나타냅니다. 이 경우 alt 속성이 있어야 합니다. 이 속성은 하이퍼링크의 텍스트를 지정합니다. 그 값은 이미지 자체가 아닌 다른 하이퍼링크의 텍스트 및 이미지의 대체 텍스트와 함께 제공될 때 하이퍼링크가 텍스트 없이 이미지에 적용된 모양으로 사용할 때와 동일한 종류의 선택을 사용자에게 제공하는 텍스트여야 합니다. alt 속성은 동일한 리소스를 가리키며 비어 있지 않은 alt 속성이 있는 동일한 이미지 맵의 다른 area 요소가 있는 경우 비워 둘 수 있습니다.

area 요소에 href 속성이 없는 경우 요소가 나타내는 영역을 선택할 수 없으며, alt 속성은 생략되어야 합니다.

두 경우 모두 shapecoords 속성은 영역을 지정합니다.

shape 속성은 다음 키워드와 상태를 가진 열거형 속성입니다:

키워드 준수 상태 간단한 설명
circle 원 상태 정확히 세 개의 정수를 사용하여 coords 속성에 원을 지정합니다.
circ 아니요
default 기본 상태 이 영역은 전체 이미지입니다. (coords 속성은 사용되지 않습니다.)
poly 다각형 상태 적어도 여섯 개의 정수를 사용하여 coords 속성에 다각형을 지정합니다.
polygon 아니요
rect 사각형 상태 정확히 네 개의 정수를 사용하여 coords 속성에 사각형을 지정합니다.
rectangle 아니요

속성의 누락된 값 기본값잘못된 값 기본값은 모두 사각형 상태입니다.

coords 속성은 지정된 경우 유효한 부동 소수점 수 목록을 포함해야 합니다. 이 속성은 shape 속성에 의해 설명된 모양의 좌표를 제공합니다. 이 속성의 처리는 이미지 맵 처리 모델의 일부로 설명됩니다.

원 상태에서, area 요소는 coords 속성이 있어야 하며, 세 개의 정수를 포함해야 하며, 마지막 정수는 음수가 아니어야 합니다. 첫 번째 정수는 이미지의 왼쪽 가장자리에서 원의 중심까지의 거리이며, 두 번째 정수는 이미지의 상단 가장자리에서 원의 중심까지의 거리여야 하며, 세 번째 정수는 다시 CSS 픽셀로 반경을 나타내야 합니다.

기본 상태에서, area 요소에는 coords 속성이 없어야 합니다. (이 영역은 전체 이미지입니다.)

다각형 상태에서, area 요소에는 적어도 여섯 개의 정수가 포함된 coords 속성이 있어야 하며, 정수의 개수는 짝수여야 합니다. 각 정수 쌍은 각각 이미지의 왼쪽 및 상단에서 CSS 픽셀로 측정한 거리를 나타내야 하며, 모든 좌표는 순서대로 다각형의 점을 나타내야 합니다.

사각형 상태에서, area 요소는 정확히 네 개의 정수를 포함한 coords 속성이 있어야 하며, 첫 번째 정수는 세 번째 정수보다 작아야 하며, 두 번째 정수는 네 번째 정수보다 작아야 합니다. 네 개의 점은 각각 이미지의 왼쪽 가장자리에서 사각형의 왼쪽 면까지의 거리, 상단 가장자리에서 상단 면까지의 거리, 왼쪽 가장자리에서 오른쪽 면까지의 거리, 상단 가장자리에서 하단 면까지의 거리를 나타내야 합니다. 이 모두는 CSS 픽셀로 측정됩니다.

사용자 에이전트가 사용자가 하이퍼링크를 따라갈 수 있도록 허용할 때 하이퍼링크를 다운로드하거나, href, target, download, ping 속성은 링크가 따라가는 방식을 결정합니다. rel 속성은 사용자가 링크를 따르기 전에 대상 리소스의 성격을 사용자에게 나타내는 데 사용할 수 있습니다.

target, download, ping, rel, 그리고 referrerpolicy 속성은 href 속성이 없는 경우 생략해야 합니다.

속성 itemproparea 요소에 지정된 경우, href 속성도 지정해야 합니다.

HTMLAreaElement/rel

현재 모든 엔진에서 지원됩니다.

Firefox30+Safari9+Chrome54+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

IDL 속성 relListrelList 속성의 내용을 반영해야 합니다.

HTMLAreaElement/referrerPolicy

현재 모든 엔진에서 지원됩니다.

Firefox50+Safari14.1+Chrome52+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

IDL 속성 referrerPolicyreferrerPolicy 속성의 내용을 반영해야 하며, 알려진 값만 제한됩니다.

4.8.14 이미지 맵

4.8.14.1 작성

이미지 맵은 이미지의 기하학적 영역을 하이퍼링크와 연결할 수 있게 합니다.

img 요소 형태의 이미지는 map 요소 형태의 이미지 맵과 연결될 수 있으며, img 요소에 usemap 속성을 지정하여 연결할 수 있습니다. 지정된 경우, usemap 속성은 반드시 map 요소에 대한 유효한 해시 이름 참조이어야 합니다.

다음과 같은 이미지를 고려하십시오:

네 가지 모양이 똑같은 간격으로 배치된 선: 빨간색 속이 빈 상자, 초록색 원, 파란색 삼각형, 노란색 네모난 별.

색깔이 있는 영역만 클릭 가능하도록 하려면 다음과 같이 할 수 있습니다:

<p>
 선택할 모양을 선택하십시오:
 <img src="shapes.png" usemap="#shapes"
      alt="네 가지 모양이 있습니다: 빨간색 속이 빈 상자, 초록색 원, 파란색 삼각형, 노란색 네모난 별.">
 <map name="shapes">
  <area shape=rect coords="50,50,100,100"> <!-- 빨간 상자의 구멍 -->
  <area shape=rect coords="25,25,125,125" href="red.html" alt="빨간 상자.">
  <area shape=circle coords="200,75,50" href="green.html" alt="초록 원.">
  <area shape=poly coords="325,25,262,125,388,125" href="blue.html" alt="파란 삼각형.">
  <area shape=poly coords="450,25,435,60,400,75,435,90,450,125,465,90,500,75,465,60"
        href="yellow.html" alt="노란 별.">
 </map>
</p>
4.8.14.2 처리 모델

img 요소에 usemap 속성이 지정된 경우, 사용자 에이전트는 다음과 같이 처리해야 합니다:

  1. 해시 이름 참조를 해시 이름 참조 구문 분석 규칙을 사용하여 구문 분석합니다. 이는 map 요소를 컨텍스트 노드로 사용하여 구문 분석됩니다. 이 과정에서 요소(즉, map) 또는 null이 반환됩니다.

  2. null이 반환되면, 반환합니다. 결국 이미지는 이미지 맵과 연결되지 않습니다.

  3. 그렇지 않으면, 사용자 에이전트는 map의 하위 요소인 모든 area 요소들을 수집해야 합니다. 이를 areas라고 합니다.

이미지 맵(areas)을 형성하는 area 요소 목록을 얻은 후, 상호작용이 가능한 사용자 에이전트는 두 가지 방법 중 하나로 목록을 처리해야 합니다.

사용자 에이전트가 img 요소가 나타내는 텍스트를 표시하려는 경우, 다음 단계를 사용해야 합니다.

  1. areas에서 area 요소 중 href 속성이 없는 모든 요소를 제거합니다.

  2. areas에서 area 요소 중 alt 속성이 없거나 alt 속성의 값이 빈 문자열인 모든 요소를 제거합니다. 단, areas 내에 동일한 href 속성 값을 가진 다른 요소가 있고 해당 요소에 빈 문자열이 아닌 alt 속성이 있을 경우에 한합니다.

  3. areas 내 남아있는 각 area 요소는 하이퍼링크를 나타냅니다. 이 하이퍼링크들은 모두 img의 텍스트와 연관된 방식으로 사용자에게 제공되어야 합니다.

    이 맥락에서 사용자 에이전트는 지정되지 않은 areaimg 요소, 또는 alt 속성이 빈 문자열이거나 다른 비가시적 텍스트인 요소를 구현 정의된 방식으로 표현할 수 있습니다.

사용자 에이전트가 이미지를 표시하고 상호작용을 통해 하이퍼링크를 선택하도록 허용하려는 경우, 이미지는 areas에서 가져온 레이어 모양 집합과 연결되어야 하며, 트리 순서의 반대 순서로 처리됩니다 (따라서 map에서 마지막으로 지정된 area 요소는 가장 아래의 모양이며, 트리 순서에서 map의 첫 번째 요소는 가장 위에 있는 모양입니다).

areas의 각 area 요소는 이미지를 레이어로 처리하기 위해 다음과 같이 처리해야 합니다:

  1. 요소의 shape 속성이 나타내는 상태를 찾습니다.

  2. 요소의 coords 속성을 구문 분석하여 coords 목록을 얻습니다. 이 속성이 없으면 coords 목록은 비어있는 목록이 됩니다.

  3. coords 목록의 항목 수가 아래 표에 명시된 최소 수보다 적으면, 모양이 비어있다고 간주하고 반환합니다.

    상태 최소 항목 수
    원 상태 3
    기본 상태 0
    다각형 상태 6
    사각형 상태 4
  4. 해당 상태와 관련된 다음 목록 항목에 따라 coords 목록의 초과 항목을 확인합니다.

    원 상태
    목록의 세 번째 항목 이후의 항목은 삭제하십시오.
    기본 상태
    목록의 모든 항목을 삭제하십시오.
    다각형 상태
    목록에 항목이 홀수 개일 경우 마지막 항목을 삭제하십시오.
    사각형 상태
    목록의 네 번째 항목 이후의 항목을 삭제하십시오.
  5. 요소의 shape 속성이 사각형 상태를 나타내며, 목록의 첫 번째 숫자가 세 번째 숫자보다 크면, 두 숫자를 서로 바꿉니다.

  6. 요소의 shape 속성이 사각형 상태를 나타내며, 목록의 두 번째 숫자가 네 번째 숫자보다 크면, 두 숫자를 서로 바꿉니다.

  7. 요소의 shape 속성이 원 상태를 나타내며, 목록의 세 번째 숫자가 0 이하이면, 모양이 비어있다고 간주하고 반환합니다.

  8. 이제, 요소가 나타내는 모양은 아래 목록의 해당 상태에 대한 설명과 일치합니다:

    원 상태

    xcoords의 첫 번째 숫자이고, y는 두 번째 숫자이며, r은 세 번째 숫자입니다.

    이 모양은 이미지의 왼쪽 가장자리에서 x CSS 픽셀만큼 떨어진 지점과 이미지의 상단 가장자리에서 y CSS 픽셀만큼 떨어진 지점에 중심이 있으며, 반지름은 r CSS 픽셀입니다.

    기본 상태

    이 모양은 이미지 전체를 정확히 덮는 사각형입니다.

    다각형 상태

    xicoords(2i)번째 항목이며, yi(2i+1)번째 항목입니다 (coords의 첫 번째 항목의 인덱스는 0입니다).

    좌표CSS 픽셀 단위로 이미지의 왼쪽 상단에서 측정된 (xi, yi)의 형태로 해석됩니다. coords의 항목 수는 (N/2)-1이며, 여기서 Ncoords에 있는 항목의 수입니다.

    이 모양은 좌표에 의해 정의된 꼭지점을 가진 다각형이며, 내부는 홀짝 규칙을 사용하여 결정됩니다. [GRAPHICS]

    사각형 상태

    x1coords의 첫 번째 숫자이고, y1은 두 번째 숫자이며, x2는 세 번째 숫자이고, y2는 네 번째 숫자입니다.

    이 모양은 (x1, y1) 좌표에 있는 사각형의 왼쪽 상단 모서리와 (x2, y2) 좌표에 있는 사각형의 오른쪽 하단 모서리로 구성된 사각형입니다. 이 좌표들은 이미지의 왼쪽 상단 모서리에서 측정된 CSS 픽셀 단위로 해석됩니다.

    역사적인 이유로, 좌표는 CSS 'width''height' 속성에 의해 발생하는 모든 확장을 적용한 후의 표시된 이미지에 상대적으로 해석되어야 합니다 (또는, CSS 브라우저가 아닌 경우, 이미지 요소의 widthheight 속성 — CSS 브라우저는 해당 속성을 앞서 언급한 CSS 속성에 매핑합니다).

    브라우저 확대 기능 및 CSS 또는 SVG를 사용하여 적용된 변환은 좌표에 영향을 미치지 않습니다.

위의 알고리즘에 따라 레이어된 모양 집합과 연결된 이미지와 포인팅 장치 상호작용은 해당 지점을 가리킨 포인팅 장치가 있는 경우 해당 지점에 있는 최상위 모양에 첫 번째로 사용자 상호작용 이벤트를 발생시키고, 지점에 모양이 없는 경우 이미지 요소 자체에 이벤트를 발생시켜야 합니다. 사용자 에이전트는 또한 하이퍼링크를 나타내는 개별 area 요소를 선택하고 활성화할 수 있도록 허용할 수 있습니다 (예: 키보드를 사용하여).

map 요소(및 그 하위 요소인 area 요소들)는 여러 img 요소와 연결될 수 있기 때문에, 하나의 area 요소가 문서의 여러 포커스 가능한 영역에 해당할 수 있습니다.

이미지 맵은 라이브입니다. 따라서 DOM이 변경되면, 사용자 에이전트는 이미지 맵에 대한 알고리즘을 다시 실행한 것처럼 행동해야 합니다.

4.8.15 MathML

HTML/HTML5/HTML5_Parser#Inline_SVG_and_MathML_support

모든 현재 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome7+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android5+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12+

MathML math 요소는 이 명세서의 콘텐츠 모델을 위해 포함된 콘텐츠, 구문 콘텐츠, 흐름 콘텐츠명확한 콘텐츠 범주에 속합니다.

MathML annotation-xml 요소가 HTML 네임스페이스의 요소를 포함하는 경우, 그러한 요소는 모두 흐름 콘텐츠여야 합니다.

MathML 토큰 요소(mi, mo, mn, ms, 및 mtext) 이 HTML 요소의 하위 요소일 때, HTML 네임스페이스에서 구문 콘텐츠 요소를 포함할 수 있습니다.

MathML 콘텐츠 모델이 직문자를 허용하지 않는 MathML 요소에서 발견된 요소 간 공백이 아닌 텍스트를 MathML 콘텐츠 모델, 레이아웃 및 렌더링 목적으로 해당 텍스트가 실제로 MathML mtext 요소로 래핑된 것처럼 처리해야 합니다. (그러나 이러한 텍스트는 규격에 맞지 않습니다.)

콘텐츠가 요소의 콘텐츠 모델과 일치하지 않는 MathML 요소는 MathML 레이아웃 및 렌더링 목적으로 MathML merror 요소로 대체된 것처럼 작동해야 하며, 적절한 오류 메시지를 포함해야 합니다.

MathML 요소의 의미론은 MathML다른 적용 가능한 명세서에 의해 정의됩니다. [MATHML]

HTML 문서에서 MathML을 사용하는 예는 다음과 같습니다:

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>The quadratic formula</title>
 </head>
 <body>
  <h1>The quadratic formula</h1>
  <p>
   <math>
    <mi>x</mi>
    <mo>=</mo>
    <mfrac>
     <mrow>
      <mo form="prefix"></mo> <mi>b</mi>
      <mo>±</mo>
      <msqrt>
       <msup> <mi>b</mi> <mn>2</mn> </msup>
       <mo></mo>
       <mn>4</mn> <mo></mo> <mi>a</mi> <mo></mo> <mi>c</mi>
      </msqrt>
     </mrow>
     <mrow>
      <mn>2</mn> <mo></mo> <mi>a</mi>
     </mrow>
    </mfrac>
   </math>
  </p>
 </body>
</html>

4.8.16 SVG

HTML/HTML5/HTML5_Parser#Inline_SVG_and_MathML_support

모든 현재 엔진에서 지원됨.

Firefox37+Safari11.1+Chrome7+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android37+Safari iOS11.3+Chrome Android18+WebView Android4.4+Samsung Internet4+Opera Android15+

SVG svg 요소는 이 명세서의 콘텐츠 모델에서 포함된 콘텐츠, 구문 콘텐츠, 흐름 콘텐츠, 명확한 콘텐츠 범주에 속합니다.

SVG foreignObject 요소가 HTML 네임스페이스의 요소를 포함하는 경우, 그러한 요소는 모두 흐름 콘텐츠여야 합니다.

SVG title 요소의 HTML 문서 내 콘텐츠 모델은 구문 콘텐츠입니다. (이는 SVG 2에서 제시된 요구 사항을 추가로 제한합니다.)

SVG 요소의 의미론은 SVG 2다른 적용 가능한 명세서에 의해 정의됩니다. [SVG]


doc = iframe.getSVGDocument()
doc = embed.getSVGDocument()
doc = object.getSVGDocument()

document(Document) 객체를 반환하며, iframe, embed 또는 object 요소를 사용하여 SVG를 포함하는 경우에 해당됩니다.

getSVGDocument() 메서드의 단계는 다음과 같습니다:

  1. documentthis콘텐츠 문서로 설정합니다.

  2. 만약 document가 null이 아니며, XML 파일의 페이지 로드 처리 모델 섹션에 따라 생성된 경우, 리소스의 계산된 유형image/svg+xml이므로, document를 반환합니다.

  3. null을 반환합니다.

4.8.17 크기 속성

작성자 요구사항: img, iframe, embed, object, video, source 요소에 대한 widthheight 속성은 부모가 picture 요소인 경우, type 속성이 이미지 버튼 상태일 때 input 요소는 요소의 시각적 콘텐츠의 크기(출력 매체의 명목상 방향에 상대적인 너비와 높이)를 지정할 수 있습니다. 지정된 속성이 있는 경우, 이 속성들은 CSS 픽셀로 유효한 음수가 아닌 정수 값이어야 합니다.

지정된 크기는 리소스 자체에 지정된 크기와 다를 수 있으며, 리소스의 해상도가 CSS 픽셀 해상도와 다를 수 있기 때문입니다. (화면에서는 CSS 픽셀 해상도가 96ppi이지만, 일반적으로 CSS 픽셀 해상도는 읽기 거리와 관련이 있습니다.) 두 속성이 모두 지정된 경우, 다음 문장 중 하나가 참이어야 합니다:

대상 비율은 리소스의 자연 너비자연 높이의 비율입니다. 지정된 너비지정된 높이는 각각 widthheight 속성의 값입니다.

해당 리소스에 자연 너비자연 높이가 모두 없는 경우 이 두 속성은 생략되어야 합니다.

두 속성이 모두 0인 경우, 이는 요소가 사용자를 대상으로 하지 않는다는 것을 나타냅니다(예: 페이지 조회수를 계산하는 서비스의 일부일 수 있음).

크기 속성은 이미지를 늘리는 데 사용되지 않도록 해야 합니다.

사용자 에이전트 요구사항: 사용자 에이전트는 이러한 속성을 렌더링에 대한 힌트로 사용해야 합니다.

HTMLObjectElement/width

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLObjectElement/height

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

widthheight IDL 속성은 iframe, embed, object, source, video 요소의 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다.

iframe, embedobject의 IDL 속성은 DOMString이며, videosource의 IDL 속성은 unsigned long입니다.

imginput 요소에 해당하는 IDL 속성은 해당 요소의 다른 동작과 더 밀접하게 관련되어 있으므로 각 요소의 섹션에서 정의됩니다.

4.9 표 형식 데이터

4.9.1 table 요소

요소/table

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTableElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
실체 콘텐츠.
이 요소를 사용할 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
이 순서대로: 선택적으로 caption 요소, 그 뒤에 0개 이상의 colgroup 요소, 그 뒤에 선택적으로 thead 요소, 그 뒤에 0개 이상의 tbody 요소 또는 1개 이상의 tr 요소, 그 뒤에 선택적으로 tfoot 요소, 선택적으로 1개 이상의 스크립트 지원 요소와 혼합되어 사용될 수 있음.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTableElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute HTMLTableCaptionElement? caption;
  HTMLTableCaptionElement createCaption();
  [CEReactions] undefined deleteCaption();

  [CEReactions] attribute HTMLTableSectionElement? tHead;
  HTMLTableSectionElement createTHead();
  [CEReactions] undefined deleteTHead();

  [CEReactions] attribute HTMLTableSectionElement? tFoot;
  HTMLTableSectionElement createTFoot();
  [CEReactions] undefined deleteTFoot();

  [SameObject] readonly attribute HTMLCollection tBodies;
  HTMLTableSectionElement createTBody();

  [SameObject] readonly attribute HTMLCollection rows;
  HTMLTableRowElement insertRow(optional long index = -1);
  [CEReactions] undefined deleteRow(long index);

  // also has obsolete members
};

table 요소는 형식으로 2차원 이상의 데이터를 표현합니다.

table 요소는 표 모델에 참여합니다. 표는 자손들에 의해 제공된 행, 열 및 셀을 가집니다. 행과 열은 그리드를 형성하며, 표의 셀은 겹침 없이 해당 그리드를 완전히 덮어야 합니다.

이 적합성 요구사항이 충족되는지 여부를 결정하는 정확한 규칙은 표 모델 설명에 나와 있습니다.

작성자들은 복잡한 표를 해석하는 방법을 설명하는 정보를 제공하는 것이 권장됩니다. 이러한 정보를 제공하는 방법에 대한 지침은 아래에 나와 있습니다.

표는 레이아웃 도구로 사용되어서는 안 됩니다. 역사적으로 일부 웹 작성자들이 HTML의 표를 페이지 레이아웃을 제어하는 방법으로 오용해 왔습니다. 이러한 사용은 비적합하며, 그러한 문서에서 표 데이터를 추출하려는 도구들은 매우 혼란스러운 결과를 얻게 될 것입니다. 특히 스크린 리더와 같은 접근성 도구 사용자들은 레이아웃에 사용된 표로 구성된 페이지를 탐색하기가 매우 어려울 수 있습니다.

레이아웃을 위해 HTML 표를 사용하는 대신 CSS 그리드 레이아웃, CSS 플렉서블 박스 레이아웃("flexbox"), CSS 다중 열 레이아웃, CSS 포지셔닝, CSS 표 모델 등 다양한 대안이 있습니다. [CSS]


표는 이해하고 탐색하기 어렵습니다. 사용자가 이를 돕기 위해, 사용자 에이전트는 해당 표가 (비적합한) 레이아웃 표로 분류되지 않은 이상, 표의 셀들을 명확하게 구분해야 합니다.

작성자와 구현자는 아래에 설명된 표 설계 기술 중 일부를 사용하여 사용자가 표를 더 쉽게 탐색할 수 있도록 고려하는 것이 좋습니다.

특히 임의의 콘텐츠에서 표 분석을 수행하는 사용자 에이전트는 실제 데이터를 포함하는 표와 단순히 레이아웃에 사용되는 표를 구별하는 휴리스틱을 찾는 것이 좋습니다. 이 명세에서는 정확한 휴리스틱을 정의하지 않지만, 다음과 같은 것이 가능한 지표로 제안됩니다:

특징 지표
role 속성에 presentation 값을 사용하는 경우 아마도 레이아웃 표일 가능성이 높습니다.
비적합한 값 0을 가진 border 속성을 사용하는 경우 아마도 레이아웃 표일 가능성이 높습니다.
값 0을 가진 비적합한 cellspacingcellpadding 속성을 사용하는 경우 아마도 레이아웃 표일 가능성이 높습니다.
caption, thead 또는 th 요소를 사용하는 경우 아마도 레이아웃 표가 아닐 가능성이 높습니다.
headersscope 속성을 사용하는 경우 아마도 레이아웃 표가 아닐 가능성이 높습니다.
값이 0이 아닌 비적합한 border 속성을 사용하는 경우 아마도 레이아웃 표가 아닐 가능성이 높습니다.
CSS를 사용해 명시적으로 표시된 테두리를 사용하는 경우 아마도 레이아웃 표가 아닐 가능성이 높습니다.
summary 속성을 사용하는 경우 좋은 지표가 아님 (역사적으로 레이아웃 표와 비레이아웃 표 모두 이 속성을 가졌습니다.)

위의 제안이 잘못되었을 가능성도 있습니다. 구현자들은 레이아웃 표 탐지 휴리스틱을 만들려고 시도한 경험을 바탕으로 피드백을 제공할 것을 권장합니다.

만약 table 요소가 (비적합한) summary 속성을 가지고 있고, 사용자 에이전트가 해당 표를 레이아웃 표로 분류하지 않은 경우, 사용자 에이전트는 그 속성의 내용을 사용자에게 보고할 수 있습니다.


table.caption [ = value ]

HTMLTableElement/caption

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블의 caption 요소를 반환합니다.

설정하면 caption 요소를 교체합니다.

caption = table.createCaption()

HTMLTableElement/createCaption

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블에 caption 요소가 없으면 새로 생성하고 반환합니다.

table.deleteCaption()

HTMLTableElement/deleteCaption

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블에 caption 요소가 없도록 합니다.

table.tHead [ = value ]

HTMLTableElement/tHead

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블의 thead 요소를 반환합니다.

설정하면 thead 요소를 교체합니다. 새 값이 thead 요소가 아닌 경우, "HierarchyRequestError" DOMException을 던집니다.

thead = table.createTHead()

HTMLTableElement/createTHead

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블에 thead 요소가 없으면 새로 생성하고 반환합니다.

table.deleteTHead()

HTMLTableElement/deleteTHead

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블에 thead 요소가 없도록 합니다.

table.tFoot [ = value ]

HTMLTableElement/tFoot

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블의 tfoot 요소를 반환합니다.

설정하면 tfoot 요소를 교체합니다. 새 값이 tfoot 요소가 아닌 경우, "HierarchyRequestError" DOMException을 던집니다.

tfoot = table.createTFoot()

HTMLTableElement/createTFoot

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블에 tfoot 요소가 없으면 새로 생성하고 반환합니다.

table.deleteTFoot()

HTMLTableElement/deleteTFoot

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블에 tfoot 요소가 없도록 합니다.

table.tBodies

HTMLTableElement/tBodies

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블의 HTMLCollection을 반환합니다.

tbody = table.createTBody()

HTMLTableElement/createTBody

모든 최신 엔진에서 지원됩니다.

Firefox25+Safari6+Chrome20+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

새로운 tbody 요소를 생성하고 테이블에 삽입하며, 이를 반환합니다.

table.rows

HTMLTableElement/rows

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

테이블의 HTMLCollection을 반환합니다.

tr = table.insertRow([ index ])

HTMLTableElement/insertRow

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

tr 요소와 tbody가 필요한 경우, 새로 생성하고 테이블에 삽입하며 이를 반환합니다.

위치는 테이블의 행을 기준으로 합니다. 인덱스 −1은 기본값이며, 인수 없이 호출할 경우 테이블 끝에 삽입하는 것과 동일합니다.

지정된 위치가 −1보다 작거나 행의 수보다 클 경우, "IndexSizeError" DOMException을 던집니다.

table.deleteRow(index)

HTMLTableElement/deleteRow

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

지정된 위치에 있는 tr 요소를 테이블에서 제거합니다.

위치는 테이블의 행을 기준으로 합니다. 인덱스 −1은 테이블의 마지막 행을 삭제하는 것과 동일합니다.

지정된 위치가 −1보다 작거나 마지막 행의 인덱스보다 클 경우, 또는 행이 없을 경우 "IndexSizeError" DOMException을 던집니다.

다음의 모든 속성 및 메서드 정의에서 요소가 table-created되어야 하는 경우, 이는 table 요소의 node document, 주어진 로컬 이름, 및 HTML namespace를 사용하여 요소를 생성하는 것을 의미합니다.

caption IDL 속성은 table 요소의 첫 번째 caption 자식 요소를 반환해야 하며, 그렇지 않으면 null을 반환해야 합니다. 설정할 때, table 요소의 첫 번째 caption 자식 요소를 제거해야 하며, 새로운 값이 null이 아닌 경우 첫 번째 노드로 삽입해야 합니다.

createCaption() 메서드는 table 요소의 첫 번째 caption 자식 요소를 반환해야 하며, 그렇지 않으면 새로운 caption 요소를 table-created하고, table 요소의 첫 번째 노드로 삽입한 다음 반환해야 합니다.

deleteCaption() 메서드는 table 요소의 첫 번째 caption 자식 요소를 제거해야 합니다.

tHead IDL 속성은 table 요소의 첫 번째 thead 자식 요소를 반환해야 하며, 그렇지 않으면 null을 반환해야 합니다. 설정할 때, 새로운 값이 null이거나 thead 요소인 경우 table 요소의 첫 번째 thead 자식 요소를 제거해야 하며, 새로운 값이 null이 아니면 table 요소에서 caption 요소나 colgroup 요소가 아닌 첫 번째 요소 앞에 삽입해야 하며, 그런 요소가 없다면 테이블의 끝에 삽입해야 합니다. 새로운 값이 null이거나 thead 요소가 아닌 경우, "HierarchyRequestError" DOMException을 던져야 합니다.

createTHead() 메서드는 table 요소의 첫 번째 thead 자식 요소를 반환해야 하며, 그렇지 않으면 새로운 thead 요소를 table-created하고, table 요소에서 caption 요소나 colgroup 요소가 아닌 첫 번째 요소 앞에 삽입해야 하며, 그런 요소가 없다면 테이블의 끝에 삽입한 다음 그 요소를 반환해야 합니다.

deleteTHead() 메서드는 table 요소의 첫 번째 thead 자식 요소를 제거해야 합니다.

tFoot IDL 속성은 table 요소의 첫 번째 tfoot 자식 요소를 반환해야 하며, 그렇지 않으면 null을 반환해야 합니다. 설정할 때, 새로운 값이 null이거나 tfoot 요소인 경우 table 요소의 첫 번째 tfoot 자식 요소를 제거해야 하며, 새로운 값이 null이 아닌 경우 테이블 끝에 삽입해야 합니다. 새로운 값이 null이거나 tfoot 요소가 아닌 경우, "HierarchyRequestError" DOMException을 던져야 합니다.

createTFoot() 메서드는 table 요소의 첫 번째 tfoot 자식 요소를 반환해야 하며, 그렇지 않으면 새로운 tfoot 요소를 table-created하고 테이블의 끝에 삽입한 다음 그 요소를 반환해야 합니다.

deleteTFoot() 메서드는 table 요소의 첫 번째 tfoot 자식 요소를 제거해야 합니다.

tBodies 속성은 table 노드를 기준으로 필터가 tbody 요소에만 일치하는 HTMLCollection을 반환해야 합니다.

createTBody() 메서드는 새로운 tbody 요소를 table-create하고, table 요소의 마지막 tbody 자식 요소 다음에 삽입하거나, table 요소에 tbody 자식 요소가 없을 경우 테이블의 끝에 삽입해야 하며, 그 다음 새 요소를 반환해야 합니다.

rows 속성은 table 노드를 기준으로 필터가 tr 요소에만 일치하는 HTMLCollection을 반환해야 하며, 이 요소들은 thead의 자식인 요소가 먼저 포함되고, table 또는 tbody 요소의 자식인 요소가 그 다음으로 포함되며, 마지막으로 tfoot의 자식인 요소가 포함되어야 합니다.

insertRow(index) 메서드의 동작은 테이블의 상태에 따라 달라집니다. 호출될 때 메서드는 테이블의 상태와 index 인수를 설명하는 다음 조건 목록에서 요구되는 첫 번째 항목을 수행해야 합니다:

인덱스가 −1보다 작거나 rows 컬렉션에 있는 요소의 개수보다 큰 경우:
메서드는 "IndexSizeError" DOMException을 던져야 합니다.
rows 컬렉션에 요소가 하나도 없고 tabletbody 요소가 없는 경우:
메서드는 tbody 요소를 table-create한 다음, tr 요소를 table-create하고, tr 요소를 tbody 요소에 추가한 후, tbody 요소를 table 요소에 추가하고, 마지막으로 tr 요소를 반환해야 합니다.
rows 컬렉션에 요소가 하나도 없는 경우:
메서드는 tr 요소를 table-create하고, 마지막 tbody 요소에 추가한 후 tr 요소를 반환해야 합니다.
인덱스가 −1이거나 rows 컬렉션의 항목 개수와 같은 경우:
메서드는 tr 요소를 table-create하고, rows 컬렉션에서 마지막 tr 요소의 부모에 추가해야 하며, 그런 다음 새로 생성된 tr 요소를 반환해야 합니다.
그 외의 경우:
메서드는 tr 요소를 table-create하고, rows 컬렉션에서 index번째 tr 요소 바로 앞에 삽입한 후 새로 생성된 tr 요소를 반환해야 합니다.

deleteRow(index) 메서드가 호출될 때, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. index가 -1보다 작거나 rows 컬렉션에 있는 요소 수보다 크거나 같으면, "IndexSizeError" DOMException을 던져야 합니다.

  2. index가 -1인 경우, rows 컬렉션에서 마지막 요소를 제거하거나, rows 컬렉션이 비어 있는 경우 아무 작업도 하지 않아야 합니다.

  3. 그렇지 않은 경우, index 번째 요소를 rows 컬렉션에서 제거해야 합니다.

여기 수수께끼 퍼즐을 마크업하는 테이블 사용 예가 있습니다. 이러한 테이블에는 헤더가 필요하지 않음을 확인하십시오.

<style>
 #sudoku { border-collapse: collapse; border: solid thick; }
 #sudoku colgroup, table#sudoku tbody { border: solid medium; }
 #sudoku td { border: solid thin; height: 1.4em; width: 1.4em; text-align: center; padding: 0; }
</style>
<h1>Today's Sudoku</h1>
<table id="sudoku">
 <colgroup><col><col><col>
 <colgroup><col><col><col>
 <colgroup><col><col><col>
 <tbody>
  <tr> <td> 1 <td>   <td> 3 <td> 6 <td>   <td> 4 <td> 7 <td>   <td> 9
  <tr> <td>   <td> 2 <td>   <td>   <td> 9 <td>   <td>   <td> 1 <td>
  <tr> <td> 7 <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td> 6
 <tbody>
  <tr> <td> 2 <td>   <td> 4 <td>   <td> 3 <td>   <td> 9 <td>   <td> 8
  <tr> <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td>
  <tr> <td> 5 <td>   <td>   <td> 9 <td>   <td> 7 <td>   <td>   <td> 1
 <tbody>
  <tr> <td> 6 <td>   <td>   <td>   <td> 5 <td>   <td>   <td>   <td> 2
  <tr> <td>   <td>   <td>   <td>   <td> 7 <td>   <td>   <td>   <td>
  <tr> <td> 9 <td>   <td>   <td> 8 <td>   <td> 2 <td>   <td>   <td> 5
</table>
4.9.1.1 테이블 설명 기법

첫 번째 행과 첫 번째 열에 헤더가 있는 셀의 그리드로만 구성된 테이블 이상의 것과, 일반적으로 독자가 내용을 이해하기 어려울 수 있는 테이블의 경우, 작성자는 테이블을 소개하는 설명 정보를 포함해야 합니다. 이 정보는 모든 사용자에게 유용하지만, 특히 테이블을 볼 수 없는 사용자, 예를 들어 화면 판독기 사용자에게 매우 유용합니다.

이러한 설명 정보는 테이블의 목적을 소개하고, 기본적인 셀 구조를 개략적으로 설명하며, 어떤 경향이나 패턴을 강조하고, 일반적으로 사용자가 테이블을 사용하는 방법을 가르쳐야 합니다.

예를 들어, 다음과 같은 테이블이 있습니다:

긍정적 및 부정적인 측면이 있는 특성
부정적 특성 긍정적
슬픔 기분 행복
실패 성적 합격

...이 테이블은 "특성은 두 번째 열에 제공되며, 왼쪽 열에는 부정적인 측면이, 오른쪽 열에는 긍정적인 측면이 있습니다"와 같은 설명이 유용할 수 있습니다.

이 정보를 포함하는 다양한 방법이 있습니다:

테이블을 둘러싼 산문에서
<p>다음 테이블에서는 특성이 두 번째 열에 제공되며, 왼쪽 열에는 부정적인 측면이, 오른쪽 열에는 긍정적인 측면이 있습니다.</p>
<table>
 <caption>긍정적 및 부정적인 측면이 있는 특성</caption>
 <thead>
  <tr>
   <th id="n"> 부정적
   <th> 특성
   <th> 긍정적
 </thead>
  <tr>
   <td headers="n r1"> 슬픔
   <th id="r1"> 기분
   <td> 행복
  </tr>
   <td headers="n r2"> 실패
   <th id="r2"> 성적
   <td> 합격
</table>
테이블의 caption
<table>
 <caption>
  <strong>긍정적 및 부정적인 측면이 있는 특성.</strong>
  <p>특성은 두 번째 열에 제공되며, 왼쪽 열에는 부정적인 측면이, 오른쪽 열에는 긍정적인 측면이 있습니다.</p>
 </caption>
 <thead>
  <tr>
   <th id="n"> 부정적
   <th> 특성
   <th> 긍정적
 </thead>
  <tr>
   <td headers="n r1"> 슬픔
   <th id="r1"> 기분
   <td> 행복
  </tr>
   <td headers="n r2"> 실패
   <th id="r2"> 성적
   <td> 합격
</table>
테이블의 caption에, details 요소 내에서
<table>
 <caption>
  <strong>Characteristics with positive and negative sides.</strong>
  <details>
   <summary>Help</summary>
   <p>Characteristics are given in the second column, with the
   negative side in the left column and the positive side in the right
   column.</p>
  </details>
 </caption>
 <thead>
  <tr>
   <th id="n"> Negative
   <th> Characteristic
   <th> Positive
 <tbody>
  <tr>
   <td headers="n r1"> Sad
   <th id="r1"> Mood
   <td> Happy
  <tr>
   <td headers="n r2"> Failing
   <th id="r2"> Grade
   <td> Passing
</table>
테이블 옆에, 동일한 figure 내에
<figure>
 <figcaption>긍정적 및 부정적인 측면이 있는 특성</figcaption>
 <p>특성은 두 번째 열에 제공되며, 왼쪽 열에는 부정적인 측면이, 오른쪽 열에는 긍정적인 측면이 있습니다.</p>
 <table>
  <thead>
   <tr>
    <th id="n"> 부정적
    <th> 특성
    <th> 긍정적
  </tbody>
   <tr>
    <td headers="n r1"> 슬픔
    <th id="r1"> 기분
    <td> 행복
   </tr>
    <td headers="n r2"> 실패
    <th id="r2"> 성적
    <td> 합격
 </table>
</figure>
테이블 옆에, figurefigcaption 내에
<figure>
 <figcaption>
  <strong>긍정적 및 부정적인 측면이 있는 특성</strong> 
  <p>특성은 두 번째 열에 제공되며, 왼쪽 열에는 부정적인 측면이, 오른쪽 열에는 긍정적인 측면이 있습니다.</p>
 </figcaption>
 <table>
  <thead>
   <tr>
    <th id="n"> 부정적
    <th> 특성
    <th> 긍정적
  </tbody>
   <tr>
    <td headers="n r1"> 슬픔
    <th id="r1"> 기분
    <td> 행복
   </tr>
    <td headers="n r2"> 실패
    <th id="r2"> 성적
    <td> 합격
 </table>
</figure>

작성자는 위의 기법 외에도 적절한 다른 기법이나 기법의 조합을 사용할 수 있습니다.

물론, 테이블이 배치된 방식을 설명하는 설명을 작성하는 것보다, 설명이 필요 없도록 테이블을 조정하는 것이 가장 좋은 방법입니다.

위의 예제에서 사용된 테이블의 경우, 테이블을 간단히 재배치하여 헤더가 상단과 왼쪽에 있도록 하면 설명이 필요 없으며, headers 속성을 사용할 필요도 없습니다:

<table>
 <caption>긍정적 및 부정적인 측면이 있는 특성</caption>
 <thead>
  <tr>
   <th> 특성
   <th> 부정적
   <th> 긍정적
 </thead>
  <tr>
   <th> 기분
   <td> 슬픔
   <td> 행복
  </tr>
   <th> 성적
   <td> 실패
   <td> 합격
</table>
4.9.1.2 테이블 설계를 위한 기법

좋은 테이블 설계는 테이블을 더 읽기 쉽고 사용하기 쉽게 만드는 데 중요한 역할을 합니다.

시각적 매체에서 열과 행 경계를 제공하고 행 배경을 번갈아 가며 사용하는 것은 복잡한 테이블을 더 읽기 쉽게 만드는 데 매우 효과적일 수 있습니다.

대량의 숫자 콘텐츠가 포함된 테이블의 경우, 모노스페이스 폰트를 사용하면 사용자 에이전트가 경계를 렌더링하지 않는 상황에서도 패턴을 쉽게 볼 수 있습니다. (유감스럽게도, 역사적 이유로 테이블의 경계를 렌더링하지 않는 것은 일반적인 기본값입니다.)

음성 매체에서 테이블 셀은 셀의 내용을 읽기 전에 해당 헤더를 보고하여 구분할 수 있으며, 사용자가 테이블의 전체 내용을 소스 순서대로 직렬화하는 대신 그리드 방식으로 테이블을 탐색할 수 있도록 허용합니다.

저자들은 이러한 효과를 얻기 위해 CSS를 사용하는 것이 권장됩니다.

사용자 에이전트는 페이지가 CSS를 사용하지 않고 테이블이 레이아웃 테이블로 분류되지 않은 경우, 이러한 기법을 사용하여 테이블을 렌더링하는 것이 권장됩니다.

4.9.2 caption 요소

Element/caption

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLTableCaptionElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
table 요소의 첫 번째 자식 요소로 사용됩니다.
콘텐츠 모델:
플로우 콘텐츠이지만, 자손 table 요소는 포함되지 않습니다.
text/html에서 태그 생략:
caption 요소의 종료 태그caption 요소가 ASCII 공백 문자 또는 주석으로 바로 뒤따르지 않는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTableCaptionElement : HTMLElement {
  [HTMLConstructor] constructor();

  // 더 이상 사용되지 않는 멤버도 포함됩니다
};

caption 요소는 table 요소를 부모로 가지는 경우 해당 표의 제목을 나타냅니다.

caption 요소는 테이블 모델에 참여합니다.

table 요소가 figure 요소의 유일한 콘텐츠이고 figcaption 외에는 다른 콘텐츠가 없을 때, caption 요소는 figcaption 요소로 대체되어야 합니다.

캡션은 테이블에 대한 맥락을 제공하여 이해하기 훨씬 쉽게 만들 수 있습니다.

예를 들어, 다음 테이블을 고려해 보십시오:

1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 12

추상적으로 보면 이 테이블은 명확하지 않습니다. 그러나 테이블 번호(주요 본문에서 참조하기 위해)를 제공하고 테이블의 용도를 설명하는 캡션이 있으면 더 이해하기 쉬워집니다:

<caption>
<p>Table 1.
<p>이 테이블은 두 개의 6면체 주사위를 굴려 얻은 총 점수를 보여줍니다. 첫 번째 행은 첫 번째 주사위의 값을 나타내고, 첫 번째 열은 두 번째 주사위의 값을 나타냅니다. 총 점수는 두 주사위 값에 해당하는 셀에 표시됩니다.
</caption>

이렇게 하면 사용자에게 더 많은 맥락을 제공합니다:

Table 1.

이 테이블은 두 개의 6면체 주사위를 굴려 얻은 총 점수를 보여줍니다. 첫 번째 행은 첫 번째 주사위의 값을 나타내고, 첫 번째 열은 두 번째 주사위의 값을 나타냅니다. 총 점수는 두 주사위 값에 해당하는 셀에 표시됩니다.

1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 12

4.9.3 colgroup 요소

Element/colgroup

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLTableColElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
table 요소의 자식으로, caption 요소 뒤, thead, tbody, tfoot, tr 요소 앞에 사용됩니다.
콘텐츠 모델:
span 속성이 존재할 경우: 아무것도 포함하지 않음.
span 속성이 존재하지 않을 경우: 0개 이상의 coltemplate 요소.
text/html에서 태그 생략:
colgroup 요소의 시작 태그colgroup 요소 내부의 첫 번째 항목이 col 요소인 경우 생략할 수 있으며, 요소가 종료 태그가 생략된 다른 colgroup 요소 바로 뒤에 있지 않은 경우에만 생략할 수 있습니다. (요소가 비어 있는 경우에는 생략할 수 없습니다.)
colgroup 요소의 종료 태그colgroup 요소가 ASCII 공백 문자 또는 주석 바로 뒤에 오지 않는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
span — 요소가 가로지르는 열의 수
접근성 고려 사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTableColElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long span;

  // 구식 멤버도 포함합니다
};

colgroup 요소는 table 요소의 부모가 있을 경우, 부모가 table 요소일 때, 그 부모에서 하나 이상의 열 그룹표현합니다.

colgroup 요소에 col 요소가 포함되지 않은 경우, 요소는 span 콘텐츠 속성을 지정할 수 있으며, 해당 값은 0보다 크고 1000 이하인 유효한 비음수 정수이어야 합니다.

colgroup 요소와 그 span 속성은 테이블 모델의 일부를 형성합니다.

span IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 하며, 이는 [1, 1000] 범위로 조정되며, 기본값은 1입니다.

4.9.4 col 요소

Element/col

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
colgroup 요소의 자식으로, span 속성이 없는 경우에만 사용됩니다.
콘텐츠 모델:
아무것도 포함하지 않음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐츠 속성:
전역 속성
span — 요소가 가로지르는 열의 수
접근성 고려 사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
HTMLTableColElement 사용, colgroup 요소와 동일하게 정의됨.

col 요소가 부모를 가지고 있고, 그 부모가 colgroup 요소이며, 그 자체가 table 요소인 경우, col 요소는 colgroup이 표현하는 열 그룹 내에서 하나 이상의 표현합니다.

요소는 span 콘텐츠 속성을 지정할 수 있으며, 해당 값은 0보다 크고 1000 이하인 유효한 비음수 정수이어야 합니다.

col 요소와 그 span 속성은 테이블 모델의 일부를 형성합니다.

4.9.5 tbody 요소

Element/tbody

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTableSectionElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
table 요소의 자식으로, caption, colgroup, thead 요소들 다음에 위치해야 하며, tr 요소가 table 요소의 자식으로 존재하지 않아야 합니다.
콘텐츠 모델:
0개 이상의 tr스크립트 지원 요소.
text/html에서 태그 생략:
tbody 요소의 시작 태그tr 요소가 첫 번째 자식 요소로 있을 경우 생략할 수 있으며, 이 요소가 바로 앞에 tbody, thead, 또는 tfoot 요소가 생략된 종료 태그로 끝나지 않는 경우에만 생략할 수 있습니다. (요소가 비어있으면 생략할 수 없습니다.)
tbody 요소의 종료 태그tbody 또는 tfoot 요소가 뒤따르거나 부모 요소에 더 이상 내용이 없을 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTableSectionElement : HTMLElement {
  [HTMLConstructor] constructor();

  [SameObject] readonly attribute HTMLCollection rows;
  HTMLTableRowElement insertRow(optional long index = -1);
  [CEReactions] undefined deleteRow(long index);

  // 이전에 사용되었던 멤버들도 포함됩니다.
};

HTMLTableSectionElement 인터페이스는 theadtfoot 요소에도 사용됩니다.

tbody 요소는 대표합니다 행 그룹으로, 부모 table 요소에 대한 데이터를 담고 있는 tbody 요소가 부모를 가지고 있으며, 그 부모가 table 요소인 경우에 해당합니다.

tbody 요소는 테이블 모델에 참여합니다.

tbody.rows

이 요소에 뿌리를 둔 HTMLCollection으로 반환되며, 필터는 이 요소의 자식 요소인 tr 요소만 일치시킵니다.

tr = tbody.insertRow([ index ])

tr 요소를 생성하여, 지정된 인덱스 위치에 삽입하고, 해당 tr을 반환합니다.

인덱스 위치는 테이블 섹션의 행을 기준으로 합니다. 인덱스 -1은 인덱스를 생략했을 때의 기본값으로, 테이블 섹션의 끝에 삽입하는 것과 동일합니다.

주어진 위치가 -1보다 작거나 행의 개수보다 크면, "IndexSizeError" DOMException을 던집니다.

tbody.deleteRow(index)

테이블 섹션에서 지정된 인덱스 위치의 tr 요소를 제거합니다.

인덱스 위치는 테이블 섹션의 행을 기준으로 합니다. 인덱스 -1은 테이블 섹션의 마지막 행을 삭제하는 것과 동일합니다.

주어진 위치가 -1보다 작거나 행의 마지막 인덱스보다 크거나 행이 없으면, "IndexSizeError" DOMException을 던집니다.

rows 속성은 이 요소에 뿌리를 둔 HTMLCollection을 반환하며, 필터는 이 요소의 자식 요소인 tr 요소만 일치시킵니다.

insertRow(index) 메서드는 다음과 같이 동작해야 합니다:

  1. index가 -1보다 작거나 rows 컬렉션의 요소 수보다 크면, "IndexSizeError" DOMException을 던집니다.

  2. table row는 이 요소의 노드 문서, tr, 및 HTML 네임스페이스를 사용하여 생성한 요소의 결과여야 합니다.

  3. 인덱스가 -1이거나 rows 컬렉션의 요소 수와 같으면, table row를 이 요소에 추가합니다.

  4. 그렇지 않으면, table row를 이 요소의 자식으로 index 번째 tr 요소 바로 앞에 삽입합니다.

  5. table row를 반환합니다.

deleteRow(index) 메서드는 호출되었을 때, 다음과 같이 동작해야 합니다:

  1. 인덱스가 -1보다 작거나 rows 컬렉션의 마지막 요소보다 크거나 같으면, "IndexSizeError" DOMException을 던집니다.

  2. 인덱스가 -1이면 rows 컬렉션에서 마지막 요소를 제거하거나, 컬렉션이 비어있으면 아무 작업도 하지 않습니다.

  3. 그렇지 않으면, 이 요소에서 index 번째 rows 컬렉션의 요소를 제거합니다.

4.9.6 thead 요소

Element/thead

모든 최신 브라우저 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
없음.
이 요소를 사용할 수 있는 맥락:
table 요소의 자식 요소로, captioncolgroup 요소 이후, tbody, tfoot, tr 요소들 이전에 위치해야 합니다. 그러나 table 요소의 자식 요소로 다른 thead 요소가 없을 경우에만 해당됩니다.
콘텐츠 모델:
tr 요소와 스크립트 지원 요소를 0개 이상 포함할 수 있습니다.
텍스트/HTML에서 태그 생략:
thead 요소의 종료 태그thead 요소 뒤에 바로 tbody 또는 tfoot 요소가 올 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLTableSectionElement 사용.

thead 요소는 대표로서 부모 table 요소의 열 머리글(헤더)과 보조 비헤더 셀들로 구성된 행 그룹을 나타냅니다. thead 요소가 부모를 가지며, 그 부모가 table인 경우에 해당합니다.

thead 요소는 테이블 모델에 참여합니다.

이 예시는 thead 요소의 사용 예시를 보여줍니다. thtd 요소가 thead 요소 내에서 사용된 것을 확인할 수 있습니다: 첫 번째 행은 헤더이고, 두 번째 행은 테이블 작성 방법에 대한 설명입니다.

<table>
 <caption> School auction sign-up sheet </caption>
 <thead>
  <tr>
   <th><label for=e1>Name</label>
   <th><label for=e2>Product</label>
   <th><label for=e3>Picture</label>
   <th><label for=e4>Price</label>
  <tr>
   <td>Your name here
   <td>What are you selling?
   <td>Link to a picture
   <td>Your reserve price
 <tbody>
  <tr>
   <td>Ms Danus
   <td>Doughnuts
   <td><img src="https://example.com/mydoughnuts.png" title="Doughnuts from Ms Danus">
   <td>$45
  <tr>
   <td><input id=e1 type=text name=who required form=f>
   <td><input id=e2 type=text name=what required form=f>
   <td><input id=e3 type=url name=pic form=f>
   <td><input id=e4 type=number step=0.01 min=0 value=0 required form=f>
</table>
<form id=f action="/auction.cgi">
 <input type=button name=add value="Submit">
</form>

4.9.7 tfoot 요소

Element/tfoot

모든 최신 브라우저 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 맥락:
table 요소의 자식 요소로, caption, colgroup, thead, tbody, tr 요소들 이후에 위치해야 합니다. 그러나 table 요소의 자식 요소로 다른 tfoot 요소가 없을 경우에만 해당됩니다.
콘텐츠 모델:
tr 요소와 스크립트 지원 요소를 0개 이상 포함할 수 있습니다.
텍스트/HTML에서 태그 생략:
tfoot 요소의 종료 태그는 부모 요소에 더 이상 콘텐츠가 없는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLTableSectionElement 사용.

tfoot 요소는 부모 table 요소의 열 요약(푸터)으로 구성된 행 그룹을 나타냅니다. tfoot 요소가 부모를 가지며, 그 부모가 table인 경우에 해당합니다.

tfoot 요소는 테이블 모델에 참여합니다.

4.9.8 tr 요소

Element/tr

모든 최신 브라우저 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTableRowElement

모든 최신 브라우저 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 맥락:
thead 요소의 자식으로.
tbody 요소의 자식으로.
tfoot 요소의 자식으로.
table 요소의 자식으로, caption, colgroup, thead 요소들 이후에 위치하지만, tbody 요소가 없는 경우에만 해당됩니다.
콘텐츠 모델:
td, th, 스크립트 지원 요소를 0개 이상 포함할 수 있습니다.
텍스트/HTML에서 태그 생략:
tr 요소의 종료 태그tr 요소가 바로 다음에 위치하거나, 부모 요소에 더 이상 콘텐츠가 없으면 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTableRowElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute long rowIndex;
  readonly attribute long sectionRowIndex;
  [SameObject] readonly attribute HTMLCollection cells;
  HTMLTableCellElement insertCell(optional long index = -1);
  [CEReactions] undefined deleteCell(long index);

  // 사용되지 않는 멤버 포함
};

tr 요소는 테이블 내의 나타냅니다.

tr 요소는 테이블 모델에 참여합니다.

tr.rowIndex

HTMLTableRowElement/rowIndex

모든 최신 브라우저 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

행의 위치를 테이블의 rows 목록에서 반환합니다.

요소가 테이블에 없으면 -1을 반환합니다.

tr.sectionRowIndex

행의 위치를 테이블 섹션의 rows 목록에서 반환합니다.

요소가 테이블 섹션에 없으면 -1을 반환합니다.

tr.cells

이 행의 HTMLCollection을 반환하며, 필터는 이 요소의 자식인 tdth 요소만 일치합니다.

cell = tr.insertCell([ index ])

HTMLTableRowElement/insertCell

모든 최신 브라우저 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (구버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

td 요소를 생성하여 인덱스 위치에 삽입하고 생성된 td 요소를 반환합니다.

위치는 행의 셀들에 상대적입니다. 인덱스 −1은 기본값으로, 인덱스가 생략된 경우 마지막에 삽입하는 것과 같습니다.

주어진 인덱스가 −1보다 작거나 셀 수보다 크면 "IndexSizeError" DOMException 예외가 발생합니다.

tr.deleteCell(index)

지정된 인덱스 위치의 td 또는 th 요소를 행에서 제거합니다.

위치는 행의 셀들에 상대적입니다. 인덱스 −1은 행의 마지막 셀을 삭제하는 것과 같습니다.

주어진 인덱스가 −1보다 작거나 셀 수보다 크거나 셀이 없으면 "IndexSizeError" DOMException 예외가 발생합니다.

rowIndex 속성은 이 요소에 부모 table 요소, 또는 부모 tbody, thead, tfoot 요소와 조부모 table 요소가 있는 경우, 해당 table 요소의 rows 컬렉션에서 이 tr 요소의 인덱스를 반환해야 합니다. 그러한 table 요소가 없다면, 이 속성은 −1을 반환해야 합니다.

sectionRowIndex 속성은 이 요소에 부모 table, tbody, thead, 또는 tfoot 요소가 있는 경우, 부모 요소의 rows 컬렉션에서 tr 요소의 인덱스를 반환해야 합니다 (테이블의 경우, 이는 HTMLTableElementrows 컬렉션입니다; 테이블 섹션의 경우, 이는 HTMLTableSectionElementrows 컬렉션입니다). 그러한 부모 요소가 없다면, 이 속성은 −1을 반환해야 합니다.

cells 속성은 이 tr 요소를 루트로 하고, 필터가 tdth 요소와 일치하는 HTMLCollection을 반환해야 하며, 이는 tr 요소의 자식 요소들만 필터링합니다.

insertCell(index) 메서드는 다음과 같이 동작해야 합니다:

  1. index가 −1보다 작거나 cells 컬렉션의 요소 수보다 크면, "IndexSizeError" DOMException을 던집니다.

  2. table cell은 이 tr 요소의 노드 문서, tdHTML 네임스페이스를 사용하여 생성된 요소입니다.

  3. index가 −1과 같거나 cells 컬렉션의 항목 수와 같으면, 이 table celltr 요소에 추가합니다.

  4. 그 외의 경우, 이 table celltr 요소의 자식으로, cells 컬렉션의 index번째 td 또는 th 요소 바로 앞에 삽입합니다.

  5. table cell을 반환합니다.

deleteCell(index) 메서드는 다음과 같이 동작해야 합니다:

  1. index가 −1보다 작거나 cells 컬렉션의 요소 수보다 크거나 같으면, "IndexSizeError" DOMException을 던집니다.

  2. index가 −1이면, cells 컬렉션이 비어 있지 않은 경우, 마지막 요소를 제거하고, 그렇지 않으면 아무 것도 하지 않습니다.

  3. 그 외의 경우, cells 컬렉션의 index번째 요소를 부모로부터 제거합니다.

4.9.9 td 요소

Element/td

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTableCellElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
범주:
없음.
이 요소가 사용할 수 있는 문맥:
tr 요소의 자식으로서.
콘텐츠 모델:
플로우 콘텐츠.
text/html에서의 태그 생략:
td 요소의 종료 태그td 요소가 바로 뒤에 오거나 th 요소가 뒤따르거나 상위 요소에 더 이상 콘텐츠가 없으면 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
colspan — 셀이 걸쳐야 하는 열 수
rowspan — 셀이 걸쳐야 하는 행 수
headers — 이 셀의 헤더 셀
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTableCellElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long colSpan;
  [CEReactions] attribute unsigned long rowSpan;
  [CEReactions] attribute DOMString headers;
  readonly attribute long cellIndex;

  [CEReactions] attribute DOMString scope; // th 요소만 적합
  [CEReactions] attribute DOMString abbr;  // th 요소만 적합

  // 오래된 멤버도 있음
};

HTMLTableCellElement 인터페이스는 th 요소에도 사용됩니다.

td 요소는 테이블의 데이터 을 나타냅니다.

td 요소와 그 colspan, rowspan, headers 속성은 테이블 모델에 참여합니다.

사용자 에이전트는 특히 비시각적 환경에서 또는 테이블을 2D 그리드로 표시하는 것이 비실용적인 경우 셀의 내용을 렌더링할 때 셀의 위치를 제공하거나 셀의 헤더 셀을 나열하는 등의 방법으로 셀에 대한 사용자의 컨텍스트를 제공할 수 있습니다(셀의 헤더 셀을 할당하는 알고리즘에 의해 결정됨). 셀의 헤더 셀이 나열될 때, 사용자 에이전트는 해당 헤더 셀에 abbr 속성 값이 있는 경우 해당 값을 대신 사용할 수 있습니다.

이 예제에서는 편집 가능한 셀 그리드(본질적으로 간단한 스프레드시트)로 구성된 웹 애플리케이션의 스니펫을 보여줍니다. 셀 중 하나는 위의 셀의 합계를 표시하도록 설정되었습니다. 셋은 제목으로 표시되며, th 요소 대신 td 요소를 사용합니다. 스크립트가 이 요소에 이벤트 핸들러를 연결하여 합계를 유지합니다.

<table>
 <tr>
  <th><input value="Name">
  <th><input value="Paid ($)">
 <tr>
  <td><input value="Jeff">
  <td><input value="14">
 <tr>
  <td><input value="Britta">
  <td><input value="9">
 <tr>
  <td><input value="Abed">
  <td><input value="25">
 <tr>
  <td><input value="Shirley">
  <td><input value="2">
 <tr>
  <td><input value="Annie">
  <td><input value="5">
 <tr>
  <td><input value="Troy">
  <td><input value="5">
 <tr>
  <td><input value="Pierce">
  <td><input value="1000">
 <tr>
  <th><input value="Total">
  <td><output value="1060">
</table>

4.9.10 th 요소

Element/th

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
tr 요소의 자식 요소로 사용.
콘텐츠 모델:
플로우 콘텐츠, 하지만 header, footer, 섹셔닝 콘텐츠, 또는 헤딩 콘텐츠 자손은 없음.
text/html에서 태그 생략:
th 요소의 종료 태그th 요소가 즉시 td 또는 th 요소로 이어지거나 부모 요소에 더 이상 콘텐츠가 없을 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
colspan — 셀이 걸쳐야 할 열의 수
rowspan — 셀이 걸쳐야 할 행의 수
headers — 이 셀에 대한 헤더 셀
scope — 헤더 셀이 적용되는 셀을 지정
abbr — 다른 문맥에서 셀을 참조할 때 사용할 대체 레이블
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLTableCellElement를 사용하며, td 요소에 대해 정의됩니다.

th 요소는 테이블에서 헤더 을 나타냅니다.

th 요소는 scope 콘텐츠 속성을 가질 수 있습니다.

scope 속성은 다음과 같은 키워드와 상태를 가지는 열거형 속성입니다:

키워드 상태 간략한 설명
row row 헤더 셀은 동일한 행의 일부 후속 셀에 적용됩니다.
col column 헤더 셀은 동일한 열의 일부 후속 셀에 적용됩니다.
rowgroup row group 헤더 셀은 행 그룹의 모든 남은 셀에 적용됩니다.
colgroup column group 헤더 셀은 열 그룹의 모든 남은 셀에 적용됩니다.

이 속성의 누락된 값 기본값유효하지 않은 값 기본값은 모두 auto 상태입니다. (이 상태에서는 헤더 셀이 문맥에 따라 선택된 셀 집합에 적용됩니다.)

th 요소의 scope 속성은 요소가 행 그룹에 연결되지 않은 경우 행 그룹 상태에 있어서는 안 되며, 요소가 열 그룹에 연결되지 않은 경우 열 그룹 상태에 있어서는 안 됩니다.

th 요소는 abbr 콘텐츠 속성을 지정할 수 있습니다. 이 값은 셀을 다른 문맥에서 참조할 때 사용되는 헤더 셀의 대체 라벨이어야 합니다 (예: 데이터 셀에 적용되는 헤더 셀을 설명할 때). 일반적으로 전체 헤더 셀의 약어 형태이지만, 확장되거나 단순히 다른 표현일 수도 있습니다.

th 요소와 그 colspan, rowspan, headers, 그리고 scope 속성은 테이블 모델에 참여합니다.

다음 예제는 scope 속성의 rowgroup 값이 헤더 셀이 적용되는 데이터 셀에 어떻게 영향을 미치는지를 보여줍니다.

다음은 테이블을 나타내는 마크업 조각입니다:

<table>
<thead>
<tr> <th> ID <th> 측정 <th> 평균 <th> 최대값
<tbody>
<tr> <td> <th scope=rowgroup> 고양이 <td> <td>
<tr> <td> 93 <th> 다리 <td> 3.5 <td> 4
<tr> <td> 10 <th> 꼬리 <td> 1 <td> 1
<tbody>
<tr> <td> <th scope=rowgroup> 영어 사용자 <td> <td>
<tr> <td> 32 <th> 다리 <td> 2.67 <td> 4
<tr> <td> 35 <th> 꼬리 <td> 0.33 <td> 1
</table>

이것은 다음과 같은 테이블을 생성합니다:

ID 측정 평균 최대값
고양이
93 다리 3.5 4
10 꼬리 1 1
영어 사용자
32 다리 2.67 4
35 꼬리 0.33 1

첫 번째 행의 헤더는 모두 열의 아래쪽으로 직접 적용됩니다.

rowgroup 상태의 scope 속성을 가진 헤더는 첫 번째 열에 있는 셀을 제외한 행 그룹의 모든 셀에 적용됩니다.

나머지 헤더는 오른쪽에 있는 셀에만 적용됩니다.

4.9.11 tdth 요소에 공통된 속성

tdth 요소에는 colspan 콘텐츠 속성이 지정될 수 있으며, 그 값은 0보다 크고 1000 이하인 유효한 0이 아닌 정수이어야 합니다.

tdth 요소에는 또한 rowspan 콘텐츠 속성이 지정될 수 있으며, 그 값은 65534 이하의 유효한 0이 아닌 정수이어야 합니다. 이 속성의 값이 0인 경우 셀이 행 그룹의 남은 모든 행에 걸쳐야 함을 의미합니다.

이 속성들은 각각 셀이 걸칠 열과 행의 수를 나타냅니다. 이러한 속성들은 테이블 모델 설명에서 언급된 대로 셀이 겹치도록 사용해서는 안 됩니다.


tdth 요소에는 headers 콘텐츠 속성이 지정될 수 있습니다. 이 headers 속성이 지정된 경우, 그 값은 고유한 공백으로 구분된 토큰들의 정렬되지 않은 집합으로 구성된 문자열이어야 하며, 그 중 어떤 것도 서로 동일하지 않아야 하며 각 토큰은 th 요소의 ID 값을 가져야 하며, 이 td 또는 th 요소가 테이블 모델에서 정의된 동일한 테이블에 참여해야 합니다.

th 요소는 ID id가 있는 모든 tdth 요소에 의해 직접적으로 대상화된다고 합니다. 동일한 테이블에 포함된 headers 속성의 값에 해당하는 토큰이 포함된 모든 요소 B에 의해 th 또는 td 요소는 대상화된다고 합니다.

th 요소는 스스로 대상화되어서는 안 됩니다.

colspan, rowspan, 그리고 headers 속성들은 테이블 모델에 참여합니다.


cell.cellIndex

셀의 위치를 행의 cells 목록에서 반환합니다. 이는 셀이 테이블에서 x-축에 있는 위치와 반드시 일치하는 것은 아닙니다. 앞서 있는 셀이 여러 행이나 열에 걸칠 수 있기 때문입니다.

요소가 행에 포함되지 않은 경우 -1을 반환합니다.

colSpan IDL 속성은 colspan 콘텐츠 속성을 반영해야 합니다. 이는 [1, 1000] 범위로 고정되며, 기본값은 1입니다.

rowSpan IDL 속성은 rowspan 콘텐츠 속성을 반영해야 합니다. 이는 [0, 65534] 범위로 고정되며, 기본값은 1입니다.

headers IDL 속성은 같은 이름의 콘텐츠 속성을 반영해야 합니다.

cellIndex IDL 속성은 요소가 부모 tr 요소를 가지고 있는 경우, 부모 요소의 cells 컬렉션에서 셀 요소의 인덱스를 반환해야 합니다. 그러한 부모 요소가 없는 경우, 속성은 -1을 반환해야 합니다.

scope IDL 속성은 같은 이름의 콘텐츠 속성을 반영해야 하며, 알려진 값만으로 제한됩니다.

abbr IDL 속성은 같은 이름의 콘텐츠 속성을 반영해야 합니다.

4.9.12 처리 모델

다양한 테이블 요소와 그 콘텐츠 속성들은 함께 테이블 모델을 정의합니다.

테이블은 좌표 (x, y)를 가진 슬롯의 2차원 그리드에 정렬된 셀로 구성됩니다. 그리드는 유한하며, 비어 있거나 하나 이상의 슬롯을 가질 수 있습니다. 그리드에 하나 이상의 슬롯이 있는 경우, x 좌표는 항상 0 ≤ x < xwidth 범위에 있고, y 좌표는 항상 0 ≤ y < yheight 범위에 있습니다. xwidthyheight 중 하나 또는 둘 다 0인 경우, 테이블은 비어 있습니다(슬롯이 없습니다). 테이블은 table 요소에 해당합니다.

은 특정 너비높이를 가진 슬롯의 집합으로, 셀이 cellx, celly 슬롯에 앵커링되어 있어 cellxx < cellx+widthcellyy < celly+height인 좌표의 모든 슬롯을 커버합니다. 셀은 데이터 셀 또는 헤더 셀이 될 수 있습니다. 데이터 셀은 td 요소에, 헤더 셀은 th 요소에 해당합니다. 두 유형의 셀 모두 하나 이상의 연관된 헤더 셀을 가질 수 있습니다.

일부 오류 상황에서는 두 개의 셀이 동일한 슬롯을 차지할 수 있습니다.

은 특정 y 값에 대해 x=0에서 x=xwidth-1까지 슬롯의 완전한 집합입니다. 행은 보통 tr 요소에 해당하지만, 행 그룹은 여러 행에 걸친 셀과 관련된 경우 끝에 일부 암시된 을 가질 수 있습니다.

은 특정 x 값에 대해 y=0에서 y=yheight-1까지 슬롯의 완전한 집합입니다. 열은 col 요소에 해당할 수 있습니다. col 요소가 없는 경우 열은 암시적으로 생성됩니다.

행 그룹은 (0, groupy) 슬롯에 앵커링된 의 집합으로, 특정 높이를 가지고 0 ≤ x < xwidthgroupyy < groupy+height인 좌표의 모든 슬롯을 커버합니다. 행 그룹은 tbody, thead, 그리고 tfoot 요소에 해당합니다. 모든 행이 반드시 행 그룹에 속하는 것은 아닙니다.

열 그룹은 (groupx, 0) 슬롯에 앵커링된 의 집합으로, 특정 너비를 가지고 groupxx < groupx+width0 ≤ y < yheight인 좌표의 모든 슬롯을 커버합니다. 열 그룹은 colgroup 요소에 해당합니다. 모든 열이 반드시 열 그룹에 속하는 것은 아닙니다.

행 그룹은 서로 겹칠 수 없습니다. 마찬가지로, 열 그룹도 서로 겹칠 수 없습니다.

은 두 개 이상의 행 그룹에 걸쳐 있는 슬롯을 커버할 수 없습니다. 그러나 셀이 여러 열 그룹에 속할 수는 있습니다. 하나의 셀을 구성하는 모든 슬롯은 0개 또는 1개의 행 그룹 및 0개 이상의 열 그룹에 속합니다.

, , , 행 그룹, 열 그룹 외에도, 테이블에는 caption 요소가 연결될 수 있습니다. 이는 테이블에 제목이나 설명을 제공합니다.

테이블 모델 오류table 요소 및 그 하위 요소로 표현된 데이터의 오류입니다. 문서에는 테이블 모델 오류가 없어야 합니다.

4.9.12.1 테이블 구성하기

table 요소와 연결된 테이블에서 어떤 요소가 어떤 슬롯에 해당하는지, 테이블의 크기(xwidthyheight)를 결정하고, 테이블 모델 오류가 있는지 여부를 확인하려면, 사용자 에이전트는 다음 알고리즘을 사용해야 합니다:

  1. xwidth를 0으로 설정합니다.

  2. yheight를 0으로 설정합니다.

  3. 보류 중인 tfoot 요소들을, 초기에는 비어 있는 tfoot 요소들의 목록으로 설정합니다.

  4. 테이블table 요소로 표현된 테이블로 설정합니다. xwidthyheight 변수는 테이블의 크기를 나타냅니다. 테이블은 초기에는 비어 있습니다.

  5. table 요소에 자식 요소가 없으면, 테이블을 반환합니다 (이 경우 테이블은 비어 있습니다).

  6. table 요소의 첫 번째 caption 자식 요소를 테이블에 연결합니다. 그러한 자식이 없으면, 연결된 caption 요소가 없습니다.

  7. 현재 요소table 요소의 첫 번째 자식 요소로 설정합니다.

    이 알고리즘의 어떤 단계에서 현재 요소table의 다음 자식으로 이동해야 할 때, 다음 자식이 없는 경우, 사용자 에이전트는 이 알고리즘의 끝부분에 있는 단계로 이동해야 합니다.

  8. 현재 요소가 다음 요소 중 하나가 아닐 때, table의 다음 자식으로 이동합니다:

  9. 현재 요소colgroup 요소인 경우, 다음 하위 단계를 따릅니다:

    1. 열 그룹: 현재 요소를 다음의 적절한 경우에 따라 처리합니다:

      현재 요소col 자식 요소를 가진 경우

      다음 단계를 따릅니다:

      1. xstartxwidth 값을 설정합니다.

      2. 현재 열colgroup 요소의 첫 번째 col 자식 요소로 설정합니다.

      3. : 현재 열 col 요소에 span 속성이 있는 경우, 음수가 아닌 정수의 구문 분석 규칙을 사용하여 그 값을 구문 분석합니다.

        값의 구문 분석 결과가 오류가 아니거나 0이 아니면 span을 그 값으로 설정합니다.

        그렇지 않고 col 요소에 span 속성이 없거나, 속성 값을 구문 분석하려는 시도가 오류나 0을 반환한 경우, span을 1로 설정합니다.

        span이 1000을 초과하면 1000으로 설정합니다.

      4. xwidthspan만큼 증가시킵니다.

      5. 테이블의 마지막 span 현재 열 col 요소에 해당합니다.

      6. 현재 열colgroup 요소의 마지막 col 자식 요소가 아닌 경우, 현재 열colgroup 요소의 다음 col 자식 요소로 설정하고, 이라는 레이블이 붙은 단계로 돌아갑니다.

      7. 테이블의 마지막 x=xstart부터 x=xwidth-1까지 새로운 열 그룹을 형성하며, 슬롯 (xstart, 0)에 앵커링되고, 너비는 xwidth-xstartcolgroup 요소에 해당합니다.

      현재 요소col 자식 요소가 없는 경우
      1. colgroup 요소에 span 속성이 있는 경우, 음수가 아닌 정수의 구문 분석 규칙을 사용하여 그 값을 구문 분석합니다.

        값의 구문 분석 결과가 오류가 아니거나 0이 아니면 span을 그 값으로 설정합니다.

        그렇지 않고 colgroup 요소에 span 속성이 없거나, 속성 값을 구문 분석하려는 시도가 오류나 0을 반환한 경우, span을 1로 설정합니다.

        span이 1000을 초과하면 1000으로 설정합니다.

      2. xwidthspan만큼 증가시킵니다.

      3. 테이블의 마지막 span 이 새로운 열 그룹을 형성하며, 슬롯 (xwidth-span, 0)에 앵커링되고, 너비는 span으로 설정됩니다. 이 그룹은 colgroup 요소에 해당합니다.

    2. 현재 요소table의 다음 자식으로 이동합니다.

    3. 현재 요소가 다음 요소 중 하나가 아닐 때, table의 다음 자식으로 이동합니다:

    4. 현재 요소colgroup 요소인 경우, 위의 열 그룹 단계로 이동합니다.

  10. ycurrent를 0으로 설정합니다.

  11. 아래로 확장되는 셀 목록을 빈 목록으로 설정합니다.

  12. : 현재 요소가 다음 요소 중 하나가 아닐 때, table의 다음 자식으로 이동합니다:

  13. 현재 요소tr인 경우, 행 처리 알고리즘을 실행하고, 현재 요소table의 다음 자식으로 이동한 후, 단계로 돌아갑니다.

  14. 행 그룹 종료 알고리즘을 실행합니다.

  15. 현재 요소tfoot인 경우, 해당 요소를 보류 중인 tfoot 요소들 목록에 추가하고, 현재 요소table의 다음 자식으로 이동한 후, 단계로 돌아갑니다.

  16. 현재 요소thead 또는 tbody입니다.

    행 그룹 처리 알고리즘을 실행합니다.

  17. 현재 요소table의 다음 자식으로 이동합니다.

  18. 단계로 돌아갑니다.

  19. : 트리 순서에 따라 보류 중인 tfoot 요소들 목록에 있는 각 tfoot 요소에 대해 행 그룹 처리 알고리즘을 실행합니다.

  20. 테이블 내에 이 연결되지 않은 슬롯만 포함하는 이나 이 있는 경우, 이는 테이블 모델 오류입니다.

  21. 테이블을 반환합니다.

위의 단계 세트에서 thead, tbodytfoot 요소를 처리하기 위해 호출되는 행 그룹 처리 알고리즘은 다음과 같습니다:

  1. ystartyheight 값을 설정합니다.

  2. 처리 중인 요소의 자식인 각 tr 요소에 대해 트리 순서로 행 처리 알고리즘을 실행합니다.

  3. yheightystart보다 큰 경우, 테이블의 마지막 y=ystart에서 y=yheight-1까지 새로운 행 그룹을 형성하며, 슬롯의 좌표 (0, ystart)에 앵커링되고, 높이는 yheight-ystart로 설정됩니다. 이 그룹은 처리 중인 요소에 해당합니다.

  4. 행 그룹 종료 알고리즘을 실행합니다.

위의 단계 세트에서 행의 블록을 시작하고 종료할 때 호출되는 행 그룹 종료 알고리즘은 다음과 같습니다:

  1. ycurrentyheight보다 작은 동안, 다음 단계를 따릅니다:

    1. 아래로 확장되는 셀 확장 알고리즘을 실행합니다.

    2. ycurrent를 1씩 증가시킵니다.

  2. 아래로 확장되는 셀 목록을 비웁니다.

tr 요소를 처리하기 위해 위의 단계 세트에서 호출되는 행 처리 알고리즘은 다음과 같습니다:

  1. yheightycurrent와 같으면 yheight를 1씩 증가시킵니다. (ycurrentyheight보다 크지 않습니다.)

  2. xcurrent를 0으로 설정합니다.

  3. 아래로 확장되는 셀 확장 알고리즘을 실행합니다.

  4. 처리 중인 tr 요소에 td 또는 th 자식 요소가 없으면 ycurrent를 1씩 증가시키고, 이 단계 세트를 중단한 다음 위의 알고리즘으로 돌아갑니다.

  5. 현재 셀을 처리 중인 tr 요소의 첫 번째 td 또는 th 자식 요소로 설정합니다.

  6. : xcurrentxwidth보다 작고 좌표 (xcurrent, ycurrent)를 가진 슬롯에 이미 셀이 할당되어 있는 동안, xcurrent를 1씩 증가시킵니다.

  7. xcurrentxwidth와 같으면 xwidth를 1씩 증가시킵니다. (xcurrentxwidth보다 크지 않습니다.)

  8. 현재 셀colspan 속성이 있는 경우, 그 속성의 값을 구문 분석하고, colspan을 결과로 설정합니다.

    값 구문 분석에 실패하거나 0을 반환했거나 속성이 없는 경우, colspan을 대신 1로 설정합니다.

    colspan이 1000을 초과하면 1000으로 설정합니다.

  9. 현재 셀rowspan 속성이 있는 경우, 그 속성의 값을 구문 분석하고, rowspan을 결과로 설정합니다.

    값 구문 분석에 실패했거나 속성이 없는 경우, rowspan을 대신 1로 설정합니다.

    rowspan이 65534를 초과하면 65534로 설정합니다.

  10. rowspan이 0이고 table 요소의 노드 문서퀴크 모드로 설정되지 않은 경우, 셀이 아래로 확장됨을 true로 설정하고, rowspan을 1로 설정합니다. 그렇지 않은 경우, 셀이 아래로 확장됨을 false로 설정합니다.

  11. xwidth < xcurrent+colspan이면 xwidthxcurrent+colspan으로 설정합니다.

  12. yheight < ycurrent+rowspan이면 yheightycurrent+rowspan으로 설정합니다.

  13. 좌표 (x, y)를 가진 슬롯으로서 xcurrentx < xcurrent+colspanycurrenty < ycurrent+rowspan를 포함하는 슬롯을 새로운 c로 덮으며, 앵커링된 좌표는 (xcurrent, ycurrent)입니다. 이 셀의 너비는 colspan, 높이는 rowspan으로 설정되며, 현재 셀 요소에 해당합니다.

    현재 셀 요소가 th 요소인 경우, 이 새로운 셀 c는 헤더 셀이 되고, 그렇지 않으면 데이터 셀이 됩니다.

    현재 셀 요소에 적용되는 헤더 셀을 설정하려면, 다음 섹션에 설명된 헤더 셀 할당 알고리즘을 사용합니다.

    관련된 슬롯에 이미 이 덮여 있는 경우, 이는 테이블 모델 오류입니다. 이 슬롯들은 이제 두 개의 셀이 겹쳐집니다.

  14. 셀이 아래로 확장됨이 true인 경우, c, xcurrent, colspan 튜플을 아래로 확장되는 셀 목록에 추가합니다.

  15. xcurrentcolspan만큼 증가시킵니다.

  16. 현재 셀이 처리 중인 tr 요소의 마지막 td 또는 th 자식 요소인 경우, ycurrent를 1씩 증가시키고, 이 단계 세트를 중단한 다음 위의 알고리즘으로 돌아갑니다.

  17. 현재 셀을 처리 중인 tr 요소의 다음 td 또는 th 자식 요소로 설정합니다.

  18. 이라는 레이블이 붙은 단계로 돌아갑니다.

위의 알고리즘에서 아래로 확장되는 셀 확장 알고리즘을 실행해야 할 때, 사용자 에이전트는 아래로 확장되는 셀 목록에 있는 각 {cell, cellx, width} 튜플에 대해, cell이 좌표 (x, ycurrent)를 가진 슬롯도 덮도록 확장합니다. 이때 cellxx < cellx+width 조건을 만족해야 합니다.

4.9.12.2 데이터 셀과 헤더 셀 간의 관계 형성

각 셀에는 0개 이상의 헤더 셀이 할당될 수 있습니다. 셀 principal cell에 헤더 셀을 할당하기 위한 헤더 셀 할당 알고리즘은 다음과 같습니다.

  1. header list를 빈 셀 목록으로 설정합니다.

  2. principalx, principalyprincipal cell이 고정된 슬롯의 좌표로 설정합니다.

  3. principal cellheaders 속성이 지정된 경우
    1. principal cellheaders 속성 값을 가져와 ASCII 공백으로 분리하여 id list를 얻은 토큰 목록으로 설정합니다.

    2. id list의 각 토큰에 대해, 해당 토큰과 동일한 ID를 가진 문서에서 첫 번째 요소가 동일한 테이블의 셀이며, 해당 셀이 principal cell이 아닌 경우 해당 셀을 header list에 추가합니다.

    principal cellheaders 속성이 지정되지 않은 경우
    1. principalwidthprincipal cell의 너비로 설정합니다.

    2. principalheightprincipal cell의 높이로 설정합니다.

    3. principaly에서 principaly+principalheight-1까지의 각 y 값에 대해 헤더 셀을 스캔하고 할당하는 내부 알고리즘을 실행합니다. 이때 principal cell, header list, 초기 좌표 (principalx, y), 그리고 증가량 Δx=−1Δy=0을 사용합니다.

    4. principalx에서 principalx+principalwidth-1까지의 각 x 값에 대해 헤더 셀을 스캔하고 할당하는 내부 알고리즘을 실행합니다. 이때 principal cell, header list, 초기 좌표 (x, principaly), 그리고 증가량 Δx=0Δy=−1을 사용합니다.

    5. principal cell행 그룹에 고정된 경우, 동일한 행 그룹에 고정된 행 그룹 헤더 셀들을 모두 header list에 추가합니다. 이때 x 좌표는 principalx+principalwidth-1 이하이고, y 좌표는 principaly+principalheight-1 이하이어야 합니다.

    6. principal cell열 그룹에 고정된 경우, 동일한 열 그룹에 고정된 열 그룹 헤더 셀들을 모두 header list에 추가합니다. 이때 x 좌표는 principalx+principalwidth-1 이하이고, y 좌표는 principaly+principalheight-1 이하이어야 합니다.

  4. 빈 셀header list에서 모두 제거합니다.

  5. header list에서 중복 항목을 모두 제거합니다.

  6. principal cellheader list에 포함되어 있으면 이를 제거합니다.

  7. header list에 있는 헤더를 principal cell에 할당합니다.

주어진 principal cell, header list, 초기 좌표 (initialx, initialy), Δx, Δy 증가량에 대해 헤더 셀을 스캔하고 할당하는 내부 알고리즘은 다음과 같습니다:

  1. xinitialx로 설정합니다.

  2. yinitialy로 설정합니다.

  3. opaque headers를 빈 셀 목록으로 설정합니다.

  4. principal cell이 헤더 셀인 경우

    in header block을 true로 설정하고, headers from current header blockprincipal cell만 포함하는 셀 목록으로 설정합니다.

    그 외의 경우

    in header block을 false로 설정하고, headers from current header block을 빈 셀 목록으로 설정합니다.

  5. Loop: Δx만큼 x를 증가시키고, Δy만큼 y를 증가시킵니다.

    이 알고리즘이 호출될 때마다 Δx와 Δy 중 하나는 −1이 되고, 다른 하나는 0이 됩니다.

  6. x 또는 y가 0보다 작으면 이 내부 알고리즘을 중단합니다.

  7. 슬롯 (x, y)을 덮는 셀이 없거나, 그 슬롯을 덮는 셀이 둘 이상 있으면 Loop로 돌아갑니다.

  8. 슬롯 (x, y)을 덮는 셀을 current cell로 설정합니다.

  9. current cell이 헤더 셀인 경우
    1. in header block을 true로 설정합니다.

    2. current cellheaders from current header block에 추가합니다.

    3. blocked을 false로 설정합니다.

    4. Δx가 0인 경우

      opaque headers 목록에 있는 셀이 current cell과 동일한 x 좌표로 고정되어 있고, current cell과 동일한 너비를 가진 경우 blocked를 true로 설정합니다.

      current cellcolumn header가 아닌 경우 blocked를 true로 설정합니다.

      Δy가 0인 경우

      opaque headers 목록에 있는 셀이 current cell과 동일한 y 좌표로 고정되어 있고, current cell과 동일한 높이를 가진 경우 blocked를 true로 설정합니다.

      current cellrow header가 아닌 경우 blocked를 true로 설정합니다.

    5. blocked가 false인 경우, current cellheader list에 추가합니다.

    current cell이 데이터 셀이면서 in header block이 true인 경우

    in header block을 false로 설정합니다. headers from current header block에 있는 모든 셀을 opaque headers 목록에 추가하고, headers from current header block 목록을 비웁니다.

  10. Loop로 돌아갑니다.

헤더 셀이 x, y 좌표에 고정되어 있고, widthheight를 가진 경우, 다음 조건 중 하나라도 충족되면 해당 셀은 column header로 간주됩니다:

헤더 셀이 x, y 좌표에 고정되어 있고, widthheight를 가진 경우, 다음 조건 중 하나라도 충족되면 해당 셀은 row header로 간주됩니다:

헤더 셀이 column group header로 간주되는 경우, 해당 셀의 scope 속성이 column group 상태인 경우입니다.

헤더 셀이 row group header로 간주되는 경우, 해당 셀의 scope 속성이 row group 상태인 경우입니다.

셀은 요소가 없고 자식 텍스트 콘텐츠ASCII 공백으로만 구성된 경우 empty cell로 간주됩니다.

4.9.13 예시

이 섹션은 비규범적입니다.

다음은 Smithsonian 물리 테이블, Volume 71의 표 45의 하단 부분을 마크업하는 방법을 보여줍니다:

<table>
 <caption>사양 값: <b>Steel</b>, <b>Castings</b>,
 Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05.</caption>
 <thead>
  <tr>
   <th rowspan=2>Grade.</th>
   <th rowspan=2>Yield Point.</th>
   <th colspan=2>Ultimate tensile strength</th>
   <th rowspan=2>Per cent elong. 50.8&nbsp;mm or 2&nbsp;in.</th>
   <th rowspan=2>Per cent reduct. area.</th>
  </tr>
  </tr>
   <th>kg/mm<sup>2</sup></th>
   <th>lb/in<sup>2</sup></th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Hard</td>
   <td>0.45 ultimate</td>
   <td>56.2</td>
   <td>80,000</td>
   <td>15</td>
   <td>20</td>
  </tr>
  <tr>
   <td>Medium</td>
   <td>0.45 ultimate</td>
   <td>49.2</td>
   <td>70,000</td>
   <td>18</td>
   <td>25</td>
  </tr>
  </tr>
   <td>Soft</td>
   <td>0.45 ultimate</td>
   <td>42.2</td>
   <td>60,000</td>
   <td>22</td>
   <td>30</td>
  </tr>
 </tbody>
</table>

이 표는 다음과 같이 보일 수 있습니다:

사양 값: Steel, Castings, Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05.
Grade. Yield Point. Ultimate tensile strength Per cent elong. 50.8 mm or 2 in. Per cent reduct. area.
kg/mm2 lb/in2
Hard 0.45 ultimate 56.2 80,000 15 20
Medium 0.45 ultimate 49.2 70,000 18 25
Soft 0.45 ultimate 42.2 60,000 22 30

다음은 Apple, Inc의 2008 회계연도 10-K 파일링의 46페이지에 있는 총 마진 표를 마크업하는 방법을 보여줍니다:

<table>
 <thead>
  <tr>
   <th><th>2008
   <th>2007
   <th>2006
 <tbody>
  <tr>
   <th>Net sales
   <td>$ 32,479
   <td>$ 24,006
   <td>$ 19,315
  </tr>
  <tr>
   <th>Cost of sales
   <td>  21,334
   <td>  15,852
   <td>  13,717
 </tbody>
  <tr>
   <th>Gross margin
   <td>$ 11,145
   <td>$  8,154
   <td>$  5,598
 <tfoot>
  <tr>
   <th>Gross margin percentage
   <td>34.3%
   <td>34.0%
   <td>29.0%
</table>

이 표는 다음과 같이 보일 수 있습니다:

2008 2007 2006
Net sales $ 32,479 $ 24,006 $ 19,315
Cost of sales 21,334 15,852 13,717
Gross margin $ 11,145 $ 8,154 $ 5,598
Gross margin percentage 34.3% 34.0% 29.0%

다음은 같은 페이지의 하단에 있는 운영 비용 표를 마크업하는 방법을 보여줍니다:

<table>
 <colgroup> <col>
 <colgroup> <col> <col> <col>
 <thead>
  <tr> <th> <th>2008 <th>2007 <th>2006
 </tr>
 </thead>
 <tbody>
  <tr> <th scope=rowgroup>Research and development
       <td> $ 1,109 <td> $ 782 <td> $ 712
  </tr>
  <tr> <th scope=row>Percentage of net sales
       <td> 3.4% <td> 3.3% <td> 3.7%
 </tr>
 </tbody>
 </tbody>
 </table>

이 표는 다음과 같이 보일 수 있습니다:

2008 2007 2006
Research and development $ 1,109 $ 782 $ 712
Percentage of net sales 3.4% 3.3% 3.7%
Selling, general, and administrative $ 3,761 $ 2,963 $ 2,433
Percentage of net sales 11.6% 12.3% 12.6%

4.10 양식

Element#Forms

모든 최신 엔진에서 지원됩니다.

Firefox4+ Safari4+ Chrome61+
Opera52+ Edge79+
Edge (Legacy)16+ Internet Explorer10+
Firefox Android5+ Safari iOS3.2+ Chrome Android61+ WebView Android61+ Samsung Internet8.0+ Opera Android47+

4.10.1 소개

이 섹션은 비규범적입니다.

폼은 텍스트, 버튼, 체크박스, 범위, 또는 색상 선택 컨트롤과 같은 폼 컨트롤이 포함된 웹 페이지의 구성 요소입니다. 사용자는 이러한 폼과 상호 작용하여 서버로 전송할 수 있는 데이터를 제공할 수 있습니다(예: 검색 결과 또는 계산 결과 반환). 많은 경우에 클라이언트 측 스크립팅이 필요하지 않지만, 스크립트가 사용자 경험을 증대시키거나 데이터를 서버에 제출하는 것 외의 목적으로 폼을 사용할 수 있도록 API가 제공됩니다.

폼 작성은 사용자 인터페이스 작성, 서버 측 처리 구현, 사용자 인터페이스를 서버와 통신하도록 설정하는 등의 여러 단계를 포함하며, 이들은 어떤 순서로도 수행할 수 있습니다.

4.10.1.1 폼의 사용자 인터페이스 작성

이 섹션은 비규범적입니다.

이 간단한 소개의 목적으로, 피자 주문 폼을 작성해 보겠습니다.

모든 폼은 form 요소로 시작하며, 그 안에 컨트롤이 배치됩니다. 대부분의 컨트롤은 기본적으로 텍스트 컨트롤을 제공하는 input 요소로 표현됩니다. 컨트롤에 레이블을 지정하려면 label 요소를 사용합니다. 레이블 텍스트와 컨트롤 자체는 label 요소 내에 배치됩니다. 폼의 각 부분은 단락으로 간주되며, 일반적으로 다른 부분과 p 요소를 사용하여 분리됩니다. 이를 조합하여 고객의 이름을 요청하는 방법은 다음과 같습니다:

<form>
 <p><label>고객 이름: <input></label></p>
</form>

사용자가 피자 크기를 선택할 수 있도록 하기 위해, 라디오 버튼 세트를 사용할 수 있습니다. 라디오 버튼은 또한 input 요소를 사용하며, 이 경우 type 속성의 값이 radio로 설정됩니다. 라디오 버튼을 그룹으로 작동하게 하려면 name 속성을 사용하여 공통 이름을 부여합니다. 라디오 버튼과 같은 컨트롤 배치를 그룹화하려면 fieldset 요소를 사용할 수 있습니다. 이러한 컨트롤 그룹의 제목은 fieldset의 첫 번째 요소이며, legend 요소가 되어야 합니다.

<form>
 <p><label>고객 이름: <input></label></p>
 <fieldset>
  <legend> 피자 크기 </legend>
  <p><label> <input type=radio name=size> 소형 </label></p>
  <p><label> <input type=radio name=size> 중형 </label></p>
  <p><label> <input type=radio name=size> 대형 </label></p>
 </fieldset>
</form>

사용자가 토핑을 선택할 수 있도록 하기 위해, 체크박스를 사용할 수 있습니다. 체크박스는 input 요소를 사용하며, type 속성의 값이 checkbox로 설정됩니다:

<form>
 <p><label>고객 이름: <input></label></p>
 <fieldset>
  <legend> 피자 크기 </legend>
  <p><label> <input type=radio name=size> 소형 </label></p>
  <p><label> <input type=radio name=size> 중형 </label></p>
  <p><label> <input type=radio name=size> 대형 </label></p>
 </fieldset>
 <fieldset>
  <legend> 피자 토핑 </legend>
  <p><label> <input type=checkbox> 베이컨 </label></p>
  <p><label> <input type=checkbox> 추가 치즈 </label></p>
  <p><label> <input type=checkbox> 양파 </label></p>
  <p><label> <input type=checkbox> 버섯 </label></p>
 </fieldset>
</form>

이 폼이 작성되는 피자 가게는 항상 실수를 저지르기 때문에 고객과 연락할 방법이 필요합니다. 이를 위해 전화번호 (input 요소와 type 속성을 tel로 설정한 경우)와 이메일 주소 (input 요소와 type 속성을 email로 설정한 경우)를 위한 폼 컨트롤을 사용할 수 있습니다:

<form>
 <p><label>고객 이름: <input></label></p>
 <p><label>전화번호: <input type=tel></label></p>
 <p><label>이메일 주소: <input type=email></label></p>
 <fieldset>
  <legend> 피자 크기 </legend>
  <p><label> <input type=radio name=size> 소형 </label></p>
  <p><label> <input type=radio name=size> 중형 </label></p>
  <p><label> <input type=radio name=size> 대형 </label></p>
 </fieldset>
 <fieldset>
  <legend> 피자 토핑 </legend>
  <p><label> <input type=checkbox> 베이컨 </label></p>
  <p><label> 추가 치즈 </input type=checkbox></label></p>
  <p><label> 양파 </input type=checkbox></label></p>
  <p><label> 버섯 </input type=checkbox></label></p>
 </fieldset>
 <p><label>선호하는 배달 시간: <input type=time min="11:00" max="21:00" step="900"></label></p>
</form>

textarea 요소를 사용하여 다중 줄 텍스트 컨트롤을 제공할 수 있습니다. 이번에는 고객이 배달 지침을 제공할 수 있는 공간으로 사용할 것입니다:

<form>
 <p><label>고객 이름: <input></label></p>
 <p><label>전화번호: <input type=tel></label></p>
 <p><label>이메일 주소: <input type=email></label></p>
 <fieldset>
  <legend> 피자 크기 </legend>
  <p><label> <input type=radio name=size> 소형 </label></p>
  <p><label> <input type=radio name=size> 중형 </label></p>
  <p><label> <input type=radio name=size> 대형 </label></p>
 </fieldset>
 <fieldset>
  <legend> 피자 토핑 </legend>
  <p><label> <input type=checkbox> 베이컨 </label></p>
  <p><label> 추가 치즈 </input type=checkbox></label></p>
  <p><label> 양파 </input type=checkbox></label></p>
  <p><label> 버섯 </input type=checkbox></label></p>
 </fieldset>
 <p><label>선호하는 배달 시간: <input type=time min="11:00" max="21:00" step="900"></label></p>
 <p><label>배달 지침: <textarea></textarea></label></p>
</form>

마지막으로, 폼을 제출할 수 있게 하기 위해 button 요소를 사용합니다:

<form>
 <p><label>Customer name: <input></label></p>
 <p><label>Telephone: <input type=tel></label></p>
 <p><label>Email address: <input type=email></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox> Bacon </label></p>
  <p><label> <input type=checkbox> Extra Cheese </label></p>
  <p><label> <input type=checkbox> Onion </label></p>
  <p><label> <input type=checkbox> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p>
 <p><label>Delivery instructions: <textarea></textarea></label></p>
 <p><button>Submit order</button></p>
</form>
4.10.1.2 폼의 서버 측 처리 구현

이 섹션은 비규범적입니다.

서버 측 처리기를 작성하는 구체적인 세부 사항은 이 명세의 범위를 벗어납니다. 이 소개를 위해 우리는 https://pizza.example.com/order.cgi에 있는 스크립트가 application/x-www-form-urlencoded 형식을 사용하여 제출을 수락하도록 구성되었으며, HTTP POST 본문에서 다음 매개변수를 수신할 것으로 가정합니다.

custname
고객의 이름
custtel
고객의 전화번호
custemail
고객의 이메일 주소
size
피자의 크기, small, medium, large 중 하나
topping
토핑, 선택된 토핑마다 한 번씩 지정하며, 허용되는 값은 bacon, cheese, onion, mushroom입니다.
delivery
요청된 배달 시간
comments
배달 지침
4.10.1.3 폼이 서버와 통신하도록 구성하기

이 섹션은 비규범적입니다.

폼 제출은 서버에 다양한 방법으로 노출되며, 가장 일반적으로는 HTTP GET 또는 POST 요청으로 이루어집니다. 사용된 정확한 방법을 지정하려면, method 속성을 form 요소에 지정합니다. 이는 폼 데이터가 어떻게 인코딩되는지를 지정하지 않습니다. 이를 지정하려면, enctype 속성을 사용합니다. 또한 제출된 데이터를 처리할 서비스의 URLaction 속성을 사용하여 지정해야 합니다.

제출하려는 각 폼 컨트롤에는 제출 시 데이터를 참조하는 데 사용되는 이름을 지정해야 합니다. 이전에 라디오 버튼 그룹에 대해 이름을 지정했습니다. 동일한 속성(name)이 제출 시 사용할 이름을 지정하는 데 사용됩니다. 라디오 버튼을 서로 구분하기 위해서는 value 속성을 사용하여 값을 다르게 지정할 수 있습니다.

여러 컨트롤이 동일한 이름을 가질 수 있습니다. 예를 들어, 여기에서는 모든 체크박스에 동일한 이름을 지정하고, 서버는 해당 이름과 함께 제출된 값으로 체크된 항목을 구분합니다. 라디오 버튼과 마찬가지로, 이들은 value 속성을 사용하여 고유한 값을 지정합니다.

이전 섹션에서 설정된 내용에 따르면, 결과는 다음과 같습니다.

<form method="post"
  enctype="application/x-www-form-urlencoded"
  action="https://pizza.example.com/order.cgi">
<p><label>고객 이름: <input name="custname"></label></p>
<p><label>전화 번호: <input type=tel name="custtel"></label></p>
<p><label>이메일 주소: <input type=email name="custemail"></label></p>
<fieldset>
 <legend> 피자 크기 </legend>
 <p><label> <input type=radio name=size value="small"> Small </label></p>
 <p><label> <input type=radio name=size value="medium"> Medium </label></p>
 <p><label> <input type=radio name=size value="large"> Large </label></p>
</fieldset>
</fieldset>
<fieldset>
 <legend> 피자 토핑 </legend>
 <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
 <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
 <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
 </fieldset>
</fieldset>
</form>

어떤 속성 값이 인용부호로 묶여 있고 그렇지 않은 것에는 특별한 의미가 없습니다. HTML 구문은 다양한 동등하게 유효한 방법으로 속성을 지정할 수 있으며, 이는 구문 섹션에서 다루고 있습니다. 구문 섹션에서 설명합니다.

예를 들어, 고객이 "Denise Lawrence"라는 이름을 입력하고, "555-321-8642"라는 전화번호를 입력하고, 이메일 주소를 지정하지 않고, 중간 크기의 피자를 주문하고, Extra Cheese와 Mushroom 토핑을 선택하고, 배달 시간을 7pm으로 지정하고, 배달 지침 텍스트 컨트롤을 비워둔 경우, 사용자 에이전트는 온라인 웹 서비스에 다음과 같은 데이터를 제출합니다:

custname=Denise+Lawrence&custtel=555-321-8642&custemail=&size=medium&topping=cheese&topping=mushroom&delivery=19%3A00&comments=
4.10.1.5 폼 컨트롤의 클라이언트 측 자동 채우기 활성화

이 섹션은 비규범적입니다.

일부 브라우저는 사용자가 정보를 매번 다시 입력하지 않도록 폼 컨트롤을 자동으로 채워 사용자를 돕습니다. 예를 들어, 사용자의 전화번호를 묻는 필드는 사용자의 전화번호로 자동으로 채워질 수 있습니다.

이를 돕기 위해 autocomplete 속성을 사용하여 필드의 목적을 설명할 수 있습니다. 이 폼의 경우, 피자 배달 정보를 위해 유용하게 주석을 달 수 있는 세 개의 필드가 있습니다. 이 정보를 추가하는 방법은 다음과 같습니다:

<form method="post"
  enctype="application/x-www-form-urlencoded"
  action="https://pizza.example.com/order.cgi">
<p><label>고객 이름: <input name="custname" required autocomplete="shipping name"></label></p>
<p><label>전화번호: <input type=tel name="custtel" autocomplete="shipping tel"></label></p>
<p><label>이메일 주소: <input type=email name="custemail" autocomplete="shipping email"></label></p>
<fieldset>
  <legend> 피자 크기 </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
</fieldset> 
<fieldset> 
  <legend> 피자 토핑 </legend> 
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> 
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> 
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> 
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> 
</fieldset> 
<p><label>선호하는 배달 시간: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p> 
<p><label>배달 지침: <textarea name="comments" maxlength=1000></textarea></label></p> 
<p><button>주문 제출</button></p> 
</form>
4.10.1.6 모바일 기기에서 사용자 경험 개선

이 섹션은 비규범적입니다.

일부 기기, 특히 가상 키보드를 사용하는 기기는 사용자에게 여러 입력 모드를 제공합니다. 예를 들어, 신용카드 번호를 입력할 때는 0-9의 숫자 키만 보이도록 하고, 이름을 입력할 때는 각 단어를 대문자로 시작하도록 하는 폼 필드를 보고 싶을 수 있습니다.

inputmode 속성을 사용하면 적절한 입력 모드를 선택할 수 있습니다:

<form method="post"
  enctype="application/x-www-form-urlencoded"
  action="https://pizza.example.com/order.cgi">
<p><label>고객 이름: <input name="custname" required autocomplete="shipping name"></label></p>
<p><label>전화번호: <input type=tel name="custtel" autocomplete="shipping tel"></label></p>
<p><label>버저 코드: <input name="custbuzz" inputmode="numeric"></label></p>
<p><label>이메일 주소: <input type=email name="custemail" autocomplete="shipping email"></label></p>
<fieldset> 
  <legend> 피자 크기 </legend> 
  <p><label> <input type=radio name=size required value="small"> Small </label></p> 
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p> 
  <p><label> <input type=radio name=size required value="large"> Large </label></p> 
</fieldset> 
<fieldset> 
  <legend> 피자 토핑 </legend> 
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> 
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> 
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> 
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> 
</fieldset> 
<p><label>선호하는 배달 시간: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p> 
<p><label>배달 지침: <textarea name="comments" maxlength=1000></textarea></label></p> 
<p><button>주문 제출</button></p> 
</form>
4.10.1.7 필드 타입, 자동완성 필드 이름 및 입력 모드의 차이

이 섹션은 비규범적입니다.

type, autocomplete, inputmode 속성은 혼란스럽게 유사하게 보일 수 있습니다. 예를 들어, 세 가지 경우 모두에서 "email" 문자열이 유효한 값이 될 수 있습니다. 이 섹션에서는 이 세 가지 속성의 차이를 설명하고 이들을 사용하는 방법에 대한 조언을 제공합니다.

type 속성은 input 요소에 적용되며, 사용자 에이전트가 필드를 표시하는 방법을 결정합니다. 이 속성의 다른 값을 선택하는 것은 input 요소, textarea 요소, select 요소 등을 선택하는 것과 동일합니다.

autocomplete 속성은 사용자가 입력할 값이 실제로 무엇을 나타내는지를 설명합니다. 이 속성의 다른 값을 선택하는 것은 해당 요소에 대한 라벨을 선택하는 것과 동일합니다.

우선, 전화번호를 고려해보세요. 페이지가 사용자에게 전화번호를 요청하는 경우, 사용할 적절한 폼 컨트롤은 <input type=tel>입니다. 그러나 어떤 autocomplete 값을 사용할지는 페이지가 요청하는 전화번호의 유형(국제 형식 또는 지역 형식) 등에 따라 달라집니다.

예를 들어, 친구에게 선물을 배송하는 고객이 결제 문제 발생 시 고객의 전화번호와 배송 문제 발생 시 친구의 전화번호가 모두 필요한 전자상거래 사이트의 체크아웃 과정의 일부인 페이지는 국제 전화번호(국가 코드 포함)를 기대할 수 있습니다. 이 경우, 다음과 같이 표시될 수 있습니다:

<p><label>귀하의 전화번호: <input type=tel name=custtel autocomplete="billing tel"></label>
<p><label>수신자 전화번호: <input type=tel name=shiptel autocomplete="shipping tel"></label>
<p>국가 코드 접두사 포함한 전화번호를 입력해 주세요, 예: "+1 555 123 4567".

그러나 사이트가 영국 고객과 수신자만 지원하는 경우, 다음과 같이 표시될 수 있습니다 (tel-national 대신 tel이 사용된 것을 확인하십시오):

<p><label>귀하의 전화번호: <input type=tel name=custtel autocomplete="billing tel-national"></label>
<p><label>수신자 전화번호: <input type=tel name=shiptel autocomplete="shipping tel-national"></label>
<p>UK 전화번호를 입력해 주세요, 예: "(01632) 960 123".

다음으로, 선호 언어를 고려해보세요. 적절한 autocomplete 값은 language입니다. 그러나 이 목적을 위해 사용되는 폼 컨트롤은 텍스트 컨트롤(<input type=text>), 드롭다운 리스트(<select>), 라디오 버튼(<input type=radio>) 등이 될 수 있습니다. 이는 원하는 인터페이스 유형에 따라 달라집니다.

마지막으로, 이름을 고려해보세요. 페이지가 사용자에게 이름 하나만 요청하는 경우, 적절한 컨트롤은 <input type=text>입니다. 페이지가 사용자의 전체 이름을 묻는다면, 관련 autocomplete 값은 name입니다.

<p><label>일본어 이름: <input name="j" type="text" autocomplete="section-jp name"></label> 
<label>로마자 이름: <input name="e" type="text" autocomplete="section-en name"></label>

이 예에서, section-* 키워드는 사용자 에이전트에게 두 필드가 다른 이름을 기대하고 있음을 알립니다. 그렇지 않으면, 사용자 에이전트는 사용자가 첫 번째 필드에 값을 입력했을 때 두 번째 필드를 자동으로 첫 번째 필드의 값으로 채울 수 있습니다.

-jp-en 키워드의 부분은 사용자 에이전트에 불투명하며, 사용자 에이전트는 이러한 키워드로부터 두 이름이 각각 일본어와 영어로 입력되어야 한다고 추측할 수 없습니다.

typeautocomplete와 별도로, inputmode 속성은 텍스트 컨트롤이 있는 경우에 사용할 입력 모드(예: 가상 키보드)를 결정합니다.

신용카드 번호를 고려해보세요. 적절한 입력 유형은 <input type=number>아닙니다 (아래에서 설명한 대로), 대신 <input type=text>입니다. 사용자 에이전트가 숫자 입력 모드(예: 숫자만 표시하는 가상 키보드)를 사용하도록 권장하기 위해 페이지는 다음과 같이 사용할 수 있습니다.

<p><label>신용카드 번호:
            <input name="cc" type="text" inputmode="numeric" pattern="[0-9]{8,19}" autocomplete="cc-number"> 
</label></p>
4.10.1.8 날짜, 시간, 및 숫자 형식

이 섹션은 비규범적입니다.

이 피자 배달 예제에서, 시간은 "HH:MM" 형식으로 지정됩니다: 두 자리 숫자로 된 시간(24시간 형식)과 두 자리 숫자로 된 분입니다. (초를 지정할 수도 있지만, 이 예제에서는 필요하지 않습니다.)

그러나 일부 지역에서는 시간 표시 형식이 사용자에게 다르게 표현되는 경우가 많습니다. 예를 들어, 미국에서는 여전히 "2pm"과 같이 am/pm 표시기를 사용하는 12시간 시계를 사용하는 것이 일반적입니다. 프랑스에서는 "14h00"과 같이 "h" 문자를 사용하여 시간을 분과 구분하는 것이 일반적입니다.

날짜의 경우에도 비슷한 문제가 있으며, 구성 요소의 순서조차 일관되지 않은 경우가 있습니다. 예를 들어, 키프로스에서는 2003년 2월 1일을 "1/2/03"으로 쓰는 반면, 일본에서는 그 같은 날짜를 "2003年02月01日"로 표기하는 것이 일반적입니다. 숫자에서도 지역에 따라 소수점 구분자와 천 단위 구분자로 어떤 구두점을 사용하는지 다를 수 있습니다.

따라서 HTML과 폼 제출에서 사용되는 시간, 날짜, 숫자 형식(항상 이 사양에서 정의된 형식이며, 컴퓨터에서 읽을 수 있는 날짜 및 시간 형식을 위한 잘 확립된 ISO 8601 표준을 기반으로 함)과 브라우저가 사용자에게 표시하고 사용자가 입력한 내용을 수락하는 시간, 날짜, 숫자 형식을 구별하는 것이 중요합니다.

HTML 마크업과 폼 제출에서 사용되는 형식, 즉 "전송 형식"은 사용자 지역에 관계없이 일관되고 컴퓨터에서 읽을 수 있는 형태로 작성됩니다. 예를 들어, 날짜는 항상 "YYYY-MM-DD" 형식으로 작성되며, "2003-02-01"과 같이 표시됩니다. 일부 사용자는 이 형식을 볼 수 있지만, 다른 사용자는 "01.02.2003" 또는 "2003년 2월 1일"과 같이 볼 수 있습니다.

페이지에서 전송 형식으로 제공된 시간, 날짜 또는 숫자는 사용자가 보기 전에 사용자의 선호도나 페이지의 지역 설정에 따라 사용자가 선호하는 표시 형식으로 변환됩니다. 마찬가지로, 사용자가 선호하는 형식으로 시간, 날짜 또는 숫자를 입력하면 사용자 에이전트는 이를 다시 전송 형식으로 변환하여 DOM에 넣거나 제출합니다.

이렇게 하면 페이지와 서버의 스크립트가 시간, 날짜, 숫자를 일관된 방식으로 처리할 수 있으며, 다양한 형식을 지원할 필요 없이 사용자의 요구를 충족할 수 있습니다.

양식 컨트롤의 지역화에 관한 구현 노트도 참조하세요.

4.10.2 카테고리

주로 역사적인 이유로, 이 섹션의 요소들은 플로우 콘텐츠, 구문 콘텐츠, 인터랙티브 콘텐츠와 같은 일반적인 카테고리 외에도 여러 중첩되지만 미묘하게 다른 카테고리로 분류됩니다.

여러 요소들은 폼 관련 요소로 분류되며, 이는 폼 소유자를 가질 수 있음을 의미합니다.

폼 관련 요소들은 여러 하위 카테고리로 나뉩니다:

리스트된 요소

이는 form.elementsfieldset.elements API에 나열된 요소들을 나타냅니다. 이 요소들은 또한 form 콘텐츠 속성과 일치하는 form IDL 속성을 가지며, 저자가 명시적인 폼 소유자를 지정할 수 있게 합니다.

제출 가능한 요소

이는 form 요소가 제출될 때 엔트리 목록을 구성하는 데 사용할 수 있는 요소를 나타냅니다.

일부 제출 가능한 요소는 속성에 따라 버튼이 될 수 있습니다. 아래의 본문에서는 요소가 버튼인 경우를 정의합니다. 일부 버튼은 특별히 제출 버튼입니다.

재설정 가능한 요소

이는 form 요소가 재설정될 때 영향을 받을 수 있는 요소를 나타냅니다.

자동 대문자 변환 상속 요소

이는 폼 소유자로부터 autocapitalize 속성을 상속받는 요소를 나타냅니다.

일부 요소는 폼 관련 요소가 아닌 것도 있지만, 라벨 가능 요소로 분류됩니다. 이러한 요소들은 label 요소와 연결될 수 있는 요소입니다.

4.10.3 form 요소

Element/form

현재 모든 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLFormElement

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
카테고리:
플로우 콘텐츠.
명백한 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
플로우 콘텐츠가 기대되는 곳.
콘텐츠 모델:
플로우 콘텐츠, 하지만 하위 요소로 form 요소는 허용되지 않음.
text/html에서 태그 생략:
둘 다 생략할 수 없음.
콘텐츠 속성:
전역 속성
accept-charset폼 제출에 사용할 문자 인코딩
actionURL폼 제출에 사용할 URL
autocomplete — 폼 내 컨트롤에 대한 자동 완성 기능의 기본 설정
enctype엔트리 목록 인코딩 유형 — 폼 제출에 사용할 인코딩
method폼 제출에 사용할 메소드
namedocument.forms API에서 사용할 폼의 이름
novalidate폼 제출을 위한 폼 컨트롤 검증 건너뛰기
target네비게이션 대상폼 제출을 위한 네비게이션 대상
rel
접근성 고려 사항:
작성자를 위한 지침.
구현자를 위한 지침.
DOM 인터페이스:
[Exposed=Window,
LegacyOverrideBuiltIns,
LegacyUnenumerableNamedProperties]
interface HTMLFormElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString acceptCharset;
  [CEReactions] attribute USVString action;
  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute DOMString enctype;
  [CEReactions] attribute DOMString encoding;
  [CEReactions] attribute DOMString method;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute boolean noValidate;
  [CEReactions] attribute DOMString target;
  [CEReactions] attribute DOMString rel;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;

  [SameObject] readonly attribute HTMLFormControlsCollection elements;
  readonly attribute unsigned long length;
  getter Element (unsigned long index);
  getter (RadioNodeList or Element) (DOMString name);

  undefined submit();
  undefined requestSubmit(optional HTMLElement? submitter = null);
  [CEReactions] undefined reset();
  boolean checkValidity();
  boolean reportValidity();
};

form 요소는 하이퍼링크를 나타내며, 일부는 편집 가능한 값을 나타내는 폼 연관 요소들 모음을 통해 조작될 수 있으며, 이러한 값들은 서버로 제출되어 처리될 수 있습니다.

accept-charset 속성은 제출에 사용할 문자 인코딩을 지정합니다. 지정된 경우, 값은 "UTF-8"에 대해 ASCII 대소문자 구분 없음 일치여야 합니다. [ENCODING]

name 속성은 form의 이름을 forms 컬렉션 내에서 나타냅니다. 값은 빈 문자열이 아니어야 하며, 해당 컬렉션 내의 다른 form 요소와 고유해야 합니다.

autocomplete 속성은 다음의 키워드와 상태를 가진 열거된 속성입니다:

키워드 상태 간략한 설명
on on 폼 컨트롤이 기본적으로 "on"으로 설정된 자동 완성 필드 이름을 가집니다.
off off 폼 컨트롤이 기본적으로 "off"으로 설정된 자동 완성 필드 이름을 가집니다.

속성의 누락된 값 기본값잘못된 값 기본값은 모두 on 상태입니다.

action, enctype, method, novalidate, 및 target 속성은 폼 제출을 위한 속성입니다.

rel 속성은 form 요소에서 생성하는 링크 종류를 제어합니다. 속성의 값은 고유한 공백으로 구분된 토큰의 무순서 집합이어야 합니다. 허용된 키워드와 그 의미는 이전 섹션에서 정의되었습니다.

rel지원되는 토큰HTML 링크 유형에서 허용된 키워드들로, 처리 모델에 영향을 미치고 사용자 에이전트에서 지원되는 키워드입니다. 가능한 지원되는 토큰noreferrer, noopener, 및 opener입니다. rel지원되는 토큰은 사용자 에이전트가 처리 모델을 구현한 목록에 있는 토큰만 포함해야 합니다.

form.elements

HTMLFormElement/elements

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

폼 컨트롤의 HTMLFormControlsCollection을 반환합니다 (역사적인 이유로 이미지 버튼은 제외됩니다).

form.length

HTMLFormElement/length

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

폼 내 컨트롤의 수를 반환합니다 (역사적인 이유로 이미지 버튼은 제외됨).

form[index]

폼 내에서 index번째 요소를 반환합니다 (역사적인 이유로 이미지 버튼은 제외됨).

form[name]

지정된 ID 또는 name으로 폼 내에서 폼 컨트롤을 반환합니다 (여러 개가 있는 경우, 해당 폼 컨트롤의 RadioNodeList를 반환); 없으면, 지정된 ID의 img 요소를 반환합니다.

특정 이름을 사용해 요소가 참조된 이후에는, 해당 이름은 요소가 트리 내에 있는 한 해당 방법에서 요소를 참조하는 방법으로 계속 사용 가능합니다, 실제 ID 또는 name이 변경되더라도.

일치하는 항목이 여러 개 있는 경우, 해당 요소들을 모두 포함하는 RadioNodeList 객체가 반환됩니다.

form.submit()

HTMLFormElement/submit

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

폼을 제출하며, 인터랙티브 제약 조건 검증을 우회하며 submit 이벤트를 발생시키지 않습니다.

form.requestSubmit([ submitter ])

HTMLFormElement/requestSubmit

현재 모든 엔진에서 지원됨.

Firefox75+Safari16+Chrome76+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

폼을 제출하도록 요청합니다. submit() 메소드와 달리, 이 메소드는 인터랙티브 제약 조건 검증submit 이벤트를 포함하며, 이들 중 하나가 제출을 취소할 수 있습니다.

submitter 인수를 사용하여 특정 제출 버튼을 지정할 수 있으며, 이 버튼의 formaction, formenctype, formmethod, formnovalidate, 및 formtarget 속성이 제출에 영향을 줄 수 있습니다. 또한, 제출 버튼은 제출을 위한 엔트리 목록 구성에 포함되며, 일반적으로 버튼은 제외됩니다.

form.reset()

HTMLFormElement/reset

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

폼을 리셋합니다.

form.checkValidity()

폼의 컨트롤이 모두 유효한 경우 true를 반환합니다. 그렇지 않은 경우 false를 반환합니다.

form.reportValidity()

폼의 컨트롤이 모두 유효한 경우 true를 반환하며, 그렇지 않은 경우 false를 반환하고 사용자에게 알립니다.

autocomplete IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

HTMLFormElement/name

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

namerel IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

HTMLFormElement/acceptCharset

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

acceptCharset IDL 속성은 동일한 이름의 accept-charset 콘텐츠 속성을 반영해야 합니다.

relList IDL 속성은 rel 콘텐츠 속성을 반영해야 합니다.


elements IDL 속성은 HTMLFormControlsCollection을 반환해야 하며, form 요소의 루트에서, 필터는 리스트된 요소들에 맞고 폼 소유자form 요소인 경우, input 요소의 type 속성이 이미지 버튼 상태에 있는 경우를 제외하고, 역사적인 이유로 이 특정 컬렉션에서 제외해야 합니다.

length IDL 속성은 elements 컬렉션에 의해 대표되는 노드의 수를 반환해야 합니다.

지원되는 속성 인덱스는 해당 순간에 elements 속성에 의해 반환된 객체에 의해 지원되는 인덱스입니다.

인덱싱된 속성의 값을 결정하기 위해, form 요소의 경우, 사용자 에이전트는 주어진 인덱스를 인수로 하여 item 메소드를 호출할 때 elements 컬렉션에서 반환된 값을 반환해야 합니다.


form 요소에는 과거 이름 맵이라 불리는 이름과 요소의 매핑이 있습니다. 이는 요소가 이름을 변경하더라도 이름을 유지하는 데 사용됩니다.

지원되는 속성 이름은 다음 알고리즘에서 얻은 이름들로 구성되며, 알고리즘에서 얻은 순서대로 나열됩니다:

  1. sourced names라는 초기에는 비어 있는 튜플의 순서 리스트를 만드세요. 이 튜플은 문자열, 요소, 소스(id, name, 또는 past)로 구성됩니다. 소스가 past인 경우, 나이를 추가합니다.

  2. 리스트된 요소 candidate에 대해, 그 폼 소유자form 요소인 경우, input 요소의 type 속성이 이미지 버튼 상태인 경우는 제외합니다:

    1. 만약 candidateid 속성을 가지고 있다면, 그 id 속성의 값을 문자열로, candidate를 요소로, 그리고 id를 소스로 하여 sourced names에 항목을 추가하세요.

    2. 만약 candidatename 속성을 가지고 있다면, 그 name 속성의 값을 문자열로, candidate를 요소로, 그리고 name을 소스로 하여 sourced names에 항목을 추가하세요.

  3. img 요소 candidate에 대해, 그 폼 소유자form 요소인 경우:

    1. 만약 candidateid 속성을 가지고 있다면, 그 id 속성의 값을 문자열로, candidate를 요소로, 그리고 id를 소스로 하여 sourced names에 항목을 추가하세요.

    2. 만약 candidatename 속성을 가지고 있다면, 그 name 속성의 값을 문자열로, candidate를 요소로, 그리고 name을 소스로 하여 sourced names에 항목을 추가하세요.

  4. 각 항목 past entry에 대해 과거 이름 맵에 항목을 추가하여, past entry의 이름을 문자열로, past entry의 요소를 요소로, past를 소스로, 그리고 과거 이름 맵에 항목이 존재한 기간을 나이로 설정하여 sourced names에 항목을 추가하세요.

  5. sourced names를 정렬하세요. 요소 항목의 트리 순서를 기준으로 정렬하며, 동일한 요소 항목이 있는 경우 id 소스 항목을 먼저, name 소스 항목을 그 다음, past 소스 항목을 그 다음으로 배치하고, 동일한 요소 및 소스 항목이 있는 경우에는 나이 순으로 오래된 항목을 먼저 배치하세요.

  6. 이름이 빈 문자열인 sourced names의 항목을 제거하세요.

  7. 이전 항목과 동일한 이름을 가진 sourced names의 항목을 제거하세요.

  8. 이름의 리스트를 sourced names에서 반환하고, 그들의 상대적인 순서를 유지하세요.

속성 이름 name의 값을 결정하기 위해, form 요소의 경우, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. candidates라는 라이브 RadioNodeList 객체를 만들어, 리스트된 요소들 중에서 폼 소유자form 요소인 경우 input 요소의 type 속성이 이미지 버튼 상태인 경우를 제외하고, name과 동일한 id 또는 name 속성을 가진 요소를 포함하세요. 트리 순서로 정렬합니다.

  2. 만약 candidates가 비어 있다면, candidates라이브 RadioNodeList 객체로 설정하여, img 요소 중에서 폼 소유자form 요소인 경우, name과 동일한 id 또는 name 속성을 가진 요소를 포함하세요. 트리 순서로 정렬합니다.

  3. 만약 candidates가 비어 있다면, nameform 요소의 과거 이름 맵에 있는 이름 중 하나인지 확인하고, 그렇다면 그 맵에서 name과 연관된 객체를 반환하세요.

  4. 만약 candidates에 하나 이상의 노드가 포함되어 있다면, candidates를 반환하세요.

  5. 그렇지 않으면, candidates에 정확히 하나의 노드만 포함되어 있습니다. name에서 candidates의 노드로 매핑을 추가하고, form 요소의 과거 이름 맵에 동일한 이름을 가진 이전 항목이 있으면 교체하세요.

  6. candidates에 있는 노드를 반환하세요.

만약 form 요소의 과거 이름 맵에 나열된 요소가 폼 소유자를 변경하면, 그 항목은 해당 맵에서 제거되어야 합니다.


submit() 메서드 단계는 제출을 실행하는 것으로, this에서 시작하며, submit() 메서드에서 제출됨이 true로 설정됩니다.

requestSubmit(submitter) 메서드가 호출되면, 다음 단계를 실행해야 합니다:

  1. submitter가 null이 아닌 경우:

    1. submitter제출 버튼이 아닌 경우, TypeError를 발생시킵니다.

    2. submitter폼 소유자가 이 form 요소가 아닌 경우, "NotFoundError" DOMException를 발생시킵니다.

  2. 그렇지 않으면, submitter를 이 form 요소로 설정하세요.

  3. form 요소를 submitter에서 제출합니다.

reset() 메서드가 호출되면, 다음 단계를 실행해야 합니다:

  1. form 요소가 초기화 잠금으로 표시된 경우, 종료합니다.

  2. form 요소를 초기화 잠금으로 표시합니다.

  3. form 요소를 초기화합니다.

  4. form 요소에서 초기화 잠금 표시를 해제합니다.

checkValidity() 메서드가 호출되면, 사용자 에이전트는 제약 조건을 정적으로 검증해야 하며, 제약 조건 검증이 긍정적인 결과를 반환하면 true를, 부정적인 결과를 반환하면 false를 반환해야 합니다.

reportValidity() 메서드가 호출되면, 사용자 에이전트는 제약 조건을 상호작용적으로 검증해야 하며, 제약 조건 검증이 긍정적인 결과를 반환하면 true를, 부정적인 결과를 반환하면 false를 반환하고, 사용자에게 알립니다.

이 예시는 두 개의 검색 폼을 보여줍니다:

<form action="https://www.google.com/search" method="get">
 <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>
<form action="https://www.bing.com/search" method="get">
 <label>Bing: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>

4.10.4 label 요소

Element/label

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLLabelElement

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
대화형 콘텐츠.
구체적 콘텐츠.
이 요소가 사용될 수 있는 맥락:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠이지만, 후손에 라벨 가능 요소가 없거나, 이 요소의 라벨된 제어 요소일 때만 허용되며, 후손에 label 요소가 없어야 합니다.
태그 생략:
태그 생략 불가.
콘텐츠 속성:
글로벌 속성
for — 폼 제어와 라벨 연결
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLLabelElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString htmlFor;
  readonly attribute HTMLElement? control;
};

label 요소는 사용자 인터페이스에서 캡션을 나타냅니다. 이 캡션은 label 요소의 라벨된 제어로 알려진 특정 폼 제어와 연결될 수 있으며, for 속성을 사용하거나, 폼 제어를 label 요소 내부에 배치하여 연결할 수 있습니다.

다음 규칙에 의해 달리 명시되지 않은 경우, label 요소는 라벨된 제어를 가지지 않습니다.

Attributes/for

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

for 속성은 캡션이 연결될 폼 컨트롤을 지정하기 위해 사용할 수 있습니다. 이 속성이 지정된 경우, 속성의 값은 해당 ID여야 하며, label 요소와 동일한 트리 내의 라벨 가능한 요소여야 합니다. 만약 이 속성이 지정되었고, 트리 내에 IDfor 속성 값과 동일한 요소가 존재하며, 그 중 첫 번째 요소가 라벨 가능한 요소인 경우, 그 요소는 label 요소의 라벨된 컨트롤이 됩니다.

for 속성이 지정되지 않았지만, label 요소가 라벨 가능 요소 후손을 가지고 있다면, 트리 순서에서 첫 번째 후손이 label 요소의 라벨된 제어가 됩니다.

label 요소의 기본 표시와 동작은 플랫폼의 라벨 동작을 따릅니다. label 요소의 후손에 대한 이벤트 타겟의 대화형 콘텐츠에서 활성화 동작은 아무런 동작도 하지 않습니다.

폼 관련 사용자 정의 요소라벨 가능 요소로 간주되며, label 요소의 활성화 동작이 라벨된 제어에 영향을 미치면, 기본 요소와 커스텀 요소 모두 영향을 받습니다.

예를 들어, 라벨을 클릭하면 폼 제어가 활성화되는 플랫폼에서는, 아래 예제에서 label을 클릭하면 사용자 에이전트가 클릭 이벤트를 발생시키며, input 요소에서 해당 이벤트가 발생된 것처럼 작동할 수 있습니다:

<label><input type=checkbox name=lost> Lost</label>

마찬가지로, my-checkbox폼 관련 사용자 정의 요소로 선언된 경우 (예: 이 예제), 다음 코드도 동일하게 동작합니다:

<label><my-checkbox name=lost></my-checkbox> Lost</label>

다른 플랫폼에서는, 두 경우 모두 컨트롤에 포커스를 맞추거나 아무 동작도 하지 않을 수 있습니다.

다음 예제는 각 라벨에 연결된 세 개의 폼 제어를 보여주며, 그 중 두 개는 사용자가 올바른 형식을 사용할 수 있도록 작은 텍스트를 포함하고 있습니다.

<p><label>Full name: <input name=fn> <small>Format: First Last</small></label></p>
<p><label>Age: <input name=age type=number min=0></label></p>
<p><label>Post code: <input name=pc> <small>Format: AB12 3CD</small></label></p>
label.control

HTMLLabelElement/control

모든 현재 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

이 요소와 연결된 폼 제어를 반환합니다.

label.form

HTMLLabelElement/form

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이 요소와 관련된 폼 제어의 폼 소유자를 반환합니다.

없다면 null을 반환합니다.

HTMLLabelElement/htmlFor

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

htmlFor IDL 속성은 for 콘텐츠 속성을 반영해야 합니다.

control IDL 속성은 label 요소의 라벨된 제어를 반환하거나, 없다면 null을 반환해야 합니다.

form IDL 속성은 다음 단계를 실행해야 합니다:

  1. label 요소가 라벨된 제어를 가지고 있지 않다면, null을 반환합니다.

  2. label 요소의 라벨된 제어폼 관련 요소가 아니라면 null을 반환합니다.

  3. label 요소의 라벨된 제어폼 소유자를 반환합니다(이 값은 null일 수 있습니다).

form IDL 속성은 label 요소의 form IDL 속성과 다르며, 리스트된 폼 관련 요소에서 label 요소는 form 콘텐츠 속성을 가지지 않습니다.


control.labels

HTMLButtonElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

HTMLInputElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari5+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

HTMLMeterElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLOutputElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari5.1+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

HTMLProgressElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLSelectElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

HTMLTextAreaElement/labels

모든 현재 엔진에서 지원됨.

Firefox56+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

폼 제어와 연관된 모든 NodeListlabel 요소들을 반환합니다.

라벨 가능한 요소들과 모든 input 요소들은 해당 요소와 연결된 실시간 NodeList 객체를 가지고 있습니다. 이 객체는 해당 요소의 라벨된 컨트롤로 설정된 label 요소들의 목록을 트리 순서로 나타냅니다. 라벨 가능한 요소들폼과 연관된 커스텀 요소들이 아닌 경우, 그리고 labels IDL 속성이 input 요소에서 가져올 때, 그 NodeList 객체를 반환해야 하며, 항상 동일한 값을 반환해야 합니다. 그러나 input 요소의 type 속성이 숨김 상태인 경우, 대신 null을 반환해야 합니다.

ElementInternals/labels

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

폼 관련 사용자 정의 요소에는 labels IDL 속성이 없습니다. 대신, 해당 ElementInternals 객체에는 labels IDL 속성이 있으며, 이를 가져올 때 "NotSupportedError" DOMException을 발생시키며, 대상 요소폼 관련 사용자 정의 요소가 아닌 경우 발생해야 합니다. 그렇지 않은 경우, 해당 NodeList 객체를 반환해야 하며, 동일한 값을 반환해야 합니다.

이 (비준수) 예제는 NodeList에 어떤 일이 발생하는지 보여줍니다. labels가 반환되며, input 요소에 type 속성이 변경됩니다.

<!doctype html>
<p><label><input></label></p>
<script>
 const input = document.querySelector('input');
 const labels = input.labels;
 console.assert(labels.length === 1);

 input.type = 'hidden';
 console.assert(labels.length === 0); // 이제 input은 label의 라벨된 제어가 아닙니다.
 console.assert(input.labels === null);

 input.type = 'checkbox';
 console.assert(labels.length === 1); // 이제 input은 다시 label의 라벨된 제어입니다.
 console.assert(input.labels === labels); // 처음 반환된 동일한 값입니다.
</script>

4.10.5 input 요소

Element/input

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (구 버전)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android1+Samsung Internet?Opera Android12.1+

Element/input

HTMLInputElement

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (구 버전)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
type 속성이 숨김 상태가 아닌 경우: 인터랙티브 콘텐츠.
type 속성이 숨김 상태가 아닌 경우: 리스트됨, 라벨 가능, 제출 가능, 리셋 가능, 그리고 자동 대문자화 상속 폼 관련 요소.
type 속성이 숨김 상태인 경우: 리스트됨, 제출 가능, 리셋 가능, 그리고 자동 대문자화 상속 폼 관련 요소.
type 속성이 숨김 상태가 아닌 경우: 지각 가능한 콘텐츠.
이 요소를 사용할 수 있는 맥락:
구문 콘텐츠가 예상되는 경우.
콘텐츠 모델:
없음.
text/html에서 태그 생략:
어떠한 종료 태그도 없습니다.
콘텐츠 속성:
전역 속성
accept파일 업로드 컨트롤에서 예상되는 파일 형식에 대한 힌트
alt — 이미지가 제공되지 않을 때 사용되는 대체 텍스트
autocomplete — 폼 자동 완성 기능에 대한 힌트
checked — 컨트롤이 선택되었는지 여부
dirname방향성폼 제출에서 전송하는 데 사용할 폼 컨트롤의 이름
disabled — 폼 컨트롤이 비활성화되었는지 여부
formform 요소와 요소를 연결합니다.
formactionURL폼 제출에 사용할 URL
formenctype엔트리 목록폼 제출에 사용할 인코딩 타입
formmethod폼 제출에 사용할 방법
formnovalidate폼 제출을 위한 폼 컨트롤 검증을 우회합니다.
formtarget탐색 가능폼 제출에 사용
height — 수직 크기
list — 자동 완성 옵션 목록
max — 최대 값
maxlength — 값의 최대 길이
min — 최소 값
minlength — 값의 최소 길이
multiple — 여러 값을 허용할지 여부
name폼 제출form.elements API에서 사용할 요소의 이름
pattern — 폼 컨트롤의 값이 일치해야 하는 패턴
placeholder — 폼 컨트롤 내에 표시되는 사용자 가시성 레이블
popovertarget — 토글, 표시 또는 숨길 팝오버 요소를 대상으로 합니다.
popovertargetaction — 대상 팝오버 요소를 토글, 표시 또는 숨길지 여부를 나타냅니다.
readonly — 사용자가 값을 편집할 수 있는지 여부
required폼 제출을 위해 이 컨트롤이 필수인지 여부
size — 컨트롤의 크기
src — 리소스의 주소
step — 폼 컨트롤의 값이 일치해야 하는 세부 정도
type — 폼 컨트롤의 유형
value — 폼 컨트롤의 값
width — 수평 크기
또한, title 속성은 이 요소에 대해 특별한 의미를 가지고 있습니다. ( pattern 속성과 함께 사용될 때 패턴의 설명 )
접근성 고려사항:
type 속성이 숨김 상태에 있을 때: 작성자용; 구현자용.
type 속성이 텍스트 상태에 있을 때: 작성자용; 구현자용.
type 속성이 검색 상태에 있을 때: 작성자용; 구현자용.
type 속성이 전화 상태에 있을 때: 작성자용; 구현자용.
type 속성이 URL 상태에 있을 때: 작성자용; 구현자용.
type 속성이 이메일 상태에 있을 때: 작성자용; 구현자용.
type 속성이 패스워드 상태에 있을 때: 작성자용; 구현자용.
type 속성이 날짜 상태에 있을 때: 작성자용; 구현자용.
type 속성이 상태에 있을 때: 작성자용; 구현자용.
type 속성이 상태에 있을 때: 작성자용; 구현자용.
type 속성이 시간 상태에 있을 때: 작성자용; 구현자용.
type 속성이 로컬 날짜 및 시간 상태에 있을 때: 작성자용; 구현자용.
type 속성이 숫자 상태에 있을 때: 작성자용; 구현자용.
type 속성이 범위 상태에 있을 때: 작성자용; 구현자용.
type 속성이 색상 상태에 있을 때: 작성자용; 구현자용.
type 속성이 체크박스 상태에 있을 때: 작성자용; 구현자용.
type 속성이 라디오 버튼 상태에 있을 때: 작성자용; 구현자용.
type 속성이 파일 업로드 상태에 있을 때: 작성자용; 구현자용.
type 속성이 제출 버튼 상태에 있을 때: 작성자용; 구현자용.
type 속성이 이미지 버튼 상태에 있을 때: 작성자용; 구현자용.
type 속성이 리셋 버튼 상태에 있을 때: 작성자용; 구현자용.
type 속성이 버튼 상태에 있을 때: 작성자용; 구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLInputElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString accept;
  [CEReactions] attribute DOMString alt;
  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute boolean defaultChecked;
  attribute boolean checked;
  [CEReactions] attribute DOMString dirName;
  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute FileList? files;
  [CEReactions] attribute USVString formAction;
  [CEReactions] attribute DOMString formEnctype;
  [CEReactions] attribute DOMString formMethod;
  [CEReactions] attribute boolean formNoValidate;
  [CEReactions] attribute DOMString formTarget;
  [CEReactions] attribute unsigned long height;
  attribute boolean indeterminate;
  readonly attribute HTMLDataListElement? list;
  [CEReactions] attribute DOMString max;
  [CEReactions] attribute long maxLength;
  [CEReactions] attribute DOMString min;
  [CEReactions] attribute long minLength;
  [CEReactions] attribute boolean multiple;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString pattern;
  [CEReactions] attribute DOMString placeholder;
  [CEReactions] attribute boolean readOnly;
  [CEReactions] attribute boolean required;
  [CEReactions] attribute unsigned long size;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString step;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString defaultValue;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString value;
  attribute object? valueAsDate;
  attribute unrestricted double valueAsNumber;
  [CEReactions] attribute unsigned long width;

  undefined stepUp(optional long n = 1);
  undefined stepDown(optional long n = 1);

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList? labels;

  undefined select();
  attribute unsigned long? selectionStart;
  attribute unsigned long? selectionEnd;
  attribute DOMString? selectionDirection;
  undefined setRangeText(DOMString replacement);
  undefined setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  undefined setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);

  undefined showPicker();

  // also has obsolete members
};
HTMLInputElement includes PopoverInvokerElement;

input 요소는 표현 형식화된 데이터 필드를 나타내며, 일반적으로 사용자가 데이터를 편집할 수 있는 폼 컨트롤과 함께 제공됩니다.

type 속성은 요소의 데이터 유형(및 관련 컨트롤)을 제어합니다. 이 속성은 다음 키워드와 상태를 가진 열거형 속성입니다.

키워드 상태 데이터 유형 컨트롤 유형
hidden 숨김 임의의 문자열 n/a
text 텍스트 줄바꿈이 없는 텍스트 텍스트 컨트롤
search 검색 줄바꿈이 없는 텍스트 검색 컨트롤
tel 전화번호 줄바꿈이 없는 텍스트 텍스트 컨트롤
url URL 절대 URL 텍스트 컨트롤
email 이메일 이메일 주소 또는 이메일 주소 목록 텍스트 컨트롤
password 비밀번호 줄바꿈이 없는 텍스트 (민감한 정보) 데이터를 가리는 텍스트 컨트롤
date 날짜 시간대가 없는 날짜 (년, 월, 일) 날짜 컨트롤
month 시간대가 없는 연도와 월로 구성된 날짜 월 컨트롤
week 시간대가 없는 주-연도 번호와 주 번호로 구성된 날짜 주 컨트롤
time 시간 시간대가 없는 시간 (시간, 분, 초, 초의 소수 부분) 시간 컨트롤
datetime-local 로컬 날짜 및 시간 시간대가 없는 날짜와 시간 (년, 월, 일, 시간, 분, 초, 소수 초) 날짜 및 시간 컨트롤
number 숫자 수치 값 텍스트 컨트롤 또는 스피너 컨트롤
range 범위 정확한 값이 중요하지 않은 수치 값 슬라이더 컨트롤 또는 유사한 컨트롤
color 색상 8비트 빨강, 초록, 파랑 구성 요소가 있는 sRGB 색상 색상 선택기
checkbox 체크박스 미리 정의된 목록에서 0개 이상의 값 선택 체크박스
radio 라디오 버튼 열거된 값 라디오 버튼
file 파일 업로드 MIME 타입과 선택적으로 파일 이름을 가진 0개 이상의 파일 레이블 및 버튼
submit 제출 버튼 선택한 마지막 값이며 폼 제출을 시작하는 추가 의미를 가진 열거된 값 버튼
image 이미지 버튼 이미지의 크기에 상대적인 좌표로, 선택한 마지막 값이며 폼 제출을 시작하는 추가 의미를 가짐 클릭 가능한 이미지 또는 버튼
reset 리셋 버튼 n/a 버튼
button 버튼 n/a 버튼

속성의 누락된 값 기본값잘못된 값 기본값은 모두 텍스트 상태입니다.

어떤 accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, width 콘텐츠 속성, checked, files, valueAsDate, valueAsNumber, list IDL 속성, select() 메서드, selectionStart, selectionEnd, selectionDirection IDL 속성, setRangeText()setSelectionRange() 메서드, stepUp()stepDown() 메서드, inputchange 이벤트가 input 요소에 적용되는지 여부는 그 요소의 type 속성의 상태에 따라 달라집니다. 각 타입을 정의하는 하위 섹션은 이러한 기능 중 어떤 것이 각 타입에 적용되는지, 그리고 어떤 것이 적용되지 않는지를 명시적으로 정의하며, 이러한 기능의 동작은 해당 섹션에서 정의된 대로 적용 여부에 따라 다릅니다(콘텐츠 속성, API, 이벤트 참고).

다음 표는 비규범적이며 이러한 콘텐츠 속성, IDL 속성, 메서드 및 이벤트가 각 상태에 적용되는지를 요약한 것입니다:

Hidden Text, Search Telephone, URL Email Password Date, Month, Week, Time Local Date and Time Number Range Color Checkbox, Radio Button File Upload Submit Button Image Button Reset Button, Button
Content attributes
accept · · · · · · · · · · · Yes · · ·
alt · · · · · · · · · · · · · Yes ·
autocomplete Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · · · ·
checked · · · · · · · · · · Yes · · · ·
dirname Yes Yes Yes Yes Yes · · · · · · · Yes · ·
formaction · · · · · · · · · · · · Yes Yes ·
formenctype · · · · · · · · · · · · Yes Yes ·
formmethod · · · · · · · · · · · · Yes Yes ·
formnovalidate · · · · · · · · · · · · Yes Yes ·
formtarget · · · · · · · · · · · · Yes Yes ·
height · · · · · · · · · · · · · Yes ·
list · Yes Yes Yes · Yes Yes Yes Yes Yes · · · · ·
max · · · · · Yes Yes Yes Yes · · · · · ·
maxlength · Yes Yes Yes Yes · · · · · · · · · ·
min · · · · · Yes Yes Yes Yes · · · · · ·
minlength · Yes Yes Yes Yes · · · · · · · · · ·
multiple · · · Yes · · · · · · · Yes · · ·
pattern · Yes Yes Yes Yes · · · · · · · · · ·
placeholder · Yes Yes Yes Yes · · Yes · · · · · · ·
popovertarget · · · · · · · · · · · · Yes Yes Yes
popovertargetaction · · · · · · · · · · · · Yes Yes Yes
readonly · Yes Yes Yes Yes Yes Yes Yes · · · · · · ·
required · Yes Yes Yes Yes Yes Yes Yes · · Yes Yes · · ·
size · Yes Yes Yes Yes · · · · · · · · · ·
src · · · · · · · · · · · · · Yes ·
step · · · · · Yes Yes Yes Yes · · · · · ·
width · · · · · · · · · · · · · Yes ·
IDL attributes and methods
checked · · · · · · · · · · Yes · · · ·
files · · · · · · · · · · · Yes · · ·
value default value value value value value value value value value default/on filename default default default
valueAsDate · · · · · Yes · · · · · · · · ·
valueAsNumber · · · · · Yes Yes Yes Yes · · · · · ·
list · Yes Yes Yes · Yes Yes Yes Yes Yes · · · · ·
select() · Yes Yes Yes† Yes Yes† Yes† Yes† · Yes† · Yes† · · ·
selectionStart · Yes Yes · Yes · · · · · · · · · ·
selectionEnd · Yes Yes · Yes · · · · · · · · · ·
selectionDirection · Yes Yes · Yes · · · · · · · · · ·
setRangeText() · Yes Yes · Yes · · · · · · · · · ·
setSelectionRange() · Yes Yes · Yes · · · · · · · · · ·
stepDown() · · · · · Yes Yes Yes Yes · · · · · ·
stepUp() · · · · · Yes Yes Yes Yes · · · · · ·
Events
input event · Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · ·
change event · Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · ·

† 선택할 수 있는 텍스트가 없으면, select() 메서드는 아무 작업도 하지 않으며, "InvalidStateError" DOMException이 발생하지 않습니다.

일부 type 속성의 상태는 값 정리 알고리즘을 정의합니다.

input 요소는 을 가지며, 이는 value IDL 속성으로 노출됩니다. 일부 상태는 문자열을 숫자로 변환하는 알고리즘(algorithm to convert a string to a number), 숫자를 문자열로 변환하는 알고리즘(algorithm to convert a number to a string), 문자열을 Date 객체로 변환하는 알고리즘(algorithm to convert a string to a Date object), Date 객체를 문자열로 변환하는 알고리즘(algorithm to convert a Date object to a string)을 정의하며, 이는 max, min, step, valueAsDate, valueAsNumber, stepUp()에서 사용됩니다.

사용자가 컨트롤을 조작하여 을 변경할 때마다 input 요소의 변경된 값 플래그는 true로 설정되어야 합니다. (값이 프로그래밍적으로 변경될 때도 value IDL 속성의 정의에 따라 true로 설정됩니다.)

value 콘텐츠 속성은 input 요소의 기본 을 제공합니다. value 콘텐츠 속성이 추가되거나 설정되거나 제거될 때, 제어의 변경된 값 플래그가 false라면, 사용자 에이전트는 요소의 값을 value 콘텐츠 속성의 값으로 설정해야 하며, 값이 정의된 경우 값 정리 알고리즘을 실행해야 합니다.

input 요소는 체크 상태를 가지며, 이는 checked IDL 속성으로 노출됩니다.

input 요소는 불리언 변경된 체크 상태 플래그를 가집니다. 플래그가 true로 설정되면, 요소는 변경된 체크 상태를 가지게 됩니다. 변경된 체크 상태 플래그는 요소가 생성될 때 false로 설정되어야 하며, 사용자가 체크 상태를 변경하는 방식으로 컨트롤을 조작할 때마다 true로 설정되어야 합니다.

요소/input#checked

모든 현재 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

checked 콘텐츠 속성은 불리언 속성으로, input 요소의 기본 체크 상태를 제공합니다. checked 콘텐츠 속성이 추가되면, 제어가 변경된 체크 상태를 가지지 않은 경우 사용자 에이전트는 요소의 체크 상태를 true로 설정해야 합니다. checked 콘텐츠 속성이 제거되면, 제어가 변경된 체크 상태를 가지지 않은 경우 사용자 에이전트는 요소의 체크 상태를 false로 설정해야 합니다.

리셋 알고리즘input 요소의 사용자 유효성, 변경된 값 플래그, 변경된 체크 상태 플래그를 false로 되돌리고, 요소의 값을 value 콘텐츠 속성의 값으로 설정하거나, 없다면 빈 문자열로 설정하며, 요소가 checked 콘텐츠 속성을 가지고 있으면 체크 상태를 true로, 그렇지 않으면 false로 설정해야 하며, 선택된 파일 목록을 비우고, 현재 상태가 정의된 경우 값 정리 알고리즘을 실행해야 합니다.

input 요소는 변경 가능일 수 있습니다. 명시되지 않은 경우를 제외하고, input 요소는 항상 변경 가능입니다. 마찬가지로 명시되지 않은 경우를 제외하고, 사용자 에이전트는 사용자가 요소의 또는 체크 상태를 수정할 수 없도록 해야 합니다.

input 요소가 비활성화된 경우, 변경 가능하지 않습니다.

readonly 속성은 일부 경우(예: 날짜 상태, 그러나 체크박스 상태는 아님)에 input 요소가 변경 가능이 되는 것을 막을 수 있습니다.

복제 단계input 요소의 값을 , 변경된 값 플래그, 체크 상태, 변경된 체크 상태 플래그를 복사본에 전달해야 합니다.

활성화 동작input 요소의 element와 주어진 event에 대해 다음 단계를 따릅니다:

  1. element변경 가능하지 않으며, 체크박스 상태에 있지 않으며, 라디오 버튼 상태에 있지 않은 경우, 반환합니다.

  2. element입력 활성화 동작을 실행하고, 다른 작업은 수행하지 않습니다.

  3. 팝오버 타겟 속성 활성화 동작element에서 실행합니다.

요소의 활성화 동작은 사용자에 의해 시작된 활성화와 el.click()와 같은 합성 활성화 모두에 대해 실행된다는 점을 기억하십시오. 사용자 에이전트는 이곳에 명시되지 않은 특정 제어 동작을 가질 수도 있으며, 이는 진정한 사용자에 의해 시작된 활성화에서만 트리거됩니다. 일반적인 선택은 해당 제어를 위한 선택기를 보여주는 것입니다. 반면에, 입력 활성화 동작파일 업로드색상 상태와 같은 특별한 역사적 경우에만 선택기를 표시합니다.

레거시 사전 활성화 동작input 요소에 대해 다음 단계를 따릅니다:

  1. 이 요소의 type 속성이 체크박스 상태에 있으면, 이 요소의 체크 상태를 반대 값으로 설정하고(즉, true이면 false로, false이면 true로), 이 요소의 indeterminate IDL 속성을 false로 설정합니다.

  2. 이 요소의 type 속성이 라디오 버튼 상태에 있으면, 이 요소의 라디오 버튼 그룹에서 체크 상태가 true로 설정된 요소에 대한 참조를 얻고, 이 요소의 체크 상태를 true로 설정합니다.

레거시 취소된 활성화 동작input 요소에 대해 다음 단계를 따릅니다:

  1. 이 요소의 type 속성이 체크박스 상태에 있으면, 이 요소의 체크 상태indeterminate IDL 속성을 레거시 사전 활성화 동작이 실행되기 전의 값으로 되돌립니다.

  2. 이 요소의 type 속성이 라디오 버튼 상태에 있으면, 이 요소의 레거시 사전 활성화 동작에서 얻은 참조가 여전히 이 요소의 라디오 버튼 그룹에 있으면, 그 요소의 체크 상태를 true로 설정합니다. 참조된 요소가 없거나, 그 요소가 더 이상 이 요소의 라디오 버튼 그룹에 없거나, 이 요소가 더 이상 라디오 버튼 그룹을 가지고 있지 않으면, 이 요소의 체크 상태를 false로 설정합니다.


처음 input 요소가 생성될 때, 해당 요소의 렌더링과 동작은 type 속성의 상태에 따라 설정되어야 하며, 만약 정의된 경우 값 정리 알고리즘이 실행되어야 합니다.

input 요소의 type 속성이 변경될 때, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. 이전 type 속성 상태가 value IDL 속성을 value 모드로 설정했으며, 요소의 이 빈 문자열이 아니고, 새로운 type 속성 상태가 value IDL 속성을 기본값 모드 또는 기본값/켜짐 모드로 설정하면, 요소의 value 콘텐츠 속성을 요소의 으로 설정합니다.

  2. 그렇지 않으면, 이전 type 속성 상태가 value IDL 속성을 value 모드 이외의 모드로 설정했고, 새로운 type 속성 상태가 value IDL 속성을 value 모드로 설정하면, 요소의 을 콘텐츠 속성의 값으로 설정하고, 만약 값이 없으면 빈 문자열로 설정한 다음, 제어의 변경된 값 플래그를 false로 설정합니다.

  3. 그렇지 않으면, 이전 type 속성 상태가 value IDL 속성을 파일 이름 모드 이외의 모드로 설정했고, 새로운 type 속성 상태가 value IDL 속성을 파일 이름 모드로 설정하면, 요소의 을 빈 문자열로 설정합니다.

  4. 요소의 렌더링과 동작을 새로운 상태로 업데이트합니다.

  5. 요소에 대해 타입 변경 신호를 보냅니다. (특히 라디오 버튼 상태에서 사용됩니다.)

  6. 새로운 type 속성 상태에 대해 정의된 경우, 값 정리 알고리즘을 실행합니다.

  7. 이전에 setRangeText()가 요소에 적용되었는지 여부를 판단하여 previouslySelectable 값을 설정합니다.

  8. 이제 setRangeText()가 요소에 적용되었는지 여부를 판단하여 nowSelectable 값을 설정합니다.

  9. 만약 previouslySelectable 값이 false이고 nowSelectable 값이 true라면, 요소의 텍스트 입력 커서 위치를 텍스트 컨트롤의 시작 부분으로 설정하고, 선택 방향을 "none"으로 설정합니다.


name 속성은 요소의 이름을 나타냅니다. dirname 속성은 요소의 방향성이 제출되는 방식을 제어합니다. disabled 속성은 제어를 비활성화하고 값을 제출하는 것을 방지하는 데 사용됩니다. form 속성은 input 요소를 폼 소유자와 명시적으로 연결하는 데 사용됩니다. autocomplete 속성은 사용자 에이전트가 자동 완성 동작을 제공하는 방식을 제어합니다.

HTMLInputElement#indeterminate

모든 현재 엔진에서 지원됩니다.

Firefox3.6+Safari3+Chrome1+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android≤12.1+
caniuse.com 표

indeterminate IDL 속성은 초기에는 false로 설정되어야 합니다. 가져올 때, 마지막으로 설정된 값을 반환해야 합니다. 설정할 때, 새로운 값으로 설정해야 합니다. 이는 체크박스 제어의 모양을 변경하는 것 외에는 아무런 효과가 없습니다.

HTMLInputElement/multiple

모든 현재 엔진에서 지원됩니다.

Firefox3.6+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

accept, alt, max, min, multiple, pattern, placeholder, required, size, src, 그리고 step IDL 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다. dirName IDL 속성은 dirname 콘텐츠 속성을 반영해야 합니다. readOnly IDL 속성은 readonly 콘텐츠 속성을 반영해야 합니다. defaultChecked IDL 속성은 checked 콘텐츠 속성을 반영해야 합니다. defaultValue IDL 속성은 value 콘텐츠 속성을 반영해야 합니다.

type IDL 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다. maxLength IDL 속성은 maxlength 콘텐츠 속성을 반영해야 하며, 음수가 아닌 숫자로만 제한됩니다. minLength IDL 속성은 minlength 콘텐츠 속성을 반영해야 하며, 음수가 아닌 숫자로만 제한됩니다.

IDL 속성 widthheight는 이미지가 렌더링 중일 경우, CSS 픽셀로 표시된 이미지의 렌더링된 너비와 높이를 반환해야 하며, 그렇지 않은 경우, 이미지가 사용 가능하지만 렌더링 중이 아닐 경우, 자연 너비와 높이를 CSS 픽셀로 반환해야 하며, 그렇지 않으면 0을 반환해야 합니다. input 요소의 type 속성이 이미지 버튼 상태에 있지 않은 경우, 이미지가 사용 가능하지 않습니다. [CSS]

설정 시, 해당 속성들은 동일한 이름의 해당 콘텐츠 속성을 반영하는 것처럼 작동해야 합니다.

willValidate, validity, 그리고 validationMessage IDL 속성과 checkValidity(), reportValidity(), 그리고 setCustomValidity() 메서드는 제약 조건 검증 API의 일부입니다. labels IDL 속성은 요소의 라벨 목록을 제공합니다. select(), selectionStart, selectionEnd, selectionDirection, setRangeText(), 그리고 setSelectionRange() 메서드 및 IDL 속성은 요소의 텍스트 선택을 노출합니다. disabled, form, 그리고 name IDL 속성은 요소의 폼 API의 일부입니다.

4.10.5.1 type 속성의 상태
4.10.5.1.1 숨김 상태 (type=hidden)

Element/input/hidden

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (레거시)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 input 요소의 type 속성이 숨김 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 표시된 값이 사용자에 의해 검사되거나 조작될 의도가 없는 값입니다.

제약 조건 유효성 검사: 만약 input 요소의 type 속성이 숨김 상태에 있을 때, 제약 조건 유효성 검사에서 제외됩니다.

만약 name 속성이 존재하고 그 값이 ASCII 대소문자 구분 없음으로 "_charset_" 와 일치하는 경우, 요소의 value 속성은 생략해야 합니다.

autocompletedirname 콘텐츠 속성이 적용됩니다.

value IDL 속성이 적용 되며 기본 모드에 있습니다 기본값.

다음 콘텐츠 속성은 지정되어서는 안 되며 적용되지 않습니다: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, readonly, required, size, src, step, 및 width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 및 valueAsNumber IDL 속성; select(), setRangeText(), setSelectionRange(), stepDown(), 및 stepUp() 메서드.

inputchange 이벤트는 적용되지 않습니다.

4.10.5.1.2 텍스트 (type=text) 상태 및 검색 상태 (type=search)

Element/input/search

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome5+
Opera10.6+Edge79+
Edge (레거시)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Element/input/text

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (레거시)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

입력(input) 요소의 type 속성이 텍스트 상태 또는 검색 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

입력(input) 요소는 표시 요소의 을 위한 한 줄짜리 일반 텍스트 편집 컨트롤을 나타냅니다.

텍스트 상태와 검색 상태의 차이는 주로 스타일에 있습니다: 검색 컨트롤이 일반 텍스트 컨트롤과 구별되는 플랫폼에서는 검색 상태가 플랫폼의 검색 컨트롤과 일관된 모양으로 나타날 수 있으며, 일반 텍스트 컨트롤처럼 보이지 않을 수 있습니다.

요소가 변경 가능한 경우, 사용자가 요소의 을 편집할 수 있어야 합니다. 사용자 에이전트는 사용자가 요소의 에 U+000A 줄 바꿈 (LF) 또는 U+000D 캐리지 리턴 (CR) 문자를 삽입할 수 없도록 해야 합니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 요소의 쓰기 방향을 변경할 수 있도록 해야 하며, 이를 왼쪽에서 오른쪽으로 또는 오른쪽에서 왼쪽으로 설정할 수 있어야 합니다. 사용자가 이렇게 하면, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. 사용자가 왼쪽에서 오른쪽으로 쓰기 방향을 선택한 경우, 요소의 dir 속성을 "ltr" 로 설정하고, 사용자가 오른쪽에서 왼쪽으로 쓰기 방향을 선택한 경우에는 "rtl" 로 설정합니다.

  2. 요소 작업을 대기열에 추가하여 사용자 상호작용 작업 출처에서 요소가 이벤트를 발생시키도록 합니다. 이벤트의 이름은 input 이며, 버블링구성됨 속성은 true로 초기화됩니다.

속성이 지정된 경우, 해당 속성의 값에는 U+000A 줄 바꿈 (LF) 또는 U+000D 캐리지 리턴 (CR) 문자가 포함되지 않아야 합니다.

값 정리 알고리즘은 다음과 같습니다: 줄 바꿈 제거 에서.

다음의 공통 input 요소 내용 속성, IDL 속성 및 메서드가 요소에 적용됩니다: autocomplete, dirname, list, maxlength, minlength, pattern, placeholder, readonly, required, and size 내용 속성; list, selectionStart, selectionEnd, selectionDirection, and value IDL 속성; select(), setRangeText(), and setSelectionRange() 메서드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음의 내용 속성은 지정되어서는 안 되며 적용되지 않습니다: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, popovertarget, popovertargetaction, src, step, and width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: checked, files, valueAsDate, and valueAsNumber IDL 속성; stepDown() and stepUp() 메서드.

4.10.5.1.3 전화 상태 (type=tel)

Element/input/tel

모든 현재 엔진에서 지원됩니다.

FirefoxSafari4+Chrome3+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet?Opera Android11+

input 요소의 type 속성이 전화 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 전화번호를 편집하기 위한 제어를 나타냅니다. 요소의 으로 제공됩니다.

요소가 변경 가능한 경우, 사용자가 을 편집할 수 있어야 합니다. 사용자 에이전트는 사용자가 입력한 의 공백과 문장 부호를 변경할 수 있습니다. 사용자 에이전트는 사용자가 요소의 에 U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자를 삽입하지 못하게 해야 합니다.

속성은, 지정된 경우, U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자가 포함되지 않은 값을 가져야 합니다.

값 정리 알고리즘은 다음과 같습니다: 새 줄 제거 에서.

전화번호 유형은 URL이메일 유형과 달리 특정 구문을 강제하지 않습니다. 이는 의도된 것입니다. 실제로 전화번호 필드는 다양한 유효한 전화번호가 있기 때문에 일반적으로 자유형식 필드로 사용됩니다. 특정 형식을 강제해야 하는 시스템은 패턴 속성이나 setCustomValidity() 메서드를 사용하여 클라이언트 측 유효성 검사 메커니즘에 연결하는 것이 좋습니다.

다음의 일반적인 input 요소 콘텐츠 속성, IDL 속성 및 메서드 적용: autocomplete, dirname, list, maxlength, minlength, pattern, placeholder, readonly, required, and size 콘텐츠 속성; list, selectionStart, selectionEnd, selectionDirection, and value IDL 속성; select(), setRangeText(), and setSelectionRange() 메서드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음 콘텐츠 속성은 지정되지 않아야 하며 적용되지 않습니다: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, popovertarget, popovertargetaction, src, step, and width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: checked, files, valueAsDate, and valueAsNumber IDL 속성; stepDown() and stepUp() 메서드.

4.10.5.1.4 URL 상태 (type=url)

Element/input/url

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

input 요소의 type 속성이 URL 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 편집을 위한 제어를 나타냅니다. 하나의 절대 URL이 요소의 으로 제공됩니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 으로 표시된 URL을 변경할 수 있도록 해야 합니다. 사용자 에이전트는 사용자가 유효한 절대 URL이 아닌 문자열로 설정하도록 허용할 수 있지만, 대신에 또는 추가로 사용자가 입력한 문자를 자동으로 이스케이프하여 이 항상 유효한 절대 URL이 되도록 할 수 있습니다 (이 값이 사용자가 인터페이스에서 실제로 보고 수정한 값이 아닐지라도). 사용자 에이전트는 사용자가 을 빈 문자열로 설정할 수 있도록 해야 합니다. 사용자 에이전트는 사용자가 에 U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자를 삽입하도록 허용해서는 안 됩니다.

속성은 지정되어 있고 비어 있지 않은 경우, 공백으로 둘러싸일 수 있는 유효한 URL이어야 하며, 또한 절대 URL이어야 합니다.

값 위생 알고리즘은 다음과 같습니다: 새 줄 제거 에서, 그 후 선행 및 후행 ASCII 공백 제거 에서.

제약 조건 유효성 검사: 요소의 이 빈 문자열도 아니고 유효한 절대 URL도 아닌 경우, 요소는 타입 불일치 상태입니다.

다음은 공통 input 요소 콘텐츠 속성, IDL 속성 및 메소드 적용됨: autocomplete, dirname, list, maxlength, minlength, pattern, placeholder, readonly, required, 그리고 size 콘텐츠 속성; list, selectionStart, selectionEnd, selectionDirection, 및 value IDL 속성; select(), setRangeText(), 및 setSelectionRange() 메소드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됨.

다음 콘텐츠 속성은 지정할 수 없으며 적용되지 않습니다: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, popovertarget, popovertargetaction, src, step, 및 width.

다음 IDL 속성과 메소드는 적용되지 않습니다: checked, files, valueAsDate, 및 valueAsNumber IDL 속성; stepDown()stepUp() 메소드.

문서에 다음과 같은 마크업이 포함된 경우:

<input type="url" name="location" list="urls">
<datalist id="urls">
<option label="MIME: Format of Internet Message Bodies" value="https://www.rfc-editor.org/rfc/rfc2045">
<option label="HTML" value="https://html.spec.whatwg.org/">
<option label="DOM" value="https://dom.spec.whatwg.org/">
<option label="Fullscreen" value="https://fullscreen.spec.whatwg.org/">
<option label="Media Session" value="https://mediasession.spec.whatwg.org/">
<option label="The Single UNIX Specification, Version 3" value="http://www.unix.org/version3/">
</datalist>

...사용자가 "spec.w"를 입력하고 사용자 에이전트가 최근에 https://url.spec.whatwg.org/#url-parsinghttps://streams.spec.whatwg.org/를 방문한 경우, 렌더링은 다음과 같이 보일 수 있습니다:

왼쪽에 아이콘이 있는 텍스트 상자와 그 오른쪽에 'spec.w'라는 텍스트와 커서가 있으며 오른쪽에는 드롭다운 버튼이 있고, 아래에는 왼쪽에 6개의 URL이 있는 드롭다운 박스가 있으며, 첫 4개는 오른쪽에 회색으로 표시된 레이블이 있고, 드롭다운 박스 오른쪽에는 추가 값이 있음을 나타내는 스크롤바가 있습니다.

이 샘플의 처음 네 개의 URL은 사용자가 입력한 텍스트와 일치하는 작성자가 지정한 URL 목록의 URL을 포함하며, 일부 구현 정의 방식으로 정렬됩니다 (아마도 사용자가 해당 URL을 참조한 빈도에 따라). UA가 값이 URL임을 이용하여 사용자가 스킴 부분을 생략할 수 있게 하고 도메인 이름에 대해 지능적으로 일치시키는 방식을 주목하세요.

마지막 두 개의 URL(및 스크롤바의 추가 값 표시로 보아 아마 더 많은 URL이 있을 것 같습니다)은 사용자 에이전트의 세션 기록 데이터에서 일치한 것입니다. 이 데이터는 페이지 DOM에 제공되지 않습니다. 이 경우 UA는 이러한 값에 대한 제목을 제공할 수 없습니다.

4.10.5.1.5 이메일 상태 (type=email)

Element/input/email

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari5+Chrome5+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

만약 input 요소의 type 속성이 이메일 상태일 때, 이 섹션의 규칙이 적용됩니다.

이메일 상태가 작동하는 방식은 multiple 속성의 지정 여부에 따라 달라집니다.

multiple 속성이 요소에 지정되지 않은 경우

input 요소는 대표하는 제어를 제공하여 이메일 주소를 편집합니다. 이는 요소의 입니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 이메일 주소를 변경할 수 있도록 허용해야 합니다. 사용자 에이전트는 사용자가 유효한 이메일 주소가 아닌 문자열로 설정하는 것을 허용할 수 있습니다. 사용자 에이전트는 사용자가 단일 이메일 주소를 제공할 것으로 기대하고 행동해야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정하도록 허용해야 합니다. 사용자 에이전트는 사용자가 에 U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자를 삽입하는 것을 허용해서는 안 됩니다. 사용자 에이전트는 을 표시 및 편집을 위해 변환할 수 있습니다; 특히 사용자 에이전트는 의 도메인 레이블에서 punycode를 IDN으로 변환하고 그 반대도 수행해야 합니다.

제약 조건 유효성 검사: 사용자 인터페이스가 사용자 에이전트가 punycode로 변환할 수 없는 입력을 나타내는 경우, 제어는 잘못된 입력으로 인한 문제를 겪고 있습니다.

속성이 지정되어 있고 비어 있지 않은 경우, 값은 단일 유효한 이메일 주소여야 합니다.

값 정리 알고리즘은 다음과 같습니다: 줄바꿈 제거 요소의 에서, 그 다음에 앞뒤 ASCII 공백 제거를 요소의 에서 수행합니다.

제약 조건 유효성 검사: 요소의 이 빈 문자열도 아니고 단일 유효한 이메일 주소도 아닌 경우, 요소는 유형 불일치로 인한 문제를 겪고 있습니다.

multiple 속성이 요소에 지정된 경우

input 요소는 대표하는 제어를 제공하여 이메일 주소를 추가, 제거 및 편집합니다. 이는 요소의 입니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 이메일 주소를 추가, 제거 및 편집할 수 있도록 허용해야 합니다. 사용자 에이전트는 사용자가 목록의 개별 값을 유효한 이메일 주소가 아닌 문자열로 설정하는 것을 허용할 수 있지만, U+002C COMMA (,) 또는 U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자를 포함하는 문자열로 개별 값을 설정하는 것은 허용하지 않아야 합니다. 사용자 에이전트는 요소의 에서 모든 주소를 제거하도록 허용해야 합니다. 사용자 에이전트는 을 표시 및 편집을 위해 변환할 수 있습니다; 특히 사용자 에이전트는 의 도메인 레이블에서 punycode를 IDN으로 변환하고 그 반대도 수행해야 합니다.

제약 조건 유효성 검사: 사용자 인터페이스가 개별 값에 U+002C COMMA (,)가 포함되어 있거나 사용자 에이전트가 punycode로 변환할 수 없는 입력을 나타내는 경우, 제어는 잘못된 입력으로 인한 문제를 겪고 있습니다.

사용자가 요소의 을 변경할 때마다, 사용자 에이전트는 다음 단계들을 실행해야 합니다:

  1. 최신 값을 요소의 의 복사본으로 설정합니다.

  2. 앞뒤 ASCII 공백 제거최신 값의 각 값에서 수행합니다.

  3. 요소의 최신 값의 모든 값을 단일 U+002C COMMA 문자 (,)로 구분하여 이어붙인 결과입니다. 목록의 순서를 유지합니다.

속성이 지정된 경우, 값은 유효한 이메일 주소 목록이어야 합니다.

값 정리 알고리즘은 다음과 같습니다:

  1. 쉼표로 분리 요소의 을, 앞뒤 ASCII 공백 제거를 결과 토큰 각각에서 수행하고, 요소의 을 (가능하면 빈) 결과 목록으로 설정합니다. 원래 순서를 유지합니다.

  2. 요소의 은 요소의 을 단일 U+002C COMMA 문자 (,)로 구분하여 이어붙인 결과입니다. 목록의 순서를 유지합니다.

제약 조건 유효성 검사: 요소의 이 유효한 이메일 주소 목록이 아닌 경우, 요소는 유형 불일치로 인한 문제를 겪고 있습니다.

만약 multiple 속성이 설정되거나 제거될 때, 사용자 에이전트는 값 정리 알고리즘을 실행해야 합니다.

유효한 이메일 주소는 다음 ABNF의 email 생성과 일치하는 문자열입니다. 이 ABNF는 RFC 1123에서 설명된 확장을 구현합니다. [ABNF] [RFC5322] [RFC1034] [RFC1123]

email         = 1*( atext / "." ) "@" label *( "." label )
label         = let-dig [ [ ldh-str ] let-dig ]  ; 길이는 RFC 1034의 3.5절에 의해 63자로 제한됨
atext         = < as defined in RFC 5322 section 3.2.3 >
let-dig       = < as defined in RFC 1034 section 3.5 >
ldh-str       = < as defined in RFC 1034 section 3.5 >

이 요구 사항은 이메일 주소의 구문을 정의하는 RFC 5322에 대한 고의적인 위반입니다. 이 표준은 이메일 주소의 구문을 너무 엄격하게(“@” 기호 이전), 너무 모호하게(“@” 기호 이후), 너무 느슨하게(대부분의 사용자에게 익숙하지 않은 주석, 공백 문자 및 인용 문자열 허용) 정의하고 있습니다.

다음 JavaScript 및 Perl 호환 정규 표현식은 위 정의의 구현입니다.

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

유효한 이메일 주소 목록은 각각이 유효한 이메일 주소쉼표로 구분된 토큰 집합입니다. 유효한 이메일 주소 목록에서 토큰 목록을 얻으려면, 구현은 문자열을 쉼표로 분리해야 합니다.

다음의 일반적인 input 요소 콘텐츠 속성, IDL 속성 및 메서드는 적용됩니다: autocomplete, dirname, list, maxlength, minlength, multiple, pattern, placeholder, readonly, required, 및 size 콘텐츠 속성; listvalue IDL 속성; select() 메서드.

value IDL 속성은 모드 value에 있습니다.

inputchange 이벤트가 적용됩니다.

다음 콘텐츠 속성은 지정할 수 없으며 적용되지 않습니다: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, popovertarget, popovertargetaction, src, step, 및 width.

다음 IDL 속성과 메서드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, selectionDirection, valueAsDate, 및 valueAsNumber IDL 속성; setRangeText(), setSelectionRange(), stepDown()stepUp() 메서드.

4.10.5.1.6 Password 상태 (type=password)

Element/input/password

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet Explorer2+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

input 요소의 type 속성이 Password 상태일 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 다음과 같이 나타냅니다 요소의 을 위한 단일 줄의 평문 텍스트 편집 컨트롤입니다. 사용자 에이전트는 값을 가려서 다른 사람이 볼 수 없도록 해야 합니다.

요소가 mutable인 경우, 사용자가 을 편집할 수 있어야 합니다. 사용자 에이전트는 사용자가 에 U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자를 삽입하는 것을 허용해서는 안 됩니다.

value 속성이 지정된 경우, U+000A LINE FEED (LF) 또는 U+000D CARRIAGE RETURN (CR) 문자가 포함되지 않은 값을 가져야 합니다.

값 정리 알고리즘은 다음과 같습니다: 줄바꿈 문자 제거 에서.

다음은 공통 input 요소의 내용 속성, IDL 속성 및 메소드 적용되는 항목입니다: autocomplete, dirname, maxlength, minlength, pattern, placeholder, readonly, required, 그리고 size 내용 속성; selectionStart, selectionEnd, selectionDirection, 및 value IDL 속성; select(), setRangeText(), 및 setSelectionRange() 메소드.

value IDL 속성은 모드 value에 있습니다.

inputchange 이벤트가 적용됩니다.

다음 내용 속성은 지정해서는 안 되며 적용되지 않습니다: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, min, multiple, popovertarget, popovertargetaction, src, step, 및 width.

다음 IDL 속성 및 메소드가 적용되지 않습니다: checked, files, list, valueAsDate, 및 valueAsNumber IDL 속성; stepDown()stepUp() 메소드.

4.10.5.1.7 날짜 상태 (type=date)

Element/input/date

모든 최신 엔진에서 지원됩니다.

Firefox57+Safari14.1+Chrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer지원 안 함
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

input 요소의 type 속성이 날짜 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 요소의 을 특정 날짜를 나타내는 문자열로 설정하는 컨트롤을 대표합니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 날짜으로 변경할 수 있도록 허용해야 하며, 이는 날짜 파싱 을 통해 얻어진 것입니다. 사용자 에이전트는 사용자가 유효한 날짜 문자열이 아닌 비어 있지 않은 문자열로 설정하는 것을 허용해서는 안 됩니다. 사용자 에이전트가 날짜를 선택할 수 있는 사용자 인터페이스를 제공하는 경우, 은 사용자의 선택을 나타내는 유효한 날짜 문자열로 설정해야 합니다. 사용자 에이전트는 사용자가 을 비어 있는 문자열로 설정하는 것을 허용해야 합니다.

제약 조건 유효성 검사: 사용자 인터페이스가 사용자가 유효한 날짜 문자열로 변환할 수 없는 입력을 설명하는 경우, 컨트롤은 잘못된 입력으로 인한 문제를 겪고 있습니다.

날짜, 시간 및 숫자 양식 컨트롤의 입력 형식과 제출 형식 간의 차이와 양식 컨트롤의 지역화와 관련된 구현 노트에 대한 논의는 소개 섹션을 참조하세요.

속성은 지정되었으며 비어 있지 않은 경우 유효한 날짜 문자열이어야 합니다.

값 정화 알고리즘은 다음과 같습니다: 요소의 유효한 날짜 문자열이 아닌 경우, 대신 비어 있는 문자열로 설정합니다.

min 속성은 지정된 경우, 유효한 날짜 문자열을 가져야 합니다. max 속성은 지정된 경우, 유효한 날짜 문자열을 가져야 합니다.

step 속성은 일(day) 단위로 표현됩니다. 스텝 스케일 계수는 86,400,000 (이는 다른 알고리즘에서 사용되는 밀리초로 변환된 일수입니다). 기본 스텝은 1일입니다.

요소가 스텝 불일치를 겪는 경우, 사용자 에이전트는 요소의 을 요소가 스텝 불일치를 겪지 않는 가장 가까운 날짜로 반올림할 수 있습니다.

문자열을 숫자로 변환하는 알고리즘, 주어진 문자열 input은 다음과 같습니다: 날짜를 파싱하여 input에서 오류가 발생하면 오류를 반환하고, 그렇지 않으면 1970-01-01 자정 UTC부터 파싱된 날짜의 자정 UTC까지 경과한 밀리초 수를 반환합니다.

숫자를 문자열로 변환하는 알고리즘, 주어진 숫자 input은 다음과 같습니다: 1970-01-01 자정 UTC부터 input 밀리초 후의 날짜를 나타내는 유효한 날짜 문자열을 반환합니다.

문자열을 Date 객체로 변환하는 알고리즘, 주어진 문자열 input은 다음과 같습니다: 날짜를 파싱하여 input에서 오류가 발생하면 오류를 반환하고, 그렇지 않으면 파싱된 날짜의 자정 UTC를 나타내는 새로운 Date 객체를 반환합니다.

Date 객체를 문자열로 변환하는 알고리즘, 주어진 Date 객체 input은 다음과 같습니다: input에 의해 표현된 시간의 UTC에서 유효한 날짜 문자열을 반환합니다.

날짜 상태 (및 후속 섹션에서 설명되는 다른 날짜 및 시간 관련 상태)는 현대 달력에 대해 정확한 날짜와 시간 을 설정할 수 없는 값을 입력하기 위한 것이 아닙니다. 예를 들어, "빅뱅 후 1밀리초", "쥐라기 초기에 해당하는 시기", "기원전 250년경 겨울" 같은 시간을 입력하는 것은 부적절합니다.

그레고리력 도입 이전의 날짜 입력의 경우, 사용자 에이전트가 이전 기간의 날짜와 시간을 그레고리력으로 변환하는 것을 지원하지 않으며, 사용자가 수동으로 이를 수행해야 한다면 과도한 부담을 주기 때문에 날짜 상태(및 후속 섹션에서 설명되는 다른 날짜 및 시간 관련 상태)를 사용하지 않도록 권장합니다. (그레고리력이 도입된 방식은 국가마다 다르게 진행되었으며, 16세기 중반부터 20세기 초까지 다양한 시점에서 발생했습니다.) 대신, 저자는 select 요소와 input 요소를 사용하여 숫자 상태의 세밀한 입력 컨트롤을 제공하는 것이 권장됩니다.

다음의 공통 input 요소의 내용 속성, IDL 속성 및 메서드가 요소에 적용됩니다: autocomplete, list, max, min, readonly, required, 그리고 step 내용 속성; list, value, valueAsDate, 그리고 valueAsNumber IDL 속성; select(), stepDown(), 그리고 stepUp() 메서드.

value IDL 속성은 value 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음의 내용 속성은 지정해서는 안 되며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, size, src, 및 width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: checked, selectionStart, selectionEnd, 및 selectionDirection IDL 속성; setRangeText(), 및 setSelectionRange() 메서드.

4.10.5.1.8 상태 (type=month)

Element/input/month

모든 현재 엔진에서 지원됩니다.

Firefox지원 안 함Safari지원 안 함Chrome20+
Opera11+Edge79+Edge (Legacy)12+Internet Explorer지원 안 함
Firefox Android18+Safari iOSChrome Android?WebView Android?Samsung Internet?Opera Android?

input 요소의 type 속성이 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 다음을 설정하는 제어를 나타냅니다. 요소의 을 특정 을 나타내는 문자열로 설정합니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 을 변경할 수 있도록 해야 합니다. 이는 에서 을 파싱하여 얻은 것입니다. 사용자 에이전트는 사용자가 유효한 월 문자열이 아닌 비어 있지 않은 문자열로 설정하는 것을 허용해서는 안 됩니다. 사용자 에이전트가 을 선택하는 사용자 인터페이스를 제공하는 경우, 은 사용자의 선택을 나타내는 유효한 월 문자열로 설정되어야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정할 수 있도록 해야 합니다.

제약 조건 검증: 사용자 인터페이스가 사용자 에이전트가 유효한 월 문자열로 변환할 수 없는 입력을 설명할 때, 제어는 잘못된 입력을 겪고 있는 상태입니다.

날짜, 시간 및 숫자 폼 컨트롤의 입력 형식과 제출 형식의 차이에 대한 논의는 소개 섹션을 참조하고, 폼 컨트롤의 지역화에 관한 구현 노트를 참조하십시오.

속성이 지정되고 비어 있지 않은 경우, 그 값은 유효한 월 문자열이어야 합니다.

값 세정 알고리즘은 다음과 같습니다: 요소의 유효한 월 문자열이 아닌 경우, 대신 빈 문자열로 설정합니다.

최소값 속성이 지정된 경우, 그 값은 유효한 월 문자열이어야 합니다. 최대값 속성이 지정된 경우, 그 값은 유효한 월 문자열이어야 합니다.

단계 속성은 월로 표현됩니다. 단계 스케일 인자는 1입니다 (알고리즘이 월을 사용하므로 변환이 필요 없습니다). 기본 단계는 1개월입니다.

요소가 단계 불일치로 인한 문제를 겪고 있는 경우, 사용자 에이전트는 요소의 을 가장 가까운 로 반올림할 수 있습니다. 이 경우 요소는 단계 불일치를 겪지 않을 수 있습니다.

문자열을 숫자로 변환하는 알고리즘, 주어진 문자열 input,은 다음과 같습니다: input에서 파싱할 때 오류가 발생하면 오류를 반환하고, 그렇지 않으면 1970년 1월과 파싱된 사이의 월 수를 반환합니다.

숫자를 문자열로 변환하는 알고리즘, 주어진 숫자 input,은 다음과 같습니다: 1970년 1월과 input 개월 사이의 을 나타내는 유효한 월 문자열을 반환합니다.

문자열을 Date 객체로 변환하는 알고리즘, 주어진 문자열 input,은 다음과 같습니다: input에서 파싱할 때 오류가 발생하면 오류를 반환하고, 그렇지 않으면 새로운 Date 객체를 반환하여 파싱된 의 첫 날 아침 자정 UTC를 나타냅니다.

Date 객체를 문자열로 변환하는 알고리즘, 주어진 Date 객체 input,은 다음과 같습니다: 유효한 월 문자열을 반환하여 input이 나타내는 시간의 UTC 시간대에서 현재 을 나타냅니다.

다음의 공통 input 요소의 내용 속성, IDL 속성 및 메서드가 요소에 적용됩니다: autocomplete, list, max, min, readonly, required, 및 step 내용 속성; list, value, valueAsDate, 및 valueAsNumber IDL 속성; select(), stepDown(), 및 stepUp() 메서드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음의 내용 속성은 지정할 수 없으며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, size, src, 및 width.

다음의 IDL 속성 및 메서드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, 및 selectionDirection IDL 속성; setRangeText(), 및 setSelectionRange() 메서드.

4.10.5.1.9 상태 (type=week)

Element/input/week

Firefox없음Safari없음Chrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer없음
Firefox Android18+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

input 요소의 type 속성이 Week 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 특정 를 나타내는 문자열로 요소의 을 설정하는 컨트롤을 나타냅니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 를 변경할 수 있도록 허용해야 합니다. 이 주는 에서 주를 분석하여 얻은 것입니다. 사용자 에이전트는 사용자가 유효한 주 문자열이 아닌 비어 있지 않은 문자열로 설정하는 것을 허용해서는 안 됩니다. 사용자 에이전트가 를 선택할 수 있는 사용자 인터페이스를 제공하는 경우, 은 사용자의 선택을 나타내는 유효한 주 문자열로 설정되어야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정할 수 있도록 허용해야 합니다.

제약 조건 검증: 사용자 인터페이스가 사용자가 유효한 주 문자열로 변환할 수 없는 입력을 설명하는 경우, 제어는 잘못된 입력으로 인한 문제를 겪고 있습니다.

날짜, 시간 및 숫자 양식 제어의 입력 형식과 제출 형식의 차이에 대한 논의는 소개 섹션을 참조하고, 양식 제어의 현지화에 대한 구현 노트를 참조하십시오.

속성은 지정되어 있고 비어 있지 않은 경우, 유효한 주 문자열이어야 합니다.

값 세척 알고리즘은 다음과 같습니다: 요소의 유효한 주 문자열이 아닌 경우, 빈 문자열로 설정합니다.

최소 속성은 지정된 경우 유효한 주 문자열이어야 합니다. 최대 속성은 지정된 경우 유효한 주 문자열이어야 합니다.

단계 속성은 주 단위로 표현됩니다. 단계 스케일 계수는 604,800,000 (이는 주를 밀리초로 변환하며, 다른 알고리즘에서 사용됩니다)입니다. 기본 단계는 1주입니다. 기본 단계 기준는 −259,200,000 (1970-W01 주의 시작)입니다.

요소가 단계 불일치 문제를 겪는 경우, 사용자 에이전트는 요소의 을 가장 가까운 로 반올림할 수 있습니다. 이 주는 요소가 단계 불일치 문제를 겪지 않는 주입니다.

문자열을 숫자로 변환하는 알고리즘은 다음과 같습니다: 주 문자열을 분석하여 input에서 오류가 발생하면 오류를 반환하고, 그렇지 않으면 1970-01-01 자정 UTC (값 "1970-01-01T00:00:00.0Z"가 표시하는 시간)부터 파싱된 의 월요일 자정 UTC까지의 경과 밀리초 수를 반환합니다. 윤초는 무시됩니다.

숫자를 문자열로 변환하는 알고리즘는 주어진 숫자 input에 대해 다음과 같습니다: 유효한 주 문자열를 반환하여, UTC에서 input 밀리초가 1970-01-01 자정 UTC 이후의 시간 (값 "1970-01-01T00:00:00.0Z")을 나타내는 주를 표시합니다.

문자열을 Date 객체로 변환하는 알고리즘는 주어진 문자열 input에 대해 다음과 같습니다: 주를 분석하여 input에서 오류가 발생하면 오류를 반환하고, 그렇지 않으면 새로운 Date 객체를 반환하여 파싱된 의 월요일 자정 UTC를 나타냅니다.

Date 객체를 문자열로 변환하는 알고리즘는 주어진 Date 객체 input에 대해 다음과 같습니다: 유효한 주 문자열를 반환하여, input이 표시하는 시간의 UTC 시간대에서 현재의 를 나타냅니다.

다음의 공통 input 요소 콘텐츠 속성, IDL 속성 및 적용되는 메서드는 다음과 같습니다: autocomplete, list, max, min, readonly, required, 및 step 콘텐츠 속성; list, value, valueAsDate, 및 valueAsNumber IDL 속성; select(), stepDown(), 및 stepUp() 메서드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음의 콘텐츠 속성은 지정할 수 없으며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, size, src, 및 width.

다음의 IDL 속성과 메서드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, 및 selectionDirection IDL 속성; setRangeText(), 및 setSelectionRange() 메서드.

4.10.5.1.10 시간 상태 (type=time)

Element/input/time

모든 현재 엔진에서 지원합니다.

Firefox57+Safari14.1+Chrome20+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer지원하지 않음
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

입력 input 요소의 type 속성이 시간 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 다음의 제어를 나타냅니다 요소의 을 특정 시간을 나타내는 문자열로 설정합니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 시간을 변경할 수 있도록 해야 합니다. 이 에서 시간을 분석하여 얻은 값입니다. 사용자 에이전트는 사용자가 유효한 시간 문자열이 아닌 비어 있지 않은 문자열로 설정하는 것을 허용해서는 안 됩니다. 사용자 에이전트가 시간을 선택하는 사용자 인터페이스를 제공하는 경우, 은 사용자의 선택을 나타내는 유효한 시간 문자열로 설정되어야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정할 수 있도록 해야 합니다.

제약 조건 유효성 검사: 사용자 인터페이스가 사용자가 유효한 시간 문자열로 변환할 수 없는 입력을 설명할 때, 해당 제어는 잘못된 입력으로 인한 문제를 겪고 있습니다.

날짜, 시간 및 숫자 폼 컨트롤의 입력 형식과 제출 형식의 차이점, 그리고 폼 컨트롤의 지역화에 대한 논의는 소개 섹션을 참조하십시오.

속성은 지정되어 있고 비어 있지 않은 경우, 유효한 시간 문자열이어야 합니다.

값 정리 알고리즘은 다음과 같습니다: 요소의 유효한 시간 문자열이 아닌 경우, 빈 문자열로 설정합니다.

폼 컨트롤은 주기적인 도메인을 가집니다.

min 속성은 지정된 경우, 유효한 시간 문자열이어야 합니다. max 속성도 지정된 경우, 유효한 시간 문자열이어야 합니다.

step 속성은 초 단위로 표현됩니다. 스텝 스케일 계수는 1000 (이는 초를 밀리초로 변환하며, 다른 알고리즘에서 사용됨)입니다. 기본 스텝은 60초입니다.

요소가 스텝 불일치로 인한 문제를 겪는 경우, 사용자 에이전트는 요소의 을 가장 가까운 시간으로 반올림할 수 있습니다. 이 시간은 요소가 스텝 불일치로 인한 문제를 겪지 않는 시간입니다.

문자열을 숫자로 변환하는 알고리즘, 주어진 문자열 input은 다음과 같습니다: 시간을 분석하여 input에서 시간 변환을 시도하고, 에러가 발생하면 에러를 반환합니다. 그렇지 않으면, 시간의 자정부터 경과된 밀리초 수를 반환합니다.

숫자를 문자열로 변환하는 알고리즘, 주어진 숫자 input은 다음과 같습니다: 자정 이후 input 밀리초를 나타내는 유효한 시간 문자열을 반환합니다.

문자열을 Date 객체로 변환하는 알고리즘, 주어진 문자열 input은 다음과 같습니다: 시간을 분석하여 input에서 시간 변환을 시도하고, 에러가 발생하면 에러를 반환합니다. 그렇지 않으면, 새로운 Date 객체를 반환하여 1970-01-01 UTC에서 파싱된 시간을 나타냅니다.

Date 객체를 문자열로 변환하는 알고리즘, 주어진 Date 객체 input은 다음과 같습니다: 유효한 시간 문자열을 반환하여 input이 나타내는 UTC 시간 구성 요소를 나타냅니다.

다음은 일반적인 입력 요소의 콘텐츠 속성, IDL 속성 및 적용되는 메소드: autocomplete, list, max, min, readonly, required, 및 step 콘텐츠 속성; list, value, valueAsDate, 및 valueAsNumber IDL 속성; select(), stepDown(), 및 stepUp() 메소드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음 콘텐츠 속성은 지정되지 않아야 하며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, size, src, 및 width.

다음 IDL 속성 및 메소드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, 및 selectionDirection IDL 속성; setRangeText(), 및 setSelectionRange() 메소드.

4.10.5.1.11 로컬 날짜 및 시간 상태 (type=datetime-local)

Element/input/datetime-local

모든 현재 엔진에서 지원됩니다.

Firefox93+Safari14.1+Chrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer지원 안 함
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

입력 input 요소의 type 속성이 로컬 날짜 및 시간 상태일 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 제시합니다 사용자가 요소의 로컬 날짜 및 시간을 나타내는 문자열로 설정할 수 있는 컨트롤을 나타냅니다. 시간대 오프셋 정보는 포함되지 않습니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 날짜 및 시간 을 통해 변경할 수 있도록 해야 합니다. 이 값은 날짜 및 시간 을 분석하여 얻은 값입니다. 사용자 에이전트는 사용자가 을 유효하지 않은 유효한 표준화된 로컬 날짜 및 시간 문자열 로 설정하는 것을 허용해서는 안 됩니다. 사용자 에이전트가 로컬 날짜 및 시간 을 선택할 수 있는 사용자 인터페이스를 제공하는 경우, 은 사용자의 선택을 나타내는 유효한 표준화된 로컬 날짜 및 시간 문자열로 설정해야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정하는 것을 허용해야 합니다.

제약 조건 검증: 사용자 인터페이스가 사용자 에이전트가 유효한 표준화된 로컬 날짜 및 시간 문자열로 변환할 수 없는 입력을 설명하는 경우, 해당 컨트롤은 잘못된 입력으로 인해 문제가 발생하고 있습니다.

날짜, 시간 및 숫자 양식 컨트롤의 입력 형식과 제출 형식의 차이에 대한 논의는 소개 섹션을 참조하십시오. 또한, 구현 노트를 참조하여 양식 컨트롤의 지역화에 대해 확인하십시오.

value 속성이 지정되어 있고 비어 있지 않다면, 유효한 로컬 날짜 및 시간 문자열 값을 가져야 합니다.

값 정화 알고리즘은 다음과 같습니다: 요소의 유효한 로컬 날짜 및 시간 문자열 이면, 이를 같은 날짜와 시간을 나타내는 유효한 표준화된 로컬 날짜 및 시간 문자열 로 설정합니다. 그렇지 않으면 빈 문자열로 설정합니다.

min 속성이 지정된 경우, 유효한 로컬 날짜 및 시간 문자열 값을 가져야 합니다. max 속성이 지정된 경우, 유효한 로컬 날짜 및 시간 문자열 값을 가져야 합니다.

step 속성은 초 단위로 표현됩니다. 스텝 스케일 계수 는 1000 (초를 밀리초로 변환, 다른 알고리즘에서 사용됨)입니다. 기본 스텝은 60초입니다.

요소가 스텝 불일치로 인한 문제를 겪는 경우, 사용자 에이전트는 요소의 로컬 날짜 및 시간 중 가장 가까운 값으로 반올림할 수 있습니다. 이 값은 스텝 불일치 문제를 겪지 않는 값입니다.

문자열을 숫자로 변환하는 알고리즘, 주어진 문자열 input은 다음과 같습니다: 날짜 및 시간 분석input에서 오류를 발생시키면, 오류를 반환합니다. 그렇지 않으면 1970-01-01 자정 이후 경과된 밀리초 수를 반환합니다. (값 "1970-01-01T00:00:00.0"으로 표현된 시간) 분석된 로컬 날짜 및 시간을 나타내며, 윤초는 무시합니다.

숫자를 문자열로 변환하는 알고리즘, 주어진 숫자 input은 다음과 같습니다: 1970-01-01 자정 이후 input 밀리초 후의 날짜와 시간을 나타내는 유효한 표준화된 로컬 날짜 및 시간 문자열을 반환합니다.

역사적 날짜에 대한 주의 사항날짜 상태 섹션에서 확인하십시오.

다음의 공통 input 요소 내용 속성, IDL 속성 및 메서드는 적용됩니다: autocomplete, list, max, min, readonly, required, 그리고 step 내용 속성; list, value, 및 valueAsNumber IDL 속성; select(), stepDown(), 및 stepUp() 메서드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음의 내용 속성은 지정할 수 없으며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, size, src, 및 width.

다음의 IDL 속성과 메서드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, selectionDirection, 및 valueAsDate IDL 속성; setRangeText(), 및 setSelectionRange() 메서드.

다음 예제는 비행기 예약 애플리케이션의 일부를 보여줍니다. 이 애플리케이션은 input 요소를 사용하며, type 속성은 datetime-local로 설정되어 있습니다. 그런 다음 선택된 공항의 시간대에서 주어진 날짜와 시간을 해석합니다.

<fieldset>
 <legend>목적지</legend>
 <p><label>공항: <input type=text name=to list=airports></label></p>
 <p><label>출발 시간: <input type=datetime-local name=totime step=3600></label></p>
</fieldset>
<datalist id=airports>
 <option value=ATL label="Atlanta">
 <option value=MEM label="Memphis">
 <option value=LHR label="London Heathrow">
 <option value=LAX label="Los Angeles">
 <option value=FRA label="Frankfurt">
</datalist>
4.10.5.1.12 숫자 상태 (type=number)

Element/input/number

모든 현재 엔진에서 지원됩니다.

Firefox29+Safari5.1+Chrome7+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

input 요소의 type 속성이 숫자 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 제어 요소의 을 숫자를 나타내는 문자열로 설정합니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 을 변경할 수 있도록 허용해야 하며, 이를 부동 소수점 숫자 값 파싱 규칙에 적용하여 얻은 값으로 설정해야 합니다. 사용자 에이전트는 사용자가 유효한 부동 소수점 숫자가 아닌 비어 있지 않은 문자열로 설정하는 것을 허용하지 말아야 합니다. 사용자 에이전트가 숫자를 선택할 수 있는 사용자 인터페이스를 제공하는 경우, 사용자의 선택을 부동 소수점 숫자로 가장 잘 표현한 값으로 설정되어야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정할 수 있도록 해야 합니다.

제약 검증: 사용자 인터페이스가 사용자 에이전트가 유효한 부동 소수점 숫자로 변환할 수 없는 입력을 설명하는 경우, 제어 요소는 잘못된 입력으로 고통받고 있음으로 간주됩니다.

이 사양은 사용자 에이전트가 사용할 사용자 인터페이스를 정의하지 않습니다; 사용자 에이전트 공급자는 사용자 요구를 가장 잘 충족하는 것을 고려해야 합니다. 예를 들어, 페르시아어나 아랍어 시장을 위한 사용자 에이전트는 페르시아어 및 아랍어 숫자 입력을 지원할 수 있으며(위에서 설명한 제출 형식으로 변환됨). 로마인을 위한 사용자 에이전트는 값을 십진수가 아닌 로마 숫자로 표시할 수 있으며, 또는(더 현실적으로) 프랑스 시장을 위한 사용자 에이전트는 값을 천 단위에 아포스트로피를 넣고 소수점 앞에 쉼표를 표시하며 사용자가 이러한 방식으로 값을 입력할 수 있도록 허용할 수 있습니다. 이렇게 입력된 값은 위에서 설명한 제출 형식으로 내부 변환됩니다.

속성은 지정되어 있고 비어 있지 않은 경우, 유효한 부동 소수점 숫자여야 합니다.

값 정리 알고리즘은 다음과 같습니다: 요소의 유효한 부동 소수점 숫자가 아닌 경우, 빈 문자열로 설정합니다.

최소값 속성은 지정된 경우, 유효한 부동 소수점 숫자여야 합니다. 최대값 속성은 지정된 경우, 유효한 부동 소수점 숫자여야 합니다.

단계 스케일 계수는 1입니다. 기본 단계는 1(사용자가 정수만 선택할 수 있도록 허용하며, 단계 기반가 비정수인 경우 제외)

요소가 단계 불일치로 고통받고 있는 경우, 사용자 에이전트는 요소의 을 가장 가까운 숫자로 반올림할 수 있습니다. 요소가 단계 불일치로 고통받고 있는 경우가 아닌 숫자에 가장 가까운 숫자를 선택하는 것이 좋습니다. 두 숫자가 있는 경우, 사용자 에이전트는 양의 무한대에 가장 가까운 숫자를 선택하는 것이 좋습니다.

문자열을 숫자로 변환하는 알고리즘는 다음과 같습니다: 문자열 input부동 소수점 숫자 값 파싱 규칙을 적용하여 오류가 발생하면 오류를 반환하고, 그렇지 않으면 결과 숫자를 반환합니다.

숫자를 문자열로 변환하는 알고리즘는 다음과 같습니다: input을 나타내는 유효한 부동 소수점 숫자를 반환합니다.

다음의 일반적인 input 요소 콘텐츠 속성, IDL 속성 및 메서드 적용 요소에: autocomplete, list, max, min, placeholder, readonly, required, 그리고 step 콘텐츠 속성; list, value, 및 valueAsNumber IDL 속성; select(), stepDown(), 및 stepUp() 메서드.

value IDL 속성은 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음 콘텐츠 속성은 지정되어서는 안 되며 적용되지 않습니다 요소에: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, popovertarget, popovertargetaction, size, src, 및 width.

다음 IDL 속성 및 메서드는 적용되지 않습니다 요소에: checked, files, selectionStart, selectionEnd, selectionDirection, 및 valueAsDate IDL 속성; setRangeText(), 및 setSelectionRange() 메서드.

다음은 숫자 입력 컨트롤을 사용하는 예제입니다:

<label>얼마를 청구하시겠습니까? $<input type=number min=0 step=0.01 name=price></label>

위에서 설명한 바와 같이, 사용자 에이전트는 사용자의 지역 형식에 맞게 숫자 입력을 지원할 수 있으며, 이를 제출에 필요한 형식으로 변환할 수 있습니다. 여기에는 그룹 구분 기호("872,000,000,000")와 다양한 소수 구분 기호("3,99" vs "3.99")를 처리하거나 아라비아 숫자, 데바나가리 숫자, 페르시아 숫자 및 태국 숫자와 같은 지역 숫자를 사용하는 것이 포함될 수 있습니다.

type=number 상태는 숫자로만 이루어져 있지만 엄밀히 말해 숫자가 아닌 입력에는 적합하지 않습니다. 예를 들어, 신용 카드 번호나 미국 우편 번호에는 부적합합니다. type=number를 사용할지 여부를 결정하는 간단한 방법은 입력 컨트롤이 스핀박스 인터페이스(예: "위" 및 "아래" 화살표)가 있는 것이 적절한지 고려하는 것입니다. 마지막 숫자에서 1이 잘못된 신용 카드 번호는 사소한 실수가 아니라 모든 숫자가 잘못된 것만큼이나 잘못된 것입니다. 따라서 사용자가 신용 카드 번호를 "위" 및 "아래" 버튼을 사용하여 선택하는 것은 의미가 없습니다. 스핀박스 인터페이스가 적합하지 않은 경우, type=text가 적절한 선택일 수 있습니다 (가능한 경우 inputmode 또는 pattern 속성).

4.10.5.1.13 범위 상태 (type=range)

Element/input/range

모든 현재 엔진에서 지원됩니다.

Firefox23+Safari3.1+Chrome4+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android52+Safari iOS5+Chrome Android57+WebView Android4.4+Samsung Internet?Opera Android11+

input 요소의 type 속성이 범위 상태일 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 제어로써 요소의 을 문자열로 설정하며, 숫자를 나타내지만, 정확한 값은 중요하지 않으며, 사용자 에이전트는 숫자 상태보다 간단한 인터페이스를 제공할 수 있습니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 을 변경할 수 있도록 해야 하며, 이는 부동 소수점 숫자 값의 파싱 규칙을 적용하여 얻은 것입니다. 사용자 에이전트는 사용자가 유효한 부동 소수점 숫자가 아닌 문자열로 설정하도록 허용해서는 안 됩니다. 사용자 에이전트가 숫자를 선택하는 사용자 인터페이스를 제공하는 경우, 은 사용자의 선택을 나타내는 부동 소수점 숫자로서의 최상의 표현으로 설정되어야 합니다. 사용자 에이전트는 사용자가 을 빈 문자열로 설정하는 것을 허용해서는 안 됩니다.

제약 조건 검증: 사용자 인터페이스가 사용자 에이전트가 유효한 부동 소수점 숫자로 변환할 수 없는 입력을 설명하는 경우, 제어는 잘못된 입력에 시달리고 있습니다.

속성이 지정된 경우, 그 값은 유효한 부동 소수점 숫자여야 합니다.

값 정제 알고리즘은 다음과 같습니다: 요소의 유효한 부동 소수점 숫자가 아닌 경우, 요소의 값을 최상의 표현, 부동 소수점 숫자로서으로 설정합니다. 이는 기본값입니다.

기본값최소값최소값최대값의 차이의 절반을 더한 값입니다. 단, 최대값최소값보다 작으면 기본값최소값입니다.

요소가 언더플로우에 시달리고 있을 때, 사용자 에이전트는 요소의 최상의 표현, 부동 소수점 숫자로서으로 설정해야 합니다. 이는 최소값입니다.

요소가 오버플로우에 시달리고 있을 때, 최대값최소값보다 작지 않으면, 사용자 에이전트는 요소의 유효한 부동 소수점 숫자로 설정하여 최대값을 나타냅니다.

요소가 단계 불일치를 겪고 있을 때, 사용자 에이전트는 요소의 을 다음의 두 조건을 만족하는 가장 가까운 숫자로 반올림해야 합니다: 1) 요소가 단계 불일치를 겪지 않고, 2) 최소값보다 크거나 같으며, 최대값최소값보다 작지 않다면 최대값보다 작거나 같은 숫자여야 합니다. 두 숫자가 이러한 제약 조건을 모두 만족하는 경우, 사용자 에이전트는 양의 무한대에 가장 가까운 숫자를 사용해야 합니다.

예를 들어, 다음과 같은 마크업 <input type="range" min=0 max=100 step=20 value=50> 결과로 초기 값이 60인 범위 제어가 생성됩니다.

다음은 list 속성을 사용하는 자동 완성 목록의 범위 제어 예입니다. 이 제어는 전체 범위의 값 중 특히 중요한 값이 있는 경우 유용할 수 있습니다. 예를 들어, 미리 설정된 조명 수준이나 속도 제어로 사용되는 범위 제어의 전형적인 제한 속도 등이 있을 수 있습니다. 다음 마크업 조각:

<input type="range" min="-100" max="100" value="0" step="10" name="power" list="powers">
<datalist id="powers">
<option value="0">
<option value="-30">
<option value="30">
 <option value="++50">
</datalist>

...다음 스타일 시트가 적용된 경우:

input { writing-mode: vertical-lr; height: 75px; width: 49px; background: #D5CCBB; color: black; }

...다음과 같이 렌더링될 수 있습니다:

세로 슬라이더 제어로, 주요 색상이 검정색이고 배경 색상이 베이지색입니다. 슬라이더에는 5개의 눈금이 있으며, 양쪽 끝에는 긴 눈금이 있고, 중간에 가까운 세 개의 짧은 눈금이 있습니다.

사용자 에이전트가 스타일 시트에서 지정된 높이와 너비 속성의 비율을 통해 제어의 방향을 결정한 방식에 유의하십시오. 색상도 스타일 시트에서 유래되었습니다. 그러나 눈금은 마크업에서 유래되었습니다. 특히, step 속성이 눈금의 배치에 영향을 미치지 않았으며, 사용자 에이전트는 작성자가 지정한 완료 값만 사용하고 극단적인 값에 긴 눈금을 추가하기로 결정했습니다.

또한, 잘못된 값 ++50이 무시된 것을 주목하십시오.

다른 예제로, 다음 마크업 조각을 고려해보십시오:

<input name=x type=range min=100 max=700 step=9.09090909 value=509.090909>

사용자 에이전트는 다양한 방식으로 표시할 수 있습니다. 예를 들어:

다이얼로 표시된 예

또는, 다른 예로:

눈금이 있는 긴 수평 슬라이더로 표시된 예

사용자 에이전트는 스타일 시트에서 제공된 치수를 기반으로 어떤 것을 표시할지 선택할 수 있습니다. 이렇게 하면 너비가 달라도 눈금의 해상도를 동일하게 유지할 수 있습니다.

마지막으로, 두 개의 레이블이 있는 범위 제어의 예를 소개합니다:

<input type="range" name="a" list="a-values">
<datalist id="a-values">
<option value="10" label="Low">
<option value="90" label="High">
</datalist>

제어가 수직으로 그려지도록 하는 스타일을 적용하면, 다음과 같이 보일 수 있습니다:

상단에 'High'라는 레이블이 붙은 눈금과 하단에 'Low'라는 레이블이 붙은 눈금이 있는 수직 슬라이더 제어.

이 상태에서는 범위 및 단계 제약이 사용자 입력 중에도 적용되며, 값이 빈 문자열로 설정될 수 없습니다.

min 속성은 지정된 경우, 유효한 부동 소수점 숫자 값을 가져야 합니다. 기본 최소값은 0입니다. max 속성은 지정된 경우, 유효한 부동 소수점 숫자 값을 가져야 합니다. 기본 최대값은 100입니다.

단계 스케일 팩터는 1입니다. 기본 단계는 1입니다 (정수만 허용됩니다. 단, min 속성이 정수가 아닌 값을 가지는 경우를 제외합니다).

문자열을 숫자로 변환하는 알고리즘, 주어진 문자열 input,은 다음과 같습니다: 부동 소수점 숫자 값 구문 분석 규칙input에 적용하여 오류가 발생하면 오류를 반환하고, 그렇지 않으면 결과 숫자를 반환합니다.

숫자를 문자열로 변환하는 알고리즘, 주어진 숫자 input,은 다음과 같습니다: input부동 소수점 숫자로서의 최적 표현을 반환합니다.

다음은 공통 input 요소의 내용 속성, IDL 속성 및 메서드 적용됩니다: autocomplete, list, max, min, 및 step 내용 속성; list, value, 및 valueAsNumber IDL 속성; stepDown()stepUp() 메서드.

value IDL 속성은 value 모드입니다.

다음 inputchange 이벤트가 적용됩니다.

다음 내용 속성은 지정해서는 안 되며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, readonly, required, size, src, 및 width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, selectionDirection, 및 valueAsDate IDL 속성; select(), setRangeText(), 및 setSelectionRange() 메서드.

4.10.5.1.14 색상 상태 (type=color)

Element/input/color

모든 현재 엔진에서 지원됩니다.

Firefox29+Safari12.1+Chrome20+
Opera12+Edge79+
Edge (Legacy)14+Internet Explorer지원 안 함
Firefox Android🔰 27+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

입력 요소의 input 요소의 type 속성이 색상 상태(Color) 일 때, 이 섹션의 규칙이 적용됩니다.

입력 요소는 색상 팔레트 컨트롤을 나타내며, 요소의 value를 문자열로 설정하여 간단한 색상을 나타냅니다.

이 상태에서는 항상 색상이 선택되어 있으며, 값을 빈 문자열로 설정할 수 없습니다.

요소가 mutable인 경우, 사용자 에이전트는 사용자에게 색상을 변경할 수 있도록 허용해야 합니다. 색상은 value 속성을 통해 간단한 색상 값 구문 분석 규칙 을 적용하여 얻은 값이어야 합니다. 사용자 에이전트는 사용자가 value유효한 소문자 간단한 색상으로 설정할 수 있도록 해야 하며, 색상 선택기 사용자 인터페이스를 제공하는 경우, value는 사용자의 선택에 대한 간단한 색상 값 직렬화 규칙 을 적용한 결과로 설정되어야 합니다. 사용자 에이전트는 사용자가 value를 빈 문자열로 설정할 수 없도록 해야 합니다.

이러한 요소의 입력 활성화 동작가능한 경우 선택기 표시입니다.

제약 조건 검증: 사용자 인터페이스가 사용자가 유효한 소문자 간단한 색상으로 변환할 수 없는 입력을 설명할 때, 컨트롤은 잘못된 입력을 겪고 있음으로 간주됩니다.

속성 value는 지정되어 있고 비어 있지 않다면, 유효한 간단한 색상이어야 합니다.

값 정리 알고리즘은 다음과 같습니다: 요소의 value유효한 간단한 색상인 경우, 그것을 ASCII 소문자로 변환된 값으로 설정합니다. 그렇지 않으면, "#000000" 문자열로 설정합니다.

다음은 일반적인 input 요소의 콘텐츠 속성 및 IDL 속성으로, 요소에 적용됩니다: autocompletelist 콘텐츠 속성; listvalue IDL 속성; select() 메서드.

value IDL 속성은 value 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음 콘텐츠 속성은 지정되어서는 안 되며 적용되지 않습니다: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, maxlength, min, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, readonly, required, size, src, step, 및 width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: checked, files, selectionStart, selectionEnd, selectionDirection, valueAsDate 및, valueAsNumber IDL 속성; setRangeText(), setSelectionRange(), stepDown(), 및 stepUp() 메서드.

4.10.5.1.15 체크박스 상태 (type=checkbox)

Element/input/checkbox

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

input 요소의 type 속성이 체크박스 상태일 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 대표하는 두 가지 상태의 컨트롤로 요소의 체크됨 상태를 나타냅니다. 요소의 체크됨 상태가 true이면, 컨트롤은 긍정적인 선택을 나타내며, false이면 부정적인 선택을 나타냅니다. 요소의 indeterminate IDL 속성이 true로 설정되면, 컨트롤의 선택은 세 번째의 불확정 상태에 있는 것처럼 모호해야 합니다.

컨트롤은 요소의 indeterminate IDL 속성이 true로 설정되더라도 진정한 삼 상태 컨트롤이 아닙니다. indeterminate IDL 속성은 단지 세 번째 상태의 모양만 제공합니다.

입력 활성화 동작은 다음 단계들을 실행합니다:

  1. 요소가 연결되지 않은 경우, 반환합니다.

  2. 이벤트 발생 input 이름으로 요소에서 발생시키고, 버블구성됨 속성을 true로 초기화합니다.

  3. 이벤트 발생 change 이름으로 요소에서 발생시키고, 버블 속성을 true로 초기화합니다.

제약 조건 검증: 요소가 필수 이고, 체크됨 상태가 false이면, 요소는 누락된 상태입니다.

input.indeterminate [ = value ]

설정 시, 체크박스 컨트롤의 렌더링을 무시하여 현재 값이 보이지 않도록 합니다.

다음 공통 input 요소의 콘텐츠 속성과 IDL 속성 적용됩니다: checked, 그리고 required 콘텐츠 속성; checkedvalue IDL 속성.

value IDL 속성은 기본/켜짐 모드입니다.

inputchange 이벤트가 적용됩니다.

다음 콘텐츠 속성은 지정되어서는 안 되며 적용되지 않습니다: accept, alt, autocomplete, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, readonly, size, src, step, 그리고 width.

다음 IDL 속성과 메서드는 적용되지 않습니다: files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 그리고 valueAsNumber IDL 속성; select(), setRangeText(), setSelectionRange(), stepDown(), 그리고 stepUp() 메서드.

4.10.5.1.16 라디오 버튼 상태 (type=radio)

요소/input/radio

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 input 요소의 type 속성이 라디오 버튼 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

다음 input 요소는 대표하는 컨트롤로, 다른 input 요소와 함께 사용될 때, 오직 하나의 컨트롤만이 체크됨 상태를 true로 설정할 수 있는 라디오 버튼 그룹을 형성합니다. 요소의 체크됨 상태가 true일 경우, 이 컨트롤은 그룹 내에서 선택된 컨트롤을 나타내며, false일 경우, 선택되지 않은 그룹 내의 컨트롤을 나타냅니다.

다음 라디오 버튼 그룹에는 input 요소 a와 함께 모든 다른 input 요소 b가 포함됩니다. 이들 요소는 다음 모든 조건을 충족해야 합니다:

트리에는 input 요소가 포함되어서는 안 되며, 그 라디오 버튼 그룹이 오직 해당 요소만 포함되어야 합니다.

다음 현상 중 어느 것이 발생할 때, 요소의 체크됨 상태가 true로 설정되면, 동일한 라디오 버튼 그룹에 있는 모든 다른 요소의 체크됨 상태는 false로 설정되어야 합니다:

입력 활성화 동작는 다음 단계를 수행합니다:

  1. 요소가 연결되지 않은 경우, 반환합니다.

  2. 이벤트를 발생시킵니다 input라는 이름으로 요소에서, 버블구성됨 속성을 true로 초기화합니다.

  3. 이벤트를 발생시킵니다 change라는 이름으로 요소에서, 버블 속성을 true로 초기화합니다.

제약 검증: 라디오 버튼 그룹에 있는 요소가 필수일 경우, 그리고 input 요소들이 모두 라디오 버튼 그룹에서 체크됨이 false인 경우, 요소는 부재로 인한 문제가 있습니다.

다음 예제는 어떤 이유로 인해, puppers가 필수비활성화됨으로 지정된 경우입니다:

<form>
 <p><label><input type="radio" name="dog-type" value="pupper" required disabled> Pupper</label>
 <p><label><input type="radio" name="dog-type" value="doggo"> Doggo</label>
 <p><button>Make your choice</button>
</form>

사용자가 "Doggo"를 선택하지 않고 이 양식을 제출하려고 하면, 두 개 모두 input 요소는 부재로 인한 문제를 겪게 됩니다, 왜냐하면 라디오 버튼 그룹의 요소가 필수이기 때문입니다 (즉, 첫 번째 요소), 그리고 라디오 버튼 그룹의 모든 요소가 false인 체크됨을 가지고 있기 때문입니다.

반면, 사용자가 "Doggo"를 선택하고 양식을 제출하면, input 요소는 부재로 인한 문제를 겪지 않게 됩니다, 왜냐하면 그 중 하나는 필수이지만, 모든 요소가 false인 체크됨을 가지고 있지 않기 때문입니다.

라디오 버튼 그룹의 어떤 버튼도 체크되지 않으면, 사용자나 스크립트에 의해 체크되기 전까지는 모두 초기 상태에서 체크되지 않은 상태로 유지됩니다.

다음과 같은 일반 input 요소 콘텐츠 속성과 IDL 속성은 적용됩니다: checkedrequired 콘텐츠 속성; checkedvalue IDL 속성.

value IDL 속성은 기본/켜짐 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음 콘텐츠 속성은 지정되어서는 안 되며 적용되지 않습니다: accept, alt, autocomplete, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, popovertarget, popovertargetaction, readonly, size, src, step, 및 width.

다음 IDL 속성 및 메서드는 적용되지 않습니다: files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 및 valueAsNumber IDL 속성; select(), setRangeText(), setSelectionRange(), stepDown(), 및 stepUp() 메서드.

4.10.5.1.17 파일 업로드 상태 (type=file)

Element/input/file

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

input 요소의 type 속성이 파일 업로드 상태에 있을 때, 이 섹션의 규칙이 적용됩니다.

input 요소는 선택된 파일들의 목록을 나타냅니다. 각 파일은 파일 이름, 파일 유형, 파일 본문(파일 내용)으로 구성됩니다.

파일 이름은 경로 구성 요소를 포함해서는 안 됩니다, 사용자가 전체 디렉토리 계층 또는 서로 다른 디렉토리에서 동일한 이름을 가진 여러 파일을 선택한 경우에도 마찬가지입니다. 경로 구성 요소파일 업로드 상태의 목적으로, 파일 이름의 U+005C 역슬래시 문자 (\)로 구분된 부분들입니다.

multiple 속성이 설정되지 않은 경우, 선택된 파일들 목록에 파일이 하나만 있어야 합니다.

이러한 요소의 입력 활성화 동작파일 선택기를 표시하다, 해당되는 경우 입니다.

요소가 변경 가능한 경우, 사용자 에이전트는 사용자가 드래그 앤 드롭으로 파일을 추가하거나 제거하는 등의 방법으로 파일 목록을 변경할 수 있도록 해야 합니다. 사용자가 이렇게 할 때, 사용자 에이전트는 파일 선택을 업데이트 해야 합니다.

요소가 변경 가능하지 않은 경우, 사용자 에이전트는 사용자가 요소의 선택을 변경할 수 없도록 해야 합니다.

요소 element파일 선택 업데이트 방법:

  1. 요소 작업 대기열에 추가사용자 상호작용 작업 소스 에 대해 element 및 다음 단계:

    1. element선택된 파일들를 업데이트하여 사용자의 선택을 나타내도록 합니다.

    2. 이벤트 발생 이름이 inputinput 요소에서 발생시키며, 버블링합성됨 속성을 true로 초기화합니다.

    3. 이벤트 발생 이름이 changeinput 요소에서 발생시키며, 버블링 속성을 true로 초기화합니다.

제약 검증: 요소가 필수 이고 선택된 파일들 목록이 비어 있으면, 요소는 누락으로 인한 문제를 겪고 있습니다.


Attributes/accept

현재 모든 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Element/input#attr-accept

현재 모든 엔진에서 지원됩니다.

Firefox37+Safari11.1+Chrome26+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android37+Safari iOS11.3+Chrome Android26+WebView Android4.4+Samsung Internet1.5+Opera Android15+

accept 속성은 사용자 에이전트에 수락할 파일 유형에 대한 힌트를 제공하는 데 사용할 수 있습니다.

지정된 경우, 속성은 쉼표로 구분된 토큰 집합으로 구성되어야 하며, 각 토큰은 다음 항목 중 하나에 대한 ASCII 대소문자 구분 없는 일치 항목이어야 합니다.

문자열 "audio/*"
사운드 파일이 수락된다는 것을 나타냅니다.
문자열 "video/*"
비디오 파일이 수락된다는 것을 나타냅니다.
문자열 "image/*"
이미지 파일이 수락된다는 것을 나타냅니다.
유효한 MIME 유형 문자열(매개변수 없음)
지정된 유형의 파일이 수락된다는 것을 나타냅니다.
첫 문자가 U+002E FULL STOP 문자 (.)인 문자열
지정된 파일 확장자를 가진 파일이 수락된다는 것을 나타냅니다.

토큰은 다른 토큰의 ASCII 대소문자 구분 없는 일치 항목이 되어서는 안 되며 (즉, 중복이 허용되지 않습니다). 속성에서 토큰 목록을 얻으려면 사용자 에이전트는 속성 값을 쉼표로 분리해야 합니다.

사용자 에이전트는 이 속성의 값을 사용하여 일반 파일 선택기보다 더 적절한 사용자 인터페이스를 표시할 수 있습니다. 예를 들어, 값이 image/*인 경우, 사용자 에이전트는 사용자가 로컬 카메라를 사용하거나 사진 컬렉션에서 사진을 선택할 수 있는 옵션을 제공할 수 있습니다; 값이 audio/*인 경우, 사용자 에이전트는 사용자가 헤드셋 마이크를 사용하여 클립을 녹음할 수 있는 옵션을 제공할 수 있습니다.

사용자 에이전트는 이러한 토큰 중 하나(또는 여러 개)에 의해 허용되지 않는 파일을 사용자가 선택하는 것을 방지해야 합니다.

작성자는 특정 형식의 데이터를 찾을 때 MIME 유형과 해당 확장자를 모두 지정할 것을 권장합니다.

예를 들어, Microsoft Word 문서를 Open Document Format 파일로 변환하는 애플리케이션을 고려해 보십시오. Microsoft Word 문서는 다양한 MIME 유형과 확장자로 설명되므로, 사이트는 여러 개를 나열할 수 있습니다:

<input type="file" accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

파일 유형을 설명하는 데 파일 확장자만 사용하는 플랫폼에서는 여기 나열된 확장자를 사용하여 허용된 문서를 필터링할 수 있으며, MIME 유형은 시스템의 유형 등록 테이블(시스템에서 사용하는 MIME 유형을 확장자에 매핑)과 함께 사용하여 허용할 다른 확장자를 결정할 수 있습니다. 유사하게, 파일 이름이나 확장자가 없고 문서를 내부적으로 MIME 유형으로 레이블을 지정하는 시스템에서는 MIME 유형을 사용하여 허용된 파일을 선택할 수 있으며, 시스템이 알려진 확장자를 MIME 유형에 매핑하는 확장자 등록 테이블을 가진 경우 확장자를 사용할 수 있습니다.

확장자는 모호할 수 있습니다 (예: ".dat" 확장자를 사용하는 형식이 무수히 많으며, 사용자는 일반적으로 Microsoft Word 문서가 아니더라도 파일 이름을 ".doc" 확장자로 쉽게 변경할 수 있습니다), MIME 유형은 신뢰할 수 없을 수 있습니다 (예: 많은 형식이 공식적으로 등록된 유형이 없으며, 많은 형식이 실제로는 여러 MIME 유형으로 레이블이 붙습니다). 작성자는 일반적으로 클라이언트로부터 받은 데이터는 예상된 형식이 아닐 수 있으므로 주의해서 처리해야 한다는 점을 상기해야 합니다. 이는 사용자가 적대적이지 않고 사용자 에이전트가 accept 속성의 요구 사항을 완전히 준수했더라도 마찬가지입니다.

Element/input/file

역사적인 이유로, value IDL 속성은 파일 이름 앞에 문자열 "C:\fakepath\"를 붙입니다. 일부 레거시 사용자 에이전트는 실제 전체 경로를 포함하기도 했습니다 (이는 보안 취약점이었습니다). 이로 인해 value IDL 속성에서 파일 이름을 하위 호환 방식으로 얻는 것은 간단하지 않습니다. 다음 함수는 적절히 호환 가능한 방식으로 파일 이름을 추출합니다:

function extractFilename(path) {
  if (path.substr(0, 12) == "C:\\fakepath\\")
    return path.substr(12); // 최신 브라우저
  var x;
  x = path.lastIndexOf('/');
  if (x >= 0) // 유닉스 기반 경로
    return path.substr(x+1);
  x = path.lastIndexOf('\\');
  if (x >= 0) // 윈도우 기반 경로
    return path.substr(x+1);
  return path; // 파일 이름만
}

다음과 같이 사용할 수 있습니다:

<p><input type=file name=image onchange="updateFilename(this.value)"></p>
<p>선택한 파일의 이름은: <span id="filename">(없음)</span></p>
<script>
 function updateFilename(path) {
   var name = extractFilename(path);
   document.getElementById('filename').textContent = name;
 }
</script>

다음과 같은 일반적인 input 요소의 내용 속성과 IDL 속성은 적용됩니다: accept, multiple, 그리고 required 내용 속성; files 그리고 value IDL 속성; select() 메서드.

value IDL 속성은 filename 모드에 있습니다.

inputchange 이벤트는 적용됩니다.

다음과 같은 내용 속성은 지정할 수 없으며 적용되지 않습니다: alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, pattern, popovertarget, popovertargetaction, placeholder, readonly, size, src, step, 그리고 width.

요소의 value 속성은 생략해야 합니다.

다음 IDL 속성과 메서드는 적용되지 않습니다: checked, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 그리고 valueAsNumber IDL 속성; setRangeText(), setSelectionRange(), stepDown(), 그리고 stepUp() 메서드.

4.10.5.1.18 제출 버튼 상태 (type=submit)

Element/input/submit

현재 모든 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 input 요소의 type 속성이 제출 버튼 상태에 있다면, 이 섹션의 규칙이 적용됩니다.

(이것은 추적 벡터입니다.) input 요소는 버튼을 나타내며, 활성화되면 양식을 제출합니다. 요소에 value 속성이 있으면 버튼의 레이블은 그 속성의 값이어야 하고, 그렇지 않으면 구현 정의 문자열이 "제출" 또는 유사한 의미여야 합니다. 요소는 버튼, 구체적으로는 제출 버튼입니다.

기본 레이블이 구현 정의이므로 버튼의 너비는 일반적으로 버튼의 레이블에 따라 다릅니다. 따라서 버튼의 너비는 몇 비트의 지문 정보가 누출될 수 있습니다. 이 정보는 사용자 에이전트 및 사용자의 지역 설정과 강하게 연관될 가능성이 높습니다.

요소의 입력 활성화 동작는 다음과 같습니다:

  1. 요소에 폼 소유자가 없는 경우, 반환합니다.

  2. 요소의 노드 문서완전히 활성화되지 않은 경우, 반환합니다.

  3. 제출 요소의 폼 소유자를 요소에서 userInvolvementevent사용자 탐색 개입으로 설정하여 제출합니다.

formaction, formenctype, formmethod, formnovalidate, 및 formtarget 속성은 양식 제출을 위한 속성입니다.

formnovalidate 속성은 제약 조건 검증을 트리거하지 않는 제출 버튼을 만드는 데 사용할 수 있습니다.

다음은 공통 input 요소의 내용 속성과 IDL 속성이 적용되는 항목입니다: dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, popovertarget, 그리고 popovertargetaction 내용 속성; value IDL 속성.

value IDL 속성은 기본값 모드입니다.

다음 내용 속성은 지정할 수 없으며 적용되지 않습니다: accept, alt, autocomplete, checked, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, 그리고 width.

다음 IDL 속성과 메서드는 적용되지 않습니다: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 그리고 valueAsNumber IDL 속성; select(), setRangeText(), setSelectionRange(), stepDown(), 그리고 stepUp() 메서드.

inputchange 이벤트는 적용되지 않습니다.

4.10.5.1.19 이미지 버튼 상태 (type=image)

Element/input/image

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 input 요소의 type 속성이 이미지 버튼 상태에 있다면, 이 섹션의 규칙이 적용됩니다.

input 요소는 사용자가 좌표를 선택하여 폼을 제출할 수 있는 이미지이거나, 폼을 제출하는 버튼을 나타냅니다. 이 요소는 버튼이며, 특히 제출 버튼입니다.

좌표는 폼 제출 중에 요소의 이름에 ".x"와 ".y"가 추가된 두 항목을 서버로 전송하여 전달됩니다. 좌표의 xy 구성 요소는 각각의 이름에 추가됩니다.


Element/input#src

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이미지는 src 속성에 의해 지정됩니다. src 속성은 반드시 있어야 하며, 페이지 또는 스크립트되지 않은 상호작용이 없는 비동적(선택적으로 애니메이션된) 이미지 리소스를 참조하는 유효한 비어 있지 않은 URL을 포함해야 합니다.

다음 이벤트가 발생할 때

사용자 에이전트가 이미지를 지원하지 않거나, 이미지 지원이 비활성화된 경우, 또는 사용자 에이전트가 요청 시에만 이미지를 가져오거나, src 속성의 값이 비어있는 문자열일 경우를 제외하고, 다음 단계를 실행합니다:

  1. urlsrc 속성의 값을 사용하여 요소의 노드 문서를 기준으로 URL을 인코딩-파싱하여 얻은 결과로 설정합니다.

  2. 만약 url이 실패라면, 리턴합니다.

  3. urlurl로, 클라이언트를 요소의 노드 문서관련 설정 객체로, 대상을 "image"로, 시작자 유형을 "input"로, 자격 증명 모드를 "include"로 설정하여 URL 자격 증명 플래그를 설정한 새 요청으로 만듭니다.

  4. 요청 request를 가져오고, processResponseEndOfBody응답 response로 설정한 다음, 다음 단계로 진행합니다:

    1. 다운로드가 성공적으로 완료되고 이미지가 사용 가능하다면, 요소 작업을 큐에 추가하여 사용자 상호작용 작업 소스에서 input 요소를 이벤트를 발생시켜 로드 이벤트를 input 요소에 발생시킵니다.

    2. 그렇지 않으면, 원격 서버에서 응답 없이 가져오는 작업이 실패하거나, 다운로드가 완료되었지만 이미지가 유효하지 않거나 지원되지 않는 이미지라면, 요소 작업을 큐에 추가하여 사용자 상호작용 작업 소스에서 input 요소를 이벤트를 발생시켜 오류 이벤트를 input 요소에 발생시킵니다.

이미지를 가져오는 작업은 요소의 로드 이벤트를 지연시켜야 하며, 리소스를 가져온 후 (아래에 정의된 대로) 네트워킹 작업 소스에 의해 큐에 추가된 작업이 실행될 때까지 노드 문서의 로드 이벤트를 지연시켜야 합니다.

이미지를 성공적으로 얻었고, 네트워크 오류가 없으며, 이미지 유형이 지원되는 유형이고, 이미지가 해당 유형의 유효한 이미지인 경우, 이미지는 사용 가능한 상태라고 합니다. 이미지가 완전히 다운로드되기 전에 이 상태가 참이라면, 이미지를 가져오는 동안 큐에 추가된 작업은 이미지를 적절히 표시하도록 업데이트해야 합니다.

사용자 에이전트는 이미지의 이미지 스니핑 규칙을 적용하여 이미지 유형을 결정해야 하며, 이미지의 관련 콘텐츠 유형 헤더공식 유형을 제공합니다. 이러한 규칙이 적용되지 않는 경우, 이미지의 유형은 이미지의 관련 콘텐츠 유형 헤더에 의해 제공된 유형이어야 합니다.

사용자 에이전트는 input 요소로 비이미지 리소스를 지원해서는 안 됩니다. 사용자 에이전트는 이미지 리소스에 포함된 실행 가능한 코드를 실행해서는 안 됩니다. 사용자 에이전트는 다중 페이지 리소스의 첫 페이지만 표시해야 하며, 리소스의 상호작용을 허용해서는 안 되지만 리소스의 애니메이션은 허용해야 합니다.


Element/input#alt

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

alt 속성은 이미지를 사용할 수 없는 사용자 및 사용자 에이전트를 위한 버튼의 텍스트 라벨을 제공합니다. alt 속성은 반드시 있어야 하며, 이미지가 없는 경우에 적합한 버튼에 적합한 라벨을 포함해야 합니다.

input 요소는 차원 속성을 지원합니다.


src 속성이 설정되고, 이미지가 사용 가능하며 사용자 에이전트가 해당 이미지를 표시하도록 구성된 경우, 요소는 제어를 나타내며, 이 제어는 src 속성에 의해 지정된 이미지에서 좌표를 선택할 수 있도록 합니다. 이 경우, 요소가 변경 가능한 상태라면, 사용자 에이전트는 사용자가 이 좌표를 선택할 수 있도록 해야 합니다.

그렇지 않은 경우, 요소는 제출 버튼을 나타내며, 이 버튼의 라벨은 alt 속성의 값에 의해 결정됩니다.

요소의 입력 활성화 동작이벤트에 따라 다음과 같습니다:

  1. 요소에 폼 소유자가 없다면, 리턴합니다.

  2. 요소의 노드 문서완전히 활성화되지 않았다면, 리턴합니다.

  3. 사용자가 좌표를 명시적으로 선택하면서 제어를 활성화한 경우, 요소의 선택된 좌표를 해당 좌표로 설정합니다.

    이는 위에서 설명한 조건에서만 가능합니다. 요소가 제어를 나타낼 때에만 해당됩니다. 그럼에도 불구하고 사용자는 좌표를 명시적으로 선택하지 않고 제어를 활성화할 수 있습니다.

  4. 요소의 폼 제출폼 소유자에서 사용자 관여로 설정하여 수행합니다.

요소의 선택된 좌표x 구성 요소와 y 구성 요소로 이루어져 있습니다. 초기값은 (0, 0)입니다. 좌표는 요소의 이미지의 가장자리를 기준으로 하며, 좌표 공간의 x 방향은 오른쪽으로, y 방향은 아래로 향합니다.

x 구성 요소는 유효한 정수여야 하며, 다음 범위 내의 숫자를 나타냅니다: −(borderleft+paddingleft) ≤ xwidth+borderright+paddingright. 여기서 width는 이미지의 렌더링된 너비, borderleft는 이미지의 왼쪽 테두리의 너비, paddingleft는 이미지의 왼쪽 패딩의 너비, borderright는 이미지의 오른쪽 테두리의 너비, paddingright는 이미지의 오른쪽 패딩의 너비를 나타내며, 모든 치수는 CSS 픽셀로 표시됩니다.

y 구성 요소는 유효한 정수여야 하며, 다음 범위 내의 숫자를 나타냅니다: −(bordertop+paddingtop) ≤ yheight+borderbottom+paddingbottom. 여기서 height는 이미지의 렌더링된 높이, bordertop는 이미지의 상단 테두리의 너비, paddingtop는 이미지의 상단 패딩의 너비, borderbottom는 이미지의 하단 테두리의 너비, paddingbottom는 이미지의 하단 패딩의 너비를 나타내며, 모든 치수는 CSS 픽셀로 표시됩니다.

테두리나 패딩이 없는 경우, 그 너비는 CSS 픽셀로 0이 됩니다.


formaction, formenctype, formmethod, formnovalidate, 및 formtarget 속성은 폼 제출을 위한 속성입니다.

image.width [ = value ]
image.height [ = value ]

이 속성들은 이미지의 실제 렌더링된 크기를 반환하거나, 크기가 알려지지 않은 경우 0을 반환합니다.

이 속성들은 설정할 수 있으며, 해당 콘텐츠 속성을 변경합니다.

다음의 공통 input 요소 콘텐츠 속성 및 IDL 속성이 요소에 적용됩니다: alt, formaction, formenctype, formmethod, formnovalidate, formtarget, height, popovertarget, popovertargetaction, src, 및 width 콘텐츠 속성들; value IDL 속성.

다음의 콘텐츠 속성은 요소에 지정되어서는 안 되며, 적용되지 않습니다: accept, autocomplete, checked, dirname, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, 및 step.

요소의 value 속성은 생략해야 합니다.

다음의 IDL 속성과 메서드는 요소에 적용되지 않습니다: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 및 valueAsNumber IDL 속성들; select(), setRangeText(), setSelectionRange(), stepDown(), 및 stepUp() 메서드들.

inputchange 이벤트는 적용되지 않습니다.

이 상태의 동작은 img 요소의 동작과 유사한 측면이 많습니다. 독자들은 해당 섹션을 읽어보기를 권장하며, 많은 동일한 요구 사항이 더 자세히 설명되어 있습니다.

다음 폼을 참고하세요:

<form action="process.cgi">
<input type=image src=map.png name=where alt="위치 목록 표시">
</form>

사용자가 이미지의 (127,40) 좌표를 클릭하면 폼을 제출하는 데 사용되는 URL은 "process.cgi?where.x=127&where.y=40"이 됩니다.

(이 예제에서는 지도를 보지 못하는 사용자가 대신 "위치 목록 표시" 라벨이 있는 버튼을 보고, 버튼을 클릭하면 서버가 지도의 위치 대신 선택할 위치 목록을 표시한다고 가정합니다.)

4.10.5.1.20 리셋 버튼 상태 (type=reset)

Element/input/reset

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 input 요소의 type 속성이 리셋 버튼 상태에 있다면, 이 섹션의 규칙이 적용됩니다.

(이것은 추적 벡터입니다.) input 요소는 폼을 리셋하는 버튼을 나타냅니다. 요소에 value 속성이 있으면, 버튼의 라벨은 그 속성의 값이어야 합니다. 그렇지 않으면, "리셋" 또는 그와 비슷한 의미의 구현 정의 문자열이어야 합니다. 이 요소는 버튼입니다.

기본 라벨이 구현 정의이기 때문에, 버튼의 너비는 보통 버튼 라벨에 따라 달라지므로, 버튼의 너비가 지문 인식 가능성 있는 몇 비트의 정보를 누출할 수 있습니다. 이 비트들은 사용자 에이전트의 정체성과 사용자의 로캘과 강하게 연관될 가능성이 큽니다.

요소의 입력 활성화 동작은 다음과 같습니다:

  1. 요소에 폼 소유자가 없다면, 리턴합니다.

  2. 요소의 노드 문서완전히 활성화되지 않았다면, 리턴합니다.

  3. 해당 요소의 폼을 리셋합니다. 폼 소유자로부터 요소를 리셋합니다.

제약 조건 검증: 이 요소는 제약 조건 검증에서 제외됩니다.

value IDL 속성은 이 요소에 적용되며, 기본 모드입니다.

다음의 공통 input 요소 콘텐츠 속성은 요소에 적용됩니다: popovertargetpopovertargetaction.

다음의 콘텐츠 속성은 요소에 지정되어서는 안 되며, 적용되지 않습니다: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, 및 width.

다음의 IDL 속성과 메서드는 요소에 적용되지 않습니다: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 및 valueAsNumber IDL 속성들; select(), setRangeText(), setSelectionRange(), stepDown(), 및 stepUp() 메서드들.

inputchange 이벤트는 적용되지 않습니다.

4.10.5.1.21 버튼 상태 (type=button)

Element/input/button

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

만약 input 요소의 type 속성이 버튼 상태에 있다면, 이 섹션의 규칙이 적용됩니다.

input 요소는 기본 동작이 없는 버튼을 나타냅니다. 버튼의 라벨은 value 속성에서 제공되어야 하며, 비어 있는 문자열일 수 있습니다. 요소에 value 속성이 있으면, 버튼의 라벨은 그 속성의 값이어야 하며, 그렇지 않으면 비어 있는 문자열이어야 합니다. 이 요소는 버튼입니다.

이 요소에는 입력 활성화 동작이 없습니다.

제약 조건 검증: 이 요소는 제약 조건 검증에서 제외됩니다.

value IDL 속성은 이 요소에 적용되며, 기본 모드입니다.

다음의 공통 input 요소 콘텐츠 속성은 요소에 적용됩니다: popovertargetpopovertargetaction.

다음의 콘텐츠 속성은 요소에 지정되어서는 안 되며, 적용되지 않습니다: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, 및 width.

다음의 IDL 속성과 메서드는 요소에 적용되지 않습니다: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, 및 valueAsNumber IDL 속성들; select(), setRangeText(), setSelectionRange(), stepDown(), 및 stepUp() 메서드들.

inputchange 이벤트는 적용되지 않습니다.

4.10.5.2 폼 컨트롤의 현지화와 관련된 구현 메모

이 섹션은 규범적이지 않습니다.

사용자에게 표시되는 날짜, 시간, 및 숫자 컨트롤의 형식은 폼 제출에 사용되는 형식과 독립적입니다.

브라우저는 input 요소의 언어가 암시하는 로케일 또는 사용자가 선호하는 로케일의 관습에 따라 날짜, 시간, 및 숫자를 표시하는 사용자 인터페이스를 사용하는 것이 권장됩니다. 페이지의 로케일을 사용하면 페이지에서 제공된 데이터와의 일관성이 보장됩니다.

예를 들어, 미국 영어 페이지에서 Cirque De Soleil 쇼가 02/03에 열릴 것이라고 주장하지만, 브라우저가 영국 영어 로케일로 설정되어 티켓 구매 날짜 선택기에서 03/02만 표시된다면, 이는 사용자에게 혼란을 줄 것입니다. 페이지의 로케일을 사용하면 적어도 날짜가 모든 곳에서 동일한 형식으로 표시되도록 보장할 수 있습니다. (물론, 사용자가 한 달 늦게 도착하는 상황이 발생할 위험은 여전히 있지만, 이러한 문화적 차이에 대해서는 할 수 있는 일이 한정적입니다...)

4.10.5.3 공통 input 요소 속성

이 속성들은 input 요소의 type 속성이 해당 속성이 적용된다고 명시된 상태에 있는 경우에만 적용됩니다. 속성이 input 요소에 적용되지 않는 경우, 사용자 에이전트는 아래의 요구 사항 및 정의와 관계없이 해당 속성을 무시해야 합니다.

4.10.5.3.1 maxlengthminlength 속성

maxlength 속성은 적용될 때 폼 컨트롤 maxlength 속성입니다.

minlength 속성은 적용될 때 폼 컨트롤 minlength 속성입니다.

만약 input 요소에 허용되는 최대 값 길이가 있다면, 요소의 value 속성 값의 길이는 요소의 허용되는 최대 값 길이보다 작거나 같아야 합니다.

다음 예시는 메시징 클라이언트의 텍스트 입력을 임의로 고정된 문자 수로 제한하여 이 매체를 통한 대화가 간결해지고 지능적인 담론을 억제할 수 있는 방법을 보여줍니다.

<label>What are you doing? <input name=status maxlength=140></label>

여기서 비밀번호는 최소 길이를 갖습니다:

<p><label>Username: <input name=u required></label>
<p><label>Password: <input name=p required minlength=12></label>
4.10.5.3.2 size 속성

size 속성은 시각적 렌더링에서 사용자가 요소의 value를 편집하는 동안 사용자가 볼 수 있는 문자 수를 지정합니다.

size 속성은 지정된 경우 유효한 음수가 아닌 정수이며, 0보다 커야 합니다.

속성이 존재하는 경우, 그 값은 음수가 아닌 정수를 구문 분석하는 규칙을 사용하여 해석되어야 하며, 결과가 0보다 큰 경우, 사용자 에이전트는 최소한 해당 문자 수가 표시되도록 해야 합니다.

size IDL 속성은 0보다 큰 양수로만 제한되며 기본값은 20입니다.

4.10.5.3.3 readonly 속성

readonly 속성은 불리언 속성으로, 사용자가 폼 컨트롤을 편집할 수 있는지 여부를 제어합니다. 지정된 경우, 요소는 변경 가능하지 않습니다.

제약 조건 검증: readonly 속성이 input 요소에 지정된 경우, 해당 요소는 제약 조건 검증에서 제외됩니다.

disabledreadonly의 차이점은 읽기 전용 컨트롤은 여전히 기능할 수 있는 반면, 비활성화된 컨트롤은 활성화될 때까지 일반적으로 기능하지 않는다는 것입니다. 이 표준의 다른 곳에서는 비활성화 개념을 참조하는 규범적 요구 사항과 함께 더 자세히 설명되어 있습니다. (예를 들어, 요소의 활성화 동작, 포커스 가능한 영역인지 여부, 또는 폼 데이터 세트 구성 시기 등). 비활성화된 컨트롤과의 사용자 상호작용과 관련된 기타 동작, 예를 들어 텍스트를 선택하거나 복사할 수 있는지 여부는 이 표준에서 정의되지 않습니다.

다른 컨트롤(예: 체크박스 및 버튼)의 경우 읽기 전용 상태와 비활성화 상태 사이에 유용한 구별이 없으므로 readonly 속성은 적용되지 않습니다.

다음 예에서 기존 제품 식별자는 수정할 수 없지만, 새 제품을 나타내는 행과 일관성을 유지하기 위해 여전히 폼의 일부로 표시됩니다(식별자가 아직 입력되지 않은 경우).

<form action="products.cgi" method="post" enctype="multipart/form-data">
 <table>
  <tr> <th> Product ID <th> Product name <th> Price <th> Action
  <tr>
   <td> <input readonly="readonly" name="1.pid" value="H412">
   <td> <input required="required" name="1.pname" value="Floor lamp Ulke">
   <td> $<input required="required" type="number" min="0" step="0.01" name="1.pprice" value="49.99">
   <td> <button formnovalidate="formnovalidate" name="action" value="delete:1">Delete</button>
  </tr>
   <td> <input readonly="readonly" name="2.pid" value="FG28">
   <td> <input required="required" name="2.pname" value="Table lamp Ulke">
   <td> $<input required="required" type="number" min="0" step="0.01" name="2.pprice" value="24.99">
   <td> <button formnovalidate="formnovalidate" name="action" value="delete:2">Delete</button>
  </tr>
   <td> <input readonly="readonly" name="3.pid" value="" pattern="[A-Z0-9]+">
   <td> <input required="required" name="3.pname" value="">
   <td> $<input required="required" type="number" min="0" step="0.01" name="3.pprice" value="">
   <td> <button formnovalidate="formnovalidate" name="action" value="delete:3">Delete</button>
 </table>
 <p> <button formnovalidate="formnovalidate" name="action" value="add">Add</button>
 </p>
 <p> <button name="action" value="update">Save</button> </p>
</form>
4.10.5.3.4 required 속성

required 속성은 부울 속성 입니다. 지정된 경우, 요소는 필수입니다.

제약 조건 유효성 검사: 요소가 필수이고, 그 IDL 속성이 적용되며, 모드가 이고, 요소가 변경 가능하며, 요소의 이 빈 문자열일 경우, 해당 요소는 누락된 상태가 됩니다.

다음 양식에는 이메일 주소와 비밀번호를 위한 두 개의 필수 필드가 있습니다. 또한, 비밀번호 필드와 이 세 번째 필드에 동일한 비밀번호를 입력해야만 유효한 세 번째 필드가 있습니다.

<h1>새 계정 만들기</h1>
<form action="/newaccount" method=post
      oninput="up2.setCustomValidity(up2.value != up.value ? 'Passwords do not match.' : '')">
 <p>
  <label for="username">이메일 주소:</label>
  <input id="username" type=email required name=un>
 <p>
  <label for="password1">비밀번호:</label>
  <input id="password1" type=password required name=up>
 <p>
  <label for="password2">비밀번호 확인:</label>
  <input id="password2" type=password name=up2>
 <p>
  <input type=submit value="계정 만들기">
</form>

라디오 버튼의 경우, required 속성은 그룹 내의 라디오 버튼 중 하나라도 선택되면 만족됩니다. 따라서, 다음 예에서 라디오 버튼 중 하나라도 체크되면 됩니다. 단, 필수로 표시된 라디오 버튼만 해당되는 것은 아닙니다:

<fieldset>
 <legend>이 영화가 베크델 테스트를 통과했습니까?</legend>
 <p><label><input type="radio" name="bechdel" value="no-characters"> 아니요, 영화에 여성 캐릭터가 두 명도 없습니다. </label>
 <p><label><input type="radio" name="bechdel" value="no-names"> 아니요, 여성 캐릭터가 서로 대화를 나누지 않습니다. </label>
 <p><label><input type="radio" name="bechdel" value="no-topic"> 아니요, 여성 캐릭터가 서로 대화할 때는 항상 남성 캐릭터에 대한 이야기입니다. </label>
 <p><label><input type="radio" name="bechdel" value="yes" required> 네. </label>
 <p><label><input type="radio" name="bechdel" value="unknown"> 잘 모르겠습니다. </label>
</fieldset>

라디오 버튼 그룹이 필수인지 아닌지에 대한 혼동을 피하기 위해, 저자들은 그룹 내 모든 라디오 버튼에 속성을 명시할 것을 권장합니다. 사실, 일반적으로, 저자들은 처음부터 선택된 제어 항목이 없는 라디오 버튼 그룹을 피하는 것이 좋습니다. 이러한 상태는 사용자가 되돌릴 수 없는 상태이므로, 일반적으로 열악한 사용자 인터페이스로 간주됩니다.

4.10.5.3.5 multiple 속성

Attributes/multiple

모든 최신 엔진에서 지원됩니다.

Firefox3.6+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Element/input#attr-multiple

모든 최신 엔진에서 지원됩니다.

Firefox3.6+Safari4+Chrome2+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android≤37+Samsung Internet?Opera Android≤12.1+

multiple 속성은 사용자가 하나 이상의 값을 지정할 수 있는지 여부를 나타내는 부울 속성입니다.

다음 예는 이메일 클라이언트의 "받는 사람" 필드가 여러 이메일 주소를 수락할 수 있는 방법을 보여줍니다.

<label>받는 사람: <input type=email multiple name=to></label>

사용자의 연락처 데이터베이스에 많은 친구가 있고, 그 중 두 명이 "스파이더맨"("spider@parker.example.net" 주소)과 "스칼렛 위치"("scarlet@avengers.example.net" 주소)라고 가정했을 때, 사용자가 "s"를 입력하면, 사용자 에이전트는 이 두 이메일 주소를 사용자에게 제안할 수 있습니다.

페이지는 또한 사용자의 연락처 데이터베이스를 사이트와 연동할 수 있습니다:

<label>받는 사람: <input type=email multiple name=to list=contacts></label>
...
<datalist id="contacts">
 <option value="hedral@damowmow.com">
 <option value="pillar@example.com">
 <option value="astrophy@cute.example">
 <option value="astronomy@science.example.org">
</datalist>

사용자가 이 텍스트 컨트롤에 "bob@example.net"을 입력한 후 "s"로 시작하는 두 번째 이메일 주소를 입력하기 시작했다고 가정해보십시오. 사용자 에이전트는 앞서 언급한 두 친구의 이메일 주소뿐만 아니라 datalist 요소에 제공된 "astrophy" 및 "astronomy" 값을 모두 표시할 수 있습니다.

다음 예는 이메일 클라이언트의 "첨부 파일" 필드가 여러 파일 업로드를 수락할 수 있는 방법을 보여줍니다.

<label>첨부 파일: <input type=file multiple name=att></label>
4.10.5.3.6 pattern 속성

Attributes/pattern

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome4+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android≤37+Samsung Internet?Opera Android≤12.1+

Attributes/pattern

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

pattern 속성은 컨트롤의 또는 multiple 속성이 설정되어 적용된 경우, 컨트롤의 값들을 확인하는 정규 표현식을 지정합니다.

지정된 경우, 속성의 값은 JavaScript Pattern[+UnicodeSetsMode, +N] 생산자와 일치해야 합니다.

input 요소의 컴파일된 패턴 정규 표현식이 존재하는 경우, 이는 JavaScript RegExp 객체입니다. 이는 다음과 같이 결정됩니다:

  1. 요소에 pattern 속성이 지정되지 않은 경우, 아무것도 반환하지 않습니다. 요소에는 컴파일된 패턴 정규 표현식이 없습니다.

  2. pattern을 요소의 pattern 속성의 값으로 설정합니다.

  3. regexpCompletionRegExpCreate(pattern, "v")로 설정합니다.

  4. regexpCompletion이상 완료인 경우, 아무것도 반환하지 않습니다. 요소에는 컴파일된 패턴 정규 표현식이 없습니다.

    사용자 에이전트는 이 오류를 디버깅을 돕기 위해 개발자 콘솔에 기록할 것을 권장합니다.

  5. anchoredPattern을 "^(?:"로 설정하고, 그 뒤에 pattern을 추가하고, 그 뒤에 ")$"를 추가합니다.

  6. ! RegExpCreate(anchoredPattern, "v")을 반환합니다.

이 단계를 수행하는 이유는 속성의 pattern 값을 직접 사용하는 대신 두 가지입니다. 첫째, 문자열과 비교할 때 정규 표현식의 시작 부분이 문자열의 시작 부분에 고정되도록 하고 끝 부분이 문자열의 끝 부분에 고정되도록 합니다. 둘째, 정규 표현식이 독립된 형태로 유효하도록 하며, "^(?:"와 ")$" 앵커로 둘러싸인 후에만 유효해지는 것이 아니라는 것을 보장합니다.

RegExp 객체 regexp은 문자열 input일치시킵니다. 이는 ! RegExpBuiltinExec(regexp, input)이 null이 아닌 경우입니다.

제약 조건 유효성 검사: 요소의 이 빈 문자열이 아니고, 요소의 multiple 속성이 지정되지 않았거나 해당 속성이 요소의 input 요소에 적용되지 않으며, 요소에 컴파일된 패턴 정규 표현식이 있고, 그 정규 표현식이 요소의 과 일치하지 않으면 요소는 패턴 불일치 문제가 있습니다.

제약 조건 유효성 검사: 요소의 이 빈 문자열이 아니고, 요소의 multiple 속성이 지정되어 있고, 해당 속성이 input 요소에 적용되며, 요소에 컴파일된 패턴 정규 표현식이 있고, 그 정규 표현식이 요소의 각 과 일치하지 않으면 요소는 패턴 불일치 문제가 있습니다.

input 요소에 pattern 속성이 지정된 경우, 작성자는 패턴에 대한 설명을 제공하기 위해 title 속성을 포함해야 합니다. 사용자 에이전트는 패턴이 일치하지 않는다고 사용자에게 알리거나, 도구 설명 또는 제어가 포커스를 받을 때 보조 기술에 의해 읽히는 등 적절한 시기에 이 속성의 내용을 사용할 수 있습니다.

예를 들어, 다음 코드 조각:

<label> 부품 번호:
 <input pattern="[0-9][A-Z]{3}" name="part"
        title="부품 번호는 숫자 뒤에 세 개의 대문자입니다."/>
</label>

...는 UA가 다음과 같은 경고를 표시하게 할 수 있습니다:

부품 번호는 숫자 뒤에 세 개의 대문자입니다.
이 필드가 올바르지 않으면 이 양식을 제출할 수 없습니다.

컨트롤에 pattern 속성이 있는 경우, title 속성은 패턴을 설명해야 합니다. 사용자가 컨트롤을 작성하는 데 도움이 되는 한, 추가 정보를 포함할 수도 있습니다. 그렇지 않으면 보조 기술이 손상될 수 있습니다.

예를 들어, title 속성에 컨트롤의 캡션이 포함되어 있으면 보조 기술이 입력한 텍스트가 요구된 패턴과 일치하지 않습니다. 생일과 같은 말을 하게 될 수 있는데, 이는 유용하지 않습니다.

사용자 에이전트는 여전히 title 속성을 비오류 상황에서도 표시할 수 있습니다(예: 컨트롤 위에 커서를 올렸을 때 도구 설명으로 표시됨). 따라서 작성자는 title 속성을 오류가 발생한 것처럼 작성하지 않도록 주의해야 합니다.

4.10.5.3.7 minmax 속성

Attributes/max

모든 최신 엔진에서 지원됩니다.

Firefox16+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Attributes/min

모든 최신 엔진에서 지원됩니다.

Firefox16+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

일부 폼 컨트롤은 사용자가 제공할 수 있는 허용 범위를 제한하는 명시적 제약 조건을 가질 수 있습니다. 일반적으로 이러한 범위는 선형적이고 연속적입니다. 그러나 폼 컨트롤은 주기적 도메인을 가질 수 있으며, 이 경우 폼 컨트롤의 가장 넓은 가능한 범위는 유한하며 저자는 경계를 넘는 명시적 범위를 지정할 수 있습니다.

특히, type=time 컨트롤의 가장 넓은 범위는 자정에서 자정까지(24시간)이며, 저자는 연속적인 선형 범위(예: 오후 9시부터 오후 11시까지)와 자정을 넘는 불연속 범위(예: 오후 11시부터 오전 1시까지)를 모두 설정할 수 있습니다.

minmax 속성은 요소의 허용 범위를 나타냅니다.

이들의 구문은 type 속성의 현재 상태를 정의하는 섹션에 의해 정의됩니다.

요소에 min 속성이 있고, 문자열을 숫자로 변환하는 알고리즘을 이 속성의 값에 적용한 결과가 숫자인 경우, 해당 숫자가 요소의 최소값이 됩니다. 그렇지 않으면, type 속성의 현재 상태가 기본 최소값을 정의하는 경우, 그 값이 최소값이 됩니다. 그렇지 않으면 요소에는 최소값이 없습니다.

min 속성은 또한 단계 기준값을 정의합니다.

요소에 max 속성이 있고, 문자열을 숫자로 변환하는 알고리즘을 이 속성의 값에 적용한 결과가 숫자인 경우, 해당 숫자가 요소의 최대값이 됩니다. 그렇지 않으면, type 속성의 현재 상태가 기본 최대값을 정의하는 경우, 그 값이 최대값이 됩니다. 그렇지 않으면 요소에는 최대값이 없습니다.

요소가 주기적 도메인을 갖지 않는 경우, max 속성의 값 (해당 최대값)은 min 속성의 값(해당 최소값)보다 작지 않아야 합니다.

요소가 주기적 도메인을 갖지 않고, 최대값최소값보다 작은 경우, 요소에 이 있는 한, 요소는 언더플로우 또는 오버플로우 상태에 있게 됩니다.

요소가 역 범위를 갖는 경우, 이는 주기적 도메인을 가지며, 해당 최대값이 해당 최소값보다 작은 경우입니다.

요소가 정의된 최소값 또는 정의된 최대값을 가지고 있으면, 범위 제한이 있다고 말할 수 있습니다.

제약 조건 유효성 검사: 요소에 최소값이 있고 역 범위가 없으며, 문자열을 숫자로 변환하는 알고리즘을 요소의 에 적용한 결과가 숫자이고 그 숫자가 해당 최소값보다 작으면 요소는 언더플로우 상태에 있습니다.

제약 조건 유효성 검사: 요소에 최대값이 있고 역 범위가 없으며, 문자열을 숫자로 변환하는 알고리즘을 요소의 에 적용한 결과가 숫자이고 그 숫자가 해당 최대값보다 크면 요소는 오버플로우 상태에 있습니다.

제약 조건 유효성 검사: 요소가 역 범위를 가지며, 문자열을 숫자로 변환하는 알고리즘을 요소의 에 적용한 결과가 숫자이고, 그 숫자가 해당 최대값보다 크고 동시에 해당 최소값보다 작으면, 요소는 동시에 언더플로우오버플로우 상태에 있습니다.

다음 날짜 컨트롤은 1980년대 이전의 날짜로 입력을 제한합니다:

<input name=bday type=date max="1979-12-31">

다음 숫자 컨트롤은 0보다 큰 정수로 입력을 제한합니다:

<input name=quantity required="" type="number" min="1" value="1">

다음 시간 컨트롤은 오후 9시에서 오전 6시 사이에 발생하는 분으로 입력을 제한하며, 기본값은 자정입니다:

<input name="sleepStart" type=time min="21:00" max="06:00" step="60" value="00:00">
4.10.5.3.8 step 속성

Attributes/step

모든 최신 엔진에서 지원됩니다.

Firefox16+Safari5+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

step 속성은 또는 값들의 예상(및 필수) 세분성을 제한하여 허용되는 값을 나타냅니다. type 속성의 현재 상태를 정의하는 섹션은 또한 기본 단계, 단계 배율 및 경우에 따라 기본 단계 기준값을 정의하며, 이는 아래에 설명된 대로 속성을 처리하는 데 사용됩니다.

step 속성이 지정된 경우, 이 속성은 유효한 부동 소수점 숫자로서 0보다 큰 숫자여야 하며, 또는 문자열 "any"와 ASCII 대소문자 구분 없이 일치해야 합니다.

이 속성은 요소에 대해 허용되는 값의 단계를 다음과 같이 제공합니다:

  1. 속성이 적용되지 않으면, 허용되는 값의 단계가 없습니다.

  2. 그렇지 않고 속성이 없으면, 허용되는 값의 단계기본 단계단계 배율을 곱한 값입니다.

  3. 그렇지 않고 속성의 값이 문자열 "any"와 ASCII 대소문자 구분 없이 일치하는 경우, 허용되는 값의 단계가 없습니다.

  4. 그렇지 않고 부동 소수점 숫자 값을 구문 분석하는 규칙을 적용한 결과가 오류, 0 또는 0보다 작은 숫자라면, 허용되는 값의 단계기본 단계단계 배율을 곱한 값입니다.

  5. 그렇지 않은 경우, 허용되는 값의 단계는 속성의 값을 적용할 때 부동 소수점 숫자 값을 구문 분석하는 규칙에 의해 반환된 숫자에 단계 배율을 곱한 값입니다.

단계 기준값은 다음 알고리즘에 의해 반환된 값입니다:

  1. 요소에 min 콘텐츠 속성이 있고, 문자열을 숫자로 변환하는 알고리즘을 이 속성의 값에 적용한 결과가 오류가 아닌 경우, 해당 결과를 반환합니다.

  2. 요소에 value 콘텐츠 속성이 있고, 문자열을 숫자로 변환하는 알고리즘을 이 속성의 값에 적용한 결과가 오류가 아닌 경우, 해당 결과를 반환합니다.

  3. 이 요소에 대해 type 속성의 상태에 따라 정의된 기본 단계 기준값이 있으면, 그 값을 반환합니다.

  4. 0을 반환합니다.

제약 조건 유효성 검사: 요소에 허용되는 값의 단계가 있고, 문자열을 숫자로 변환하는 알고리즘을 요소의 에 적용한 결과가 숫자이고, 그 숫자에서 단계 기준값을 뺀 값이 허용되는 값의 단계의 정수 배수가 아닌 경우, 요소는 단계 불일치 문제를 겪고 있습니다.

다음 범위 컨트롤은 0에서 1 사이의 값만 허용하며, 이 범위에서 256단계를 허용합니다:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

다음 컨트롤은 하루 중 언제든지 선택할 수 있으며, 예를 들어 천분의 일초 단위 또는 그 이상의 정확도로 선택할 수 있습니다:

<input name=favtime type=time step=any>

일반적으로, 시간 컨트롤은 1분 단위로 제한됩니다.

4.10.5.3.9 list 속성

Element/input#list

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari12.1+Chrome20+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android12.1+

list 속성은 사용자에게 제안된 미리 정의된 옵션을 나열하는 요소를 식별하는 데 사용됩니다.

존재하는 경우, 그 값은 동일한 트리에서 datalist 요소의 ID여야 합니다.

제안 소스 요소트리 내에서 list 속성의 값과 동일한 ID를 가진 첫 번째 요소입니다. 해당 요소가 datalist 요소인 경우에만 적용됩니다. list 속성이 없거나, 해당 ID를 가진 요소가 없거나, 첫 번째 요소가 datalist 요소가 아닌 경우, 제안 소스 요소는 없습니다.

제안 소스 요소가 존재하는 경우, 사용자가 입력 요소의 을 편집할 때 사용자 에이전트는 제안 소스 요소에서 제공하는 제안을 사용자가 사용하는 컨트롤 유형에 맞게 제시해야 합니다. 필요에 따라, 사용자 에이전트는 제안의 라벨을 사용하여 사용자에게 제안을 식별할 수 있습니다.

사용자 에이전트는 제안의 수가 많은 경우 제안 소스 요소에서 제안을 필터링하여 가장 관련성이 높은 제안만 포함하는 것을 권장합니다. 정확한 임계값은 정의되지 않았지만, 목록을 4~7개의 값으로 제한하는 것이 합리적입니다. 사용자의 입력에 따라 필터링할 때, 사용자 에이전트는 제안의 라벨 모두에서 일치를 검색해야 합니다. 입력 변형이 일치 과정에 어떻게 영향을 미치는지 고려해야 합니다. 유니코드 정규화를 적용하여 다른 키보드 또는 입력 메커니즘으로 인해 발생하는 서로 다른 유니코드 코드 포인트 시퀀스가 일치 과정에 방해가 되지 않도록 해야 합니다. 대소문자 변형은 무시해야 하며, 이는 언어별 대소문자 매핑이 필요할 수 있습니다. 이러한 예에 대한 자세한 내용은 Character Model for the World Wide Web: String Matching을 참조하십시오. 또한 사용자 에이전트는 다른 일치 기능도 제공할 수 있습니다: 예를 들어, 가나의 다른 형태를 서로(또는 한자와) 일치시키거나, 악센트를 무시하거나, 맞춤법 교정을 적용하는 등의 기능이 포함될 수 있습니다. [CHARMODNORM]

이 텍스트 필드는 JavaScript 함수 유형을 선택할 수 있습니다.

<input type="text" list="function-types">
<datalist id="function-types">
  <option value="function">function</option>
  <option value="async function">async function</option>
  <option value="function*">generator function</option>
  <option value="=>">arrow function</option>
  <option value="async =>">async arrow function</option>
  <option value="async function*">async generator function</option>

위의 제안을 따르는 사용자 에이전트는 라벨을 모두 표시합니다:

오른쪽에 드롭다운 버튼이 있는 텍스트 상자; 아래에는 여섯 개의 값이 왼쪽에, 여섯 개의 라벨이 오른쪽에 있는 드롭다운 상자가 있습니다.

그런 다음 "arrow" 또는 "=>"을 입력하면 "arrow function" 및 "async arrow function" 라벨이 있는 항목으로 목록이 필터링됩니다. "generator" 또는 "*"을 입력하면 "generator function" 및 "async generator function" 라벨이 있는 항목으로 목록이 필터링됩니다.

항상 그렇듯이, 사용자 에이전트는 특정 요구 사항 및 사용자의 특정 상황에 적합한 사용자 인터페이스 결정을 자유롭게 내릴 수 있습니다. 그러나 이 부분은 역사적으로 구현자, 웹 개발자 및 사용자 모두에게 혼란을 야기해 왔으므로, 위에 몇 가지 "해야 할" 제안을 제공했습니다.

사용자가 제안을 선택할 때의 처리 방식은 요소가 단일 값만 허용하는 컨트롤인지, 아니면 여러 값을 허용하는지에 따라 달라집니다:

요소에 multiple 속성이 지정되지 않았거나 multiple 속성이 적용되지 않는 경우

사용자가 제안을 선택하면 입력 요소의 이 사용자가 직접 작성한 것처럼 선택한 제안의 으로 설정됩니다.

요소의 type 속성이 Email 상태에 있고 요소에 multiple 속성이 지정된 경우

사용자가 제안을 선택하면 사용자 에이전트는 입력 요소의 에 선택한 제안의 을 새 항목으로 추가하거나, 기존 항목을 선택한 제안의 값으로 변경해야 합니다. 이러한 동작 중 어떤 것이 적용될지는 사용자 인터페이스에 따라 구현 정의 방식으로 결정됩니다.


list 속성이 적용되지 않으면, 제안 소스 요소가 없습니다.

이 URL 필드는 몇 가지 제안을 제공합니다.

<label>홈페이지: <input name=hp type=url list=hpurls></label>
<datalist id=hpurls>
 <option value="https://www.google.com/" label="Google">
 <option value="https://www.reddit.com/" label="Reddit">

사용자의 히스토리에서 다른 URL도 나타날 수 있습니다; 이는 사용자 에이전트에 따라 달라집니다.

이 예제는 자동 완성 목록 기능을 사용하는 폼을 설계하는 방법을 보여주며, 레거시 사용자 에이전트에서도 유용하게 동작할 수 있습니다.

자동 완성 목록이 단순히 보조 기능으로 사용되고 콘텐츠에 중요하지 않은 경우, datalist 요소와 자식 option 요소만 사용하면 충분합니다. 레거시 사용자 에이전트에서 값이 렌더링되지 않도록 하려면, 값을 인라인이 아닌 value 속성에 배치해야 합니다.

<p>
 <label>
  품종을 입력하세요:
  <input type="text" name="breed" list="breeds">
  <datalist id="breeds">
   <option value="Abyssinian">
   <option value="Alpaca">
   <!-- ... -->
  </datalist>
 </label>
</p>

그러나 레거시 사용자 에이전트에서도 값을 보여야 하는 경우, 다음과 같이 datalist 요소 안에 대체 콘텐츠를 배치할 수 있습니다:

<p>
 <label>
  품종을 입력하세요:
  <input type="text" name="breed" list="breeds">
 </label>
 <datalist id="breeds">
  <label>
   또는 목록에서 선택하세요:
   <select name="breed">
    <option value=""> (선택되지 않음)
    <option>Abyssinian
    <option>Alpaca
    <!-- ... -->
   </select>
  </label>
 </datalist>
</p>

대체 콘텐츠는 datalist을 지원하지 않는 사용자 에이전트에서만 표시됩니다. 반면에 옵션은 datalist 요소의 자식이 아니더라도 모든 사용자 에이전트에서 감지됩니다.

option 요소가 datalist에서 사용되고 selected 상태인 경우, 레거시 사용자 에이전트에서 기본적으로 선택되지만(select 요소에 영향을 미치기 때문에), datalist을 지원하는 사용자 에이전트에서는 입력 요소에 영향을 미치지 않습니다.

4.10.5.3.10 placeholder 속성

Element/input#placeholder

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Element/input#attr-placeholder

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari4+Chrome3+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android≤37+Samsung Internet?Opera Android≤12.1+

placeholder 속성은 컨트롤에 값이 없을 때 사용자가 데이터를 입력하는 데 도움을 주기 위한 짧은 힌트(단어나 짧은 문구)를 나타냅니다. 힌트는 샘플 값이나 예상 형식에 대한 간단한 설명일 수 있습니다. 이 속성이 지정된 경우, 값에는 U+000A 줄 바꿈(LF) 또는 U+000D 캐리지 리턴(CR) 문자가 포함되지 않아야 합니다.

placeholder 속성은 라벨을 대체하는 용도로 사용해서는 안 됩니다. 더 긴 힌트나 기타 권장 텍스트의 경우, title 속성이 더 적합합니다.

이 메커니즘들은 매우 유사하지만 미묘한 차이가 있습니다: 컨트롤의 라벨에서 제공하는 힌트는 항상 표시됩니다; placeholder 속성에서 제공하는 짧은 힌트는 사용자가 값을 입력하기 전에 표시됩니다; title 속성에서 제공하는 힌트는 사용자가 추가 도움을 요청할 때 표시됩니다.

사용자 에이전트는 이 힌트를 컨트롤의 개행 문자를 제거한 이 빈 문자열일 때, 특히 컨트롤이 포커스되지 않은 경우 사용자에게 제시해야 합니다.

사용자 에이전트가 일반적으로 컨트롤이 포커스된 상태일 때 이 힌트를 표시하지 않는 경우에도, autofocus 속성에 의해 포커스된 경우에는 힌트를 표시해야 합니다. 이 경우 사용자가 포커스되기 전에 컨트롤을 살펴볼 기회를 가지지 못했을 수 있기 때문입니다.

다음은 placeholder 속성을 사용하는 메일 구성 사용자 인터페이스의 예입니다:

<fieldset>
 <legend>메일 계정</legend>
 <p><label>이름: <input type="text" name="fullname" placeholder="John Ratzenberger"></label></p>
 <p><label>주소: <input type="email" name="address" placeholder="john@example.net"></label></p>
 <p><label>비밀번호: <input type="password" name="password"></label></p>
 <p><label>설명: <input type="text" name="desc" placeholder="내 이메일 계정"></label></p>
</fieldset>

컨트롤의 내용은 한 방향성을 가지지만 placeholder는 다른 방향성을 가져야 하는 상황에서는, 속성 값에 유니코드의 양방향 알고리즘 서식 문자를 사용할 수 있습니다:

<input name=t1 type=tel placeholder="&#x202B;رقم الهاتف 1&#x202E;">
<input name=t2 type=tel placeholder="&#x202B;رقم الهاتف 2&#x202E;">

조금 더 명확하게 하기 위해, 다음은 인라인 아랍어 대신 숫자 문자 참조를 사용한 동일한 예제입니다:

<input name=t1 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605; &#1575;&#1604;&#1607;&#1575;&#1578;&#1601; 1&#x202E;">
<input name=t2 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605; &#1575;&#1604;&#1607;&#1575;&#1578;&#1601; 2&#x202E;">
4.10.5.4 공통 input 요소 API
input.value [ = value ]

폼 컨트롤의 현재 을 반환합니다.

값을 변경할 수 있습니다.

파일 업로드 컨트롤일 때 빈 문자열 이외의 값을 설정하면 "InvalidStateError" DOMException을 던집니다.

input.checked [ = value ]

폼 컨트롤의 현재 체크 상태를 반환합니다.

체크 상태를 변경할 수 있습니다.

input.files [ = files ]

FileList

모든 최신 엔진에서 지원됩니다.

Firefox3+Safari4+Chrome2+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11.1+

HTMLInputElement/files

모든 최신 엔진에서 지원됩니다.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+🔰 10+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

폼 컨트롤의 선택된 파일들을 나열하는 FileList 객체를 반환합니다.

컨트롤이 파일 컨트롤이 아닌 경우 null을 반환합니다.

선택된 파일을 변경하기 위해 FileList 객체로 설정할 수 있습니다. 예를 들어, 드래그 앤 드롭 작업의 결과로 설정할 수 있습니다.

input.valueAsDate [ = value ]

해당하는 경우, 폼 컨트롤의 을 나타내는 Date 객체를 반환합니다. 그렇지 않으면 null을 반환합니다.

값을 변경할 수 있습니다.

컨트롤이 날짜 또는 시간 기반이 아닌 경우 "InvalidStateError" DOMException을 던집니다.

input.valueAsNumber [ = value ]

해당하는 경우, 폼 컨트롤의 을 나타내는 숫자를 반환합니다. 그렇지 않으면 NaN을 반환합니다.

값을 변경할 수 있습니다. NaN으로 설정하면 기본값이 빈 문자열로 설정됩니다.

컨트롤이 날짜 또는 시간 기반이 아니거나 숫자 기반이 아닌 경우 "InvalidStateError" DOMException을 던집니다.

input.stepUp([ n ])

HTMLInputElement/stepUp

🔰 16+Safari5+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
input.stepDown([ n ])

HTMLInputElement/stepDown

🔰 16+Safari5+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

폼 컨트롤의 step 속성의 값에 n을 곱한 값만큼 변경합니다. n의 기본값은 1입니다.

컨트롤이 날짜 또는 시간 기반이 아니거나 숫자 기반이 아니거나 step 속성의 값이 "any"일 경우 "InvalidStateError" DOMException을 던집니다.

input.list

list 속성에 의해 지정된 datalist 요소를 반환합니다.

input.showPicker()

사용자가 값을 선택할 수 있도록 input에 대해 적용 가능한 선택기 UI를 표시합니다. (해당 컨트롤에 대해 선택기 UI가 구현되지 않은 경우 이 메서드는 아무 작업도 수행하지 않습니다.)

input변경 가능하지 않으면 "InvalidStateError" DOMException을 던집니다.

"NotAllowedError" DOMException를 일시적인 사용자 활성화 없이 호출할 경우 던집니다.

"SecurityError" DOMExceptioninput이 교차 출처 iframe 안에 있을 경우, input파일 업로드 또는 색상 상태가 아닌 한 던집니다.

value IDL 속성은 스크립트가 을 조작할 수 있게 합니다. input 요소의 속성입니다. 이 속성은 다음과 같은 모드 중 하나에 있으며, 각 모드는 속성의 동작을 정의합니다.

value

가져올 때, 요소의 현재 을 반환합니다.

설정 시:

  1. 요소의 oldValue로 저장합니다.

  2. 요소의 을 새로운 값으로 설정합니다.

  3. 요소의 더러운 값 플래그를 true로 설정합니다.

  4. 요소의 type 속성의 현재 상태가 정의된 경우, 값 정리 알고리즘을 호출합니다.

  5. 요소의 이 (값 정리 알고리즘을 적용한 후) oldValue와 다르고, 요소에 텍스트 입력 커서 위치가 있으면, 텍스트 컨트롤의 끝으로 텍스트 입력 커서 위치를 이동시키고 선택된 텍스트를 해제하고 선택 방향을 재설정하여 "none"으로 설정합니다.

기본값

가져올 때, 요소에 value 콘텐츠 속성이 있으면 그 속성의 값을 반환하고, 그렇지 않으면 빈 문자열을 반환합니다.

설정 시, 요소의 value 콘텐츠 속성 값을 새로운 값으로 설정합니다.

기본값/on

가져올 때, 요소에 value 콘텐츠 속성이 있으면 그 속성의 값을 반환하고, 그렇지 않으면 "on" 문자열을 반환합니다.

설정 시, 요소의 value 콘텐츠 속성 값을 새로운 값으로 설정합니다.

파일명

가져올 때, 선택된 파일 목록 중 첫 번째 파일의 이름 앞에 "C:\fakepath\" 문자열을 붙여 반환합니다. 파일 목록이 비어 있으면 빈 문자열을 반환합니다.

설정 시, 새로운 값이 빈 문자열이면 선택된 파일 목록을 비우고, 그렇지 않으면 "InvalidStateError" DOMException을 던집니다.

이 "fakepath" 요구 사항은 역사의 슬픈 사고입니다. 자세한 내용은 파일 업로드 상태 섹션의 예제를 참조하세요.

경로 구성 요소가 선택된 파일 목록의 파일 이름에 포함될 수 없으므로 "\fakepath\"는 경로 구성 요소로 오인될 수 없습니다.


checked IDL 속성은 스크립트가 체크 상태를 조작할 수 있게 합니다. 가져올 때, 요소의 현재 체크 상태를 반환해야 하며, 설정할 때, 요소의 체크 상태를 새로운 값으로 설정하고 요소의 더러운 체크 상태 플래그를 true로 설정해야 합니다.


files IDL 속성은 스크립트가 요소의 선택된 파일들에 접근할 수 있게 합니다.

가져올 때, IDL 속성이 적용되는 경우, 현재 선택된 파일들을 나타내는 FileList 객체를 반환해야 합니다. 목록이 변경될 때까지 동일한 객체를 반환해야 합니다. IDL 속성이 적용되지 않는 경우, null을 반환해야 합니다. [FILEAPI]

설정 시, 다음 단계를 수행해야 합니다:

  1. IDL 속성이 적용되지 않거나 주어진 값이 null인 경우, 반환합니다.

  2. 요소의 선택된 파일들을 주어진 값으로 교체합니다.


valueAsDate IDL 속성은 요소의 을 날짜로 해석한 것을 나타냅니다.

가져올 때, valueAsDate 속성이 적용되지 않는 경우, input 요소의 type 속성의 현재 상태에 대해 정의된 것처럼 null을 반환합니다. 그렇지 않으면, 요소의 에 대해 해당 상태에 정의된 문자열을 날짜 객체로 변환하는 알고리즘을 실행합니다. 알고리즘이 Date 객체를 반환하면 이를 반환하고, 그렇지 않으면 null을 반환합니다.

설정 시, valueAsDate 속성이 적용되지 않는 경우, input 요소의 type 속성의 현재 상태에 대해 정의된 것처럼 "InvalidStateError" DOMException을 던집니다. 그렇지 않으면, 새로운 값이 null이 아니거나 Date 객체가 NaN 시간 값을 나타내면, 요소의 을 빈 문자열로 설정합니다. 그렇지 않으면, 새로운 값에 대해 해당 상태에 정의된 날짜 객체를 문자열로 변환하는 알고리즘을 실행하고, 요소의 을 결과 문자열로 설정합니다.


valueAsNumber IDL 속성은 요소의 을 숫자로 해석한 것을 나타냅니다.

가져올 때, valueAsNumber 속성이 적용되지 않는 경우, input 요소의 type 속성의 현재 상태에 대해 정의된 것처럼 NaN 값을 반환합니다. 그렇지 않으면, 요소의 에 대해 해당 상태에 정의된 문자열을 숫자로 변환하는 알고리즘을 실행합니다. 알고리즘이 숫자를 반환하면 이를 반환하고, 그렇지 않으면 NaN 값을 반환합니다.

설정 시, 새로운 값이 무한대이면 TypeError 예외를 던집니다. 그렇지 않으면, valueAsNumber 속성이 적용되지 않는 경우, input 요소의 type 속성의 현재 상태에 대해 정의된 것처럼 "InvalidStateError" DOMException을 던집니다. 그렇지 않으면, 새로운 값이 NaN 값이면 요소의 을 빈 문자열로 설정합니다. 그렇지 않으면, 새로운 값에 대해 해당 상태에 정의된 숫자를 문자열로 변환하는 알고리즘을 실행하고, 요소의 을 결과 문자열로 설정합니다.


stepDown(n)stepUp(n) 메서드를 호출하면 다음 알고리즘이 실행되어야 합니다:

  1. stepDown()stepUp() 메서드가 input 요소의 type 속성의 현재 상태에 대해 정의된 대로 적용되지 않는 경우, "InvalidStateError" DOMException을 던집니다.

  2. 요소에 허용된 값 단계가 없는 경우, "InvalidStateError" DOMException을 던집니다.

  3. 요소에 최소값최대값이 있고 최소값최대값보다 큰 경우, 반환합니다.

  4. 요소에 최소값최대값이 있고, 요소의 최소값보다 크거나 같고, 요소의 최대값보다 작거나 같은 값 중 단계 기본값에서 빼서 허용된 값 단계의 정수 배수가 되는 값이 없는 경우, 반환합니다.

  5. 요소의 을 문자열에서 숫자로 변환하는 알고리즘에 적용하여 오류가 발생하지 않으면, value를 그 알고리즘의 결과로 설정합니다. 그렇지 않으면 value를 0으로 설정합니다.

  6. valueBeforeSteppingvalue로 설정합니다.

  7. 만약 value에서 단계 기본값을 뺀 값이 허용된 값 단계의 정수 배수가 아니라면, value단계 기본값에서 빼서 허용된 값 단계의 정수 배수가 되며, stepDown() 메서드가 호출되었을 때는 value보다 작고, 그렇지 않으면 value보다 큰 값 중 가장 가까운 값으로 설정합니다.

    그렇지 않으면 (value에서 단계 기본값을 뺀 값이 허용된 값 단계의 정수 배수인 경우):

    1. 인수를 n으로 설정합니다.

    2. deltan 곱한 허용된 값 단계로 설정합니다.

    3. stepDown() 메서드가 호출된 경우 delta를 부호로 만듭니다.

    4. valuedelta에 더한 값으로 설정합니다.

  8. 요소에 최소값이 있고, value가 그 최소값보다 작다면, value단계 기본값에서 빼서 value보다 크거나 같은 값 중 최소값으로 설정합니다.

  9. 요소에 최대값이 있고, value가 그 최대값보다 크다면, value단계 기본값에서 빼서 value보다 작거나 같은 값 중 최대값으로 설정합니다.

  10. 만약 호출된 메서드가 stepDown() 메서드이고 valuevalueBeforeStepping보다 크거나, stepUp() 메서드가 호출되었고 valuevalueBeforeStepping보다 작다면, 반환합니다.

    다음 예제에서 stepUp() 메서드를 호출할 때, 해당 요소의 이 변경되지 않도록 보장합니다:

    <input type=number value=1 max=0>
  11. value as stringinput 요소의 type 속성의 현재 상태에 대해 정의된 숫자를 문자열로 변환하는 알고리즘을 실행한 결과로 설정합니다.

  12. 요소의 value as string으로 설정합니다.


list IDL 속성은 현재 추천 소스 요소를 반환해야 하며, 없으면 null을 반환해야 합니다.


HTMLInputElement/showPicker

모든 현재 엔진에서 지원됩니다.

Firefox101+Safari16+Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLInputElement showPicker()HTMLSelectElement showPicker() 메서드의 단계는 다음과 같습니다:

  1. this변경 가능하지 않다면, "InvalidStateError" DOMException을 던집니다.

  2. this관련 설정 객체출처동일 출처가 아니고, thisselect 요소이거나, thistype 속성이 파일 업로드 상태 또는 색상 상태가 아닌 경우, "SecurityError" DOMException을 던집니다.

    파일 업로드색상 입력은 이 확인에서 제외됩니다. 역사적 이유로, 이들의 입력 활성화 동작도 동일한 선택기를 표시하며, 동일 출처 확인을 거치지 않았습니다.

  3. this관련 전역 객체일시적 활성화를 가지고 있지 않다면, "NotAllowedError" DOMException을 던집니다.

  4. thisselect 요소이고 this렌더링 중이 아니라면, "NotSupportedError" DOMException을 던집니다.

  5. 선택기를 표시합니다, 해당 요소가 this인 경우.

input 또는 select 요소 element에 대해 선택기를 표시하려면 다음과 같이 합니다:

  1. element관련 전역 객체일시적 활성화를 가지고 있지 않다면, 반환합니다.

  2. element변경 가능하지 않다면, 반환합니다.

  3. 사용자 활성화 소비element관련 전역 객체에 대해 실행합니다.

  4. elementinput 요소이고 elementtype 속성이 파일 업로드 상태에 있는 경우, 다음 단계를 병렬로 실행합니다:

    1. 선택적으로, 이 알고리즘의 이전 실행이 종료될 때까지 기다립니다.

    2. 사용자에게 파일을 지정하도록 요청하는 프롬프트를 표시합니다. elementmultiple 속성이 설정되지 않은 경우, 하나 이상의 파일이 선택되지 않아야 합니다. 그렇지 않으면 원하는 만큼 선택할 수 있습니다. 파일은 파일 시스템에서 가져올 수도 있고, 사용자 장치에 연결된 카메라로 촬영된 사진 등 즉석에서 생성할 수도 있습니다.

    3. 사용자가 선택을 완료할 때까지 기다립니다.

    4. 사용자가 선택을 변경하지 않고 프롬프트를 닫은 경우, element에 대해 요소 작업을 대기열에 추가하여 cancel이라는 이름의 이벤트를 element에서 발생시키고, bubbles 속성을 true로 초기화합니다.

    5. 그렇지 않으면, element에 대한 파일 선택을 업데이트합니다.

    모든 사용자 인터페이스 사양과 마찬가지로, 사용자 에이전트는 이러한 요구 사항을 해석하는 데 많은 자유를 가집니다. 위 텍스트는 사용자가 프롬프트를 닫거나 선택을 변경한다는 것을 암시합니다. 둘 중 하나만 해당됩니다. 그러나 이러한 가능성을 특정 사용자 인터페이스 요소에 매핑하는 것은 표준에서 명시하지 않습니다. 예를 들어, 사용자 에이전트는 파일을 선택한 후 '취소' 버튼을 클릭하는 것을 선택 항목을 0으로 변경하는 것으로 해석할 수 있으며, 이는 inputchange 이벤트를 발생시킬 수 있습니다. 또는 클릭을 선택을 변경하지 않고 프롬프트를 닫는 것으로 해석할 수 있으며, 이 경우 cancel 이벤트가 발생합니다. 마찬가지로, 동일한 파일을 다시 선택하는 것을 이전에 선택된 것으로 해석할지, 선택 변경으로 해석할지는 사용자 에이전트에 달려 있습니다.

  5. 그렇지 않은 경우, 사용자 에이전트는 요소에 대해 값을 선택하기 위해 관련된 사용자 인터페이스를 표시해야 하며, 사용자가 컨트롤과 상호작용할 때 보통 보여주는 방식으로 표시해야 합니다. (해당 요소에 적용되는 UI가 없다면, 이 단계는 아무런 작업도 하지 않습니다.)

    이러한 사용자 인터페이스가 표시되면, 요소의 type 속성 상태에 대해 명시된 사양의 관련 부분에 나와 있는 요소의 동작에 대한 요구 사항을 준수해야 합니다. (예를 들어, 다양한 섹션에서 문자열의 결과에 대한 제한을 설명합니다.)

    이 단계는 이전에 이 알고리즘에 의해 표시된 다른 선택기를 닫는 것과 같은 부작용을 가질 수 있습니다. (파일 선택기가 닫히면, 이는 위에서 설명한 대로 inputchange 이벤트를 발생시키거나, cancel 이벤트를 발생시킬 수 있습니다.)

    이 문서를 작성하는 시점에서, 일반적인 브라우저 구현은 다음에 대해 이러한 선택기 UI를 표시합니다:

    그러나 이 단계의 의도는 모든 선택기 UI 구현을 트리거하는 것입니다. 예를 들어, 사용자 에이전트가 비밀번호 상태에 대해 비밀번호 선택기 UI를 구현한 경우, 이 메서드는 비밀번호 입력에서 호출될 때 해당 선택기 UI를 표시하는 것이 기대됩니다.

4.10.5.5 공통 이벤트 동작

inputchange 이벤트가 적용될 때 (이는 input 컨트롤 중 버튼type 속성이 숨김 상태인 컨트롤을 제외한 모든 경우에 해당됩니다), 이벤트는 사용자가 컨트롤과 상호작용했음을 나타내기 위해 발생합니다. input 이벤트는 사용자가 컨트롤의 데이터를 수정할 때마다 발생합니다. change 이벤트는 값이 커밋될 때, 또는 컨트롤이 포커스를 잃을 때 발생합니다. 모든 경우에 input 이벤트는 해당 change 이벤트(있는 경우) 전에 발생합니다.

input 요소가 정의된 입력 활성화 동작을 가지는 경우, 이러한 이벤트가 적용될 경우 이벤트를 디스패치하는 규칙은 위에 설명된 type 속성 상태를 정의하는 섹션에 나와 있습니다. (이는 input 컨트롤 중 체크박스 상태, 라디오 버튼 상태, 또는 파일 업로드 상태를 가진 컨트롤의 경우입니다.)

input 요소가 정의된 입력 활성화 동작이 없지만 이러한 이벤트가 적용되며, 사용자 인터페이스가 상호작용적 조작과 명시적 커밋 동작을 포함하는 경우, 사용자가 요소의 을 변경할 때 사용자 에이전트는 요소 작업을 큐에 추가해야 하며, 사용자 상호작용 작업 소스에서 input 요소를 주어진 값으로 이벤트를 발생시켜야 합니다. 이벤트 이름은 input이며, input 요소에서 발생하고, 버블링구성 속성이 true로 초기화된 상태로 발생해야 합니다. 사용자가 변경 사항을 커밋할 때마다 사용자 에이전트는 요소 작업을 큐에 추가해야 하며, 사용자 상호작용 작업 소스에서 input 요소를 주어진 값으로 해당 요소의 사용자 유효성을 true로 설정하고, 이벤트를 발생시켜야 합니다. 이벤트 이름은 change이며, input 요소에서 발생하고, 버블링 속성이 true로 초기화된 상태로 발생해야 합니다.

상호작용적 조작과 커밋 동작이 모두 포함된 사용자 인터페이스의 예로는 포인팅 장치를 사용하여 조작하는 슬라이더 형태의 범위 컨트롤이 있습니다. 사용자가 컨트롤의 손잡이를 끌 때마다 위치가 변경되면 input 이벤트가 발생하고, 사용자가 손잡이를 놓아 특정 값에 커밋할 때만 change 이벤트가 발생합니다.

input 요소가 정의된 입력 활성화 동작이 없지만 이러한 이벤트가 적용되며, 사용자 인터페이스에 중간 조작 없이 명시적인 커밋 동작만 포함된 경우, 사용자가 요소의 을 커밋할 때마다 사용자 에이전트는 요소 작업을 큐에 추가해야 하며, 사용자 상호작용 작업 소스에서 input 요소를 주어진 값으로 먼저 이벤트를 발생시켜야 합니다. 이벤트 이름은 input이며, input 요소에서 발생하고, 버블링구성 속성이 true로 초기화된 상태로 발생합니다. 그 후 이벤트를 발생시켜야 합니다. 이벤트 이름은 change이며, input 요소에서 발생하고, 버블링 속성이 true로 초기화된 상태로 발생합니다.

커밋 동작을 포함하는 사용자 인터페이스의 예로는 색상 휠을 호출하는 단일 버튼으로 구성된 색상 컨트롤이 있습니다. 대화 상자가 닫힐 때만 이 변경되는 경우, 이는 명시적인 커밋 동작이 됩니다. 반면에, 컨트롤을 조작하여 색상이 상호작용적으로 변경되는 경우에는 커밋 동작이 없을 수 있습니다.

커밋 동작을 포함하는 사용자 인터페이스의 또 다른 예로는 텍스트 기반 사용자 입력과 드롭다운 달력에서의 사용자 선택을 모두 허용하는 날짜 컨트롤이 있습니다. 텍스트 입력은 명시적인 커밋 단계가 없을 수 있지만, 드롭다운 달력에서 날짜를 선택한 후 드롭다운을 해제하면 커밋 동작이 됩니다.

input 요소가 정의된 입력 활성화 동작이 없지만 이러한 이벤트가 적용되며, 사용자가 명시적인 커밋 동작 없이 요소의 을 변경하는 경우, 사용자 에이전트는 요소 작업을 큐에 추가해야 하며, 사용자 상호작용 작업 소스에서 input 요소를 주어진 값으로 이벤트를 발생시켜야 합니다. 이벤트 이름은 input이며, input 요소에서 발생하고, 버블링구성 속성이 true로 초기화된 상태로 발생합니다. 해당 change 이벤트(있는 경우)는 컨트롤이 포커스를 잃을 때 발생합니다.

사용자가 요소의 을 변경하는 예로는 텍스트 컨트롤에 입력, 붙여넣기, 해당 컨트롤에서 편집을 실행 취소하는 것이 포함됩니다. 일부 사용자 상호작용은 값 변경을 초래하지 않습니다. 예를 들어, 빈 텍스트 컨트롤에서 "삭제" 키를 누르거나, 컨트롤의 일부 텍스트를 클립보드에서 동일한 텍스트로 대체하는 것입니다.

사용자가 키보드를 사용하여 상호작용하는 동안 포커스된 상태의 슬라이더 형태의 범위 컨트롤은 커밋 단계 없이 사용자가 요소의 을 변경하는 또 다른 예입니다.

작업이 단순히 input 이벤트만 발생시키는 경우, 사용자 에이전트는 적절한 사용자의 상호작용 휴식을 기다린 후 작업을 큐에 추가할 수 있습니다. 예를 들어, 사용자 에이전트는 사용자가 100ms 동안 키를 누르지 않았을 때 이벤트를 발생시켜, 사용자가 멈출 때만 이벤트를 발생시키도록 할 수 있습니다.

사용자 에이전트가 사용자를 대신하여 input 요소의 을 변경해야 하는 경우 (예: 양식 자동 완성 기능의 일부로서), 사용자 에이전트는 요소 작업을 큐에 추가해야 하며, 사용자 상호작용 작업 소스에서 input 요소를 주어진 값으로 먼저 이벤트를 발생시켜야 합니다. 이벤트 이름은 input이며, input 요소에서 발생하고, 버블링구성 속성이 true로 초기화된 상태로 발생합니다. 그 후 이벤트를 발생시켜야 합니다. 이벤트 이름은 change이며, input 요소에서 발생하고, 버블링 속성이 true로 초기화된 상태로 발생해야 합니다.

이러한 이벤트는 스크립트가 폼 컨트롤의 값을 변경한 것에 대해서는 발생하지 않습니다. (이것은 사용자가 컨트롤을 조작하는 것에 응답하여 폼 컨트롤의 값을 업데이트하기 쉽게 하면서 스크립트 자체의 변경 사항을 필터링하여 무한 루프를 방지할 수 있도록 하기 위함입니다.)

이러한 이벤트는 또한 브라우저가 내비게이션 중 상태 복원의 일부로 폼 컨트롤의 값을 변경할 때도 발생하지 않습니다.

4.10.6 button 요소

Element/button

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

HTMLButtonElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
카테고리:
Flow 콘텐츠.
Phrasing 콘텐츠.
인터랙티브 콘텐츠.
목록화 가능, 레이블 가능, 제출 가능, 및 autocapitalize 상속 양식 연관 요소.
Palpable 콘텐츠.
이 요소가 사용될 수 있는 맥락:
Phrasing 콘텐츠가 예상되는 곳.
콘텐츠 모델:
Phrasing 콘텐츠, 하지만 인터랙티브 콘텐츠 후손과 tabindex 속성이 지정된 후손이 없어야 합니다.
text/html에서 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
disabled — 양식 컨트롤이 비활성화되었는지 여부
form — 요소를 양식 요소와 연결합니다.
formactionURL양식 제출에 사용합니다.
formenctypeEntry list 인코딩 타입을 양식 제출에 사용합니다.
formmethod양식 제출에 사용할 방법.
formnovalidate양식 제출을 위한 양식 컨트롤 유효성 검사를 건너뜁니다.
formtarget네비게이블양식 제출에 사용합니다.
name양식 제출form.elements API에서 사용할 요소의 이름.
popovertarget — 팝오버 요소를 토글, 표시 또는 숨기기 위해 타겟팅합니다.
popovertargetaction — 타겟팅된 팝오버 요소가 토글될지, 표시될지, 숨겨질지 나타냅니다.
type — 버튼의 유형.
value양식 제출에 사용할 값.
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLButtonElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute USVString formAction;
  [CEReactions] attribute DOMString formEnctype;
  [CEReactions] attribute DOMString formMethod;
  [CEReactions] attribute boolean formNoValidate;
  [CEReactions] attribute DOMString formTarget;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList labels;
};
HTMLButtonElement includes PopoverInvokerElement;

button 요소는 콘텐츠에 의해 라벨링된 버튼을 나타냅니다.

이 요소는 버튼입니다.

type 속성은 버튼이 활성화될 때의 동작을 제어합니다. 이 속성은 다음과 같은 키워드와 상태를 가진 열거된 속성입니다:

키워드 상태 간단한 설명
submit 제출 버튼 양식을 제출합니다.
reset 리셋 버튼 양식을 초기화합니다.
button 버튼 아무 작업도 하지 않습니다.

속성의 누락된 값 기본값잘못된 값 기본값은 모두 제출 버튼 상태입니다.

type 속성이 제출 버튼 상태인 경우, 이 요소는 제출 버튼입니다.

제약 조건 유효성 검사: type 속성이 리셋 버튼 상태이거나 버튼 상태인 경우, 이 요소는 제약 조건 유효성 검사에서 제외됩니다.

button 요소의 element활성화 동작event에 대해 다음과 같습니다:

  1. element비활성화된 경우, 아무 작업도 하지 않습니다.

  2. element노드 문서완전히 활성화되지 않은 경우, 아무 작업도 하지 않습니다.

  3. element양식 소유자를 가지고 있는 경우, elementtype 속성의 상태에 따라 다음을 수행합니다:

    제출 버튼

    제출 element양식 소유자사용자 참여event사용자 네비게이션 참여로 설정된 상태에서 제출합니다.

    리셋 버튼

    초기화 element양식 소유자.

    버튼

    아무 작업도 하지 않습니다.

  4. element에 대해 팝오버 타겟 속성 활성화 동작을 실행합니다.

form 속성은 button 요소를 양식 소유자와 명시적으로 연결하는 데 사용됩니다. name 속성은 요소의 이름을 나타냅니다. disabled 속성은 컨트롤을 비활성화하고 그 값을 제출하지 않도록 만드는 데 사용됩니다. formaction, formenctype, formmethod, formnovalidate, 및 formtarget 속성은 양식 제출을 위한 속성입니다.

formnovalidate 속성은 제약 조건 유효성 검사를 트리거하지 않는 제출 버튼을 만드는 데 사용할 수 있습니다.

formaction, formenctype, formmethod, formnovalidate, 및 formtarget은 요소의 type 속성이 제출 버튼 상태에 있지 않은 경우 지정할 수 없습니다.

value 속성은 양식 제출을 위해 요소의 값을 제공합니다. 요소의 value 속성의 값이거나, 값이 없는 경우 빈 문자열입니다.

버튼(및 그 값)은 버튼 자체가 양식 제출을 시작한 경우에만 양식 제출에 포함됩니다.


value IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

type IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

willValidate, validity, 및 validationMessage IDL 속성과 checkValidity(), reportValidity(), 및 setCustomValidity() 메서드는 제약 조건 유효성 검사 API의 일부입니다. labels IDL 속성은 요소의 레이블 목록을 제공합니다. disabled, form, 및 name IDL 속성은 요소의 양식 API의 일부입니다.

다음 버튼은 "힌트 표시"로 라벨링되어 있으며 활성화될 때 대화 상자를 표시합니다:

<button type=button
    onclick="alert('이 15-20분짜리 곡은 조지 거슈윈이 작곡했습니다.')">
 Show hint
</button>

4.10.7 select 요소

Element/select

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

HTMLSelectElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet Explorer1+
Firefox Android4+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
카테고리:
Flow 콘텐츠.
Phrasing 콘텐츠.
인터랙티브 콘텐츠.
목록화 가능, 레이블 가능, 제출 가능, 리셋 가능, 및 autocapitalize 상속 양식 연관 요소.
Palpable 콘텐츠.
이 요소가 사용될 수 있는 맥락:
Phrasing 콘텐츠가 예상되는 곳.
콘텐츠 모델:
0개 이상의 option, optgroup, hr, 및 스크립트 지원 요소들.
text/html에서 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
autocomplete — 양식 자동 완성 기능에 대한 힌트.
disabled — 양식 컨트롤이 비활성화되었는지 여부.
form — 요소를 양식 요소와 연결합니다.
multiple — 여러 값을 허용할지 여부.
name양식 제출에 사용할 요소의 이름과 form.elements API에서 사용할 이름.
required양식 제출을 위해 컨트롤이 필수인지 여부.
size — 컨트롤의 크기.
접근성 고려사항:
요소에 multiple 속성이나 size 속성이 값 1 이상으로 존재하는 경우: 작성자용; 구현자용.
그 외의 경우: 작성자용; 구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLSelectElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute boolean multiple;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute boolean required;
  [CEReactions] attribute unsigned long size;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLOptionsCollection options;
  [CEReactions] attribute unsigned long length;
  getter HTMLOptionElement? item(unsigned long index);
  HTMLOptionElement? namedItem(DOMString name);
  [CEReactions] undefined add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  [CEReactions] undefined remove(); // ChildNode overload
  [CEReactions] undefined remove(long index);
  [CEReactions] setter undefined (unsigned long index, HTMLOptionElement? option);

  [SameObject] readonly attribute HTMLCollection selectedOptions;
  attribute long selectedIndex;
  attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  undefined showPicker();

  readonly attribute NodeList labels;
};

select 요소는 옵션 집합 중에서 선택할 수 있는 컨트롤을 나타냅니다.

Attributes/multiple

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

multiple 속성은 boolean 속성입니다. 속성이 존재하는 경우 select 요소는 옵션 목록에서 0개 이상의 옵션을 선택할 수 있는 컨트롤을 나타냅니다. 속성이 없으면 select 요소는 옵션 목록에서 단일 옵션을 선택할 수 있는 컨트롤을 나타냅니다.

Attributes/size

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

size 속성은 사용자에게 표시할 옵션의 수를 제공합니다. size 속성이 지정된 경우, 이 속성은 유효한 비음수 정수이어야 하며 값이 0보다 커야 합니다.

표시 크기select 요소의 size 속성의 값에 비음수 정수 구문 분석 규칙을 적용한 결과이며, 속성이 존재하고 파싱이 성공한 경우입니다. 해당 규칙을 적용해도 속성의 값이 성공적으로 파싱되지 않거나 size 속성이 없는 경우, 요소의 표시 크기는 요소의 multiple 속성이 존재하는 경우 4, 그렇지 않으면 1입니다.

옵션 목록select 요소의 모든 option 자식 요소와 select 요소의 모든 optgroup 자식 요소의 모든 option 자식 요소들로 구성되며, 트리 순서에 따릅니다.

Attributes/required

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5.1+Chrome10+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

required 속성은 boolean 속성입니다. 이 속성이 지정된 경우 사용자는 양식을 제출하기 전에 값을 선택해야 합니다.

select 요소에 required 속성이 지정되어 있고, multiple 속성이 지정되어 있지 않으며, 표시 크기가 1이고, select 요소의 옵션 목록에서 첫 번째 option 요소의 이 빈 문자열이고, 해당 option 요소의 부모 노드가 select 요소(그리고 optgroup 요소가 아님)인 경우, 해당 optionselect 요소의 플레이스홀더 라벨 옵션입니다.

select 요소에 required 속성이 지정되어 있고, multiple 속성이 지정되어 있지 않으며, 표시 크기가 1인 경우, select 요소는 플레이스홀더 라벨 옵션을 가져야 합니다.

위 문단에서 언급한 요구 사항은 select 요소에 값이 1보다 큰 size 속성이 없는 경우에만 적용될 수 있습니다.

제약 조건 유효성 검사: 요소에 required 속성이 지정되어 있고, select 요소의 옵션 목록에 있는 option 요소 중 어떤 것도 선택됨이 true로 설정되지 않았거나, select 요소의 옵션 목록에서 선택됨이 true로 설정된 유일한 option 요소가 플레이스홀더 라벨 옵션인 경우, 해당 요소는 누락됨을 겪고 있습니다.

multiple 속성이 없고, 요소가 비활성화된 상태가 아니라면, 사용자 에이전트는 사용자가 해당 option 요소를 옵션 목록에서 선택하도록 허용해야 합니다. 이때 해당 옵션이 비활성화되지 않은 상태여야 합니다. 사용자가 이 option 요소를 클릭하거나 값을 변경한 후 요소에서 포커스를 잃거나, 메뉴 명령을 사용하거나, 기타 다른 메커니즘을 통해 선택할 경우, 해당 선택 상태를 true로 설정하고, 더러움 상태로 설정한 후, 선택 업데이트 알림을 전송해야 합니다.

multiple 속성이 없는 경우, option 요소가 select 요소의 옵션 목록에 추가되거나, 해당 선택 상태가 true로 설정될 때, 사용자 에이전트는 해당 목록의 다른 모든 option 요소의 선택 상태를 false로 설정해야 합니다.

multiple 속성이 없고, 요소의 디스플레이 크기가 1보다 크다면, 사용자 에이전트는 사용자가 선택 상태가 true인 option을 선택 해제하도록 허용해야 합니다. 이 요청이 사용자 에이전트에 전달된 후, 관련 사용자 상호작용 이벤트가 큐에 추가되기 전에 (예: click 이벤트 전에), 사용자 에이전트는 해당 선택 상태를 false로 설정하고, 더러움 상태로 설정한 후, 선택 업데이트 알림을 전송해야 합니다.

주어진 select 요소 element에 대해 선택 상태 설정 알고리즘은 다음 단계를 실행합니다:

  1. elementmultiple 속성이 없고, element표시 크기가 1이며, element옵션 목록에 있는 option 요소들이 선택됨이 true로 설정되어 있지 않은 경우, 트리 순서에서 비활성화되지 않은 첫 번째 option 요소의 선택됨을 true로 설정하고, 종료합니다.

  2. 만약 elementmultiple 속성이 없고, element옵션 목록에 있는 두 개 이상의 option 요소가 선택 상태가 true로 설정된 경우, 옵션 목록에서 마지막 option 요소를 제외한 모든 요소의 선택 상태트리 순서에 따라 false로 설정합니다.

option 요소의 HTML 요소 삽입 단계insertedNode가 주어졌을 때 다음과 같습니다:

  1. 만약 insertedNode의 부모가 select 요소이거나, insertedNode의 부모가 optgroup 요소이며, 그 부모가 select 요소인 경우, 해당 select 요소의 선택 상태 설정 알고리즘을 실행합니다.

옵션 HTML 요소 제거 단계removedNodeoldParent가 주어졌을 때 다음과 같습니다:

  1. oldParentselect 요소이거나, oldParentoptgroup 요소이고 그 부모가 select 요소인 경우, 해당 select 요소의 선택성 설정 알고리즘을 실행합니다.

optgroup HTML 요소 제거 단계removedNodeoldParent가 주어졌을 때 다음과 같습니다:

  1. oldParentselect 요소이고 removedNodeoption 자식이 있는 경우, oldParent선택성 설정 알고리즘을 실행합니다.

옵션 요소가 옵션 목록에서 재설정을 요청하면, 해당 select 요소의 선택성 설정 알고리즘을 실행합니다.

multiple 속성이 있고, 해당 요소가 비활성화되지 않은 경우, 사용자 에이전트는 사용자가 선택성 전환을 허용해야 합니다. 이때 옵션 요소의 선택성비활성화되지 않은 경우에만 가능합니다. 이러한 요소가 전환되면(클릭, 메뉴 명령, 또는 기타 메커니즘을 통해), 관련 사용자 상호작용 이벤트가 대기열에 추가되기 전에(예: 관련 클릭 이벤트 전에), 선택성이 변경되어야 하며(true에서 false로 또는 그 반대), 오염도가 true로 설정되어야 하며, 사용자 에이전트는 select 업데이트 알림을 보내야 합니다.

사용자 에이전트가 select 업데이트 알림을 보내야 할 때, 요소 작업 대기열에 추가하고, 사용자 상호작용 작업 소스에서 주어진 select 요소에 대해 다음 단계를 실행합니다:

  1. select 요소의 사용자 유효성을 true로 설정합니다.
  2. 이벤트input이라는 이름으로 select 요소에서 발생시키고, 버블링구성 속성을 true로 초기화합니다.
  3. 이벤트change이라는 이름으로 select 요소에서 발생시키고, 버블링 속성을 true로 초기화합니다.

reset 알고리즘select 요소 selectElement에 대해 다음과 같습니다:

  1. selectElement사용자 유효성을 false로 설정합니다.

  2. selectElement옵션 목록에 있는 optionElement에 대해 다음을 수행합니다:

    1. 만약 optionElementselected 속성을 가지고 있다면, optionElement선택 상태를 true로 설정하고, 그렇지 않다면 false로 설정합니다.

    2. optionElement더러움 상태를 false로 설정합니다.

  3. selectElement에 대해 선택 상태 설정 알고리즘을 실행합니다.

form 속성은 select 요소를 해당 form 소유자와 명시적으로 연관시키는 데 사용됩니다. name 속성은 요소의 이름을 나타냅니다. disabled 속성은 컨트롤을 비활성화하고 해당 값을 제출하지 않도록 합니다. autocomplete 속성은 사용자 에이전트가 자동 완성 동작을 제공하는 방법을 제어합니다.

select 요소가 비활성화되지 않은 경우, 해당 요소는 mutable합니다.

select.type

HTMLSelectElement/type

모든 현재 엔진에서 지원.

Firefox1+ Safari3+ Chrome1+
Opera2+ Edge79+
Edge (Legacy)12+ Internet Explorer1+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

요소에 multiple 속성이 있는 경우 "select-multiple"를 반환하고, 그렇지 않은 경우 "select-one"를 반환합니다.

select.options

HTMLSelectElement/options

모든 현재 엔진에서 지원.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

선택된 옵션 목록HTMLOptionsCollection을 반환합니다.

select.length [ = value ]

옵션 목록에 있는 요소의 수를 반환합니다.

더 작은 수로 설정하면 옵션 요소의 수가 줄어들고, select에 빈 옵션 요소가 추가됩니다.

element = select.item(index)

HTMLSelectElement/item

모든 현재 엔진에서 지원.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+
select[index]

선택된 옵션 목록에서 인덱스 index에 해당하는 항목을 반환합니다. 항목은 트리 순서에 따라 정렬됩니다.

element = select.namedItem(name)

HTMLSelectElement/namedItem

모든 현재 엔진에서 지원.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer6+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

선택된 옵션 목록에서 지정된 name과 일치하는 첫 번째 항목을 반환합니다. 일치하는 항목이 없으면 null을 반환합니다.

select.add(element [, before ])

HTMLSelectElement/add

모든 현재 엔진에서 지원.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

before로 지정된 노드 앞에 element를 삽입합니다.

before 인수가 생략되거나, null이거나, 범위를 벗어난 경우 element가 목록의 끝에 추가됩니다.

이 메서드는 element가 삽입할 요소의 조상인 경우 "HierarchyRequestError" DOMException을 발생시킵니다.

select.selectedOptions

HTMLSelectElement/selectedOptions

모든 현재 엔진에서 지원.

Firefox26+ Safari6+ Chrome19+
Opera9+ Edge79+
Edge (Legacy)12+ Internet Explorer지원 안 됨
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

선택된 옵션 목록의 HTMLCollection을 반환합니다.

select.selectedIndex [ = value ]

HTMLSelectElement/selectedIndex

모든 현재 엔진에서 지원.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet?

선택된 첫 번째 항목의 인덱스를 반환하거나, 선택된 항목이 없으면 -1을 반환합니다.

select.value [ = value ]

선택된 첫 번째 항목의 을 반환하거나, 선택된 항목이 없으면 빈 문자열을 반환합니다.

select.showPicker()

select에 대한 해당 선택 UI를 표시하여 사용자가 값을 선택할 수 있도록 합니다.

select변경 가능하지 않은 경우 "InvalidStateError" DOMException이 발생합니다.

일시적 사용자 활성화 없이 호출된 경우 "NotAllowedError" DOMException이 발생합니다.

select가 교차 출처 iframe 내부에 있는 경우 "SecurityError" DOMException이 발생합니다.

select렌더링되지 않는 경우 "NotSupportedError" DOMException이 발생합니다.

type IDL 속성은 가져올 때 multiple 속성이 없으면 문자열 "select-one"을 반환하고, multiple 속성이 있으면 문자열 "select-multiple"을 반환해야 합니다.

options IDL 속성은 HTMLOptionsCollectionselect 노드에 근거하여 반환해야 하며, 이 노드의 필터는 옵션 목록의 요소와 일치합니다.

options 컬렉션은 또한 HTMLSelectElement 객체에 반영됩니다. 지원되는 속성 인덱스는 해당 순간 options 속성에 의해 반환된 객체가 지원하는 인덱스입니다.

length IDL 속성은 컬렉션에 의해 표현된 노드의 수를 반환해야 합니다. 설정 시, 동일한 이름의 속성처럼 options 컬렉션에서 작동해야 합니다.

item(index) 메서드는 동일한 이름의 메서드options 컬렉션에서 동일한 인수로 호출될 때 반환된 값을 반환해야 합니다.

namedItem(name) 메서드는 동일한 이름의 메서드options 컬렉션에서 동일한 인수로 호출될 때 반환된 값을 반환해야 합니다.

사용자가 새로운 인덱스 속성의 값을 설정하거나 기존 인덱스 속성의 값을 설정하려고 할 때, 대신 select 요소의 options 컬렉션에 대해 해당 알고리즘을 실행해야 합니다.

유사하게, add(element, before) 메서드는 동일한 options 컬렉션에 있는 동일한 이름의 메서드처럼 작동해야 합니다.

HTMLSelectElement/remove

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

remove() 메서드는 인수를 가진 경우 해당 options 컬렉션의 동일한 이름의 메서드처럼 작동해야 하며, 인수가 없는 경우 ChildNode 인터페이스에서 동일한 이름의 메서드처럼 작동해야 합니다. 이 인터페이스는 HTMLSelectElement 상위 인터페이스인 Element에 의해 구현됩니다.

selectedOptions IDL 속성은 HTMLCollectionselect 노드에 근거하여 반환해야 하며, 이 노드의 필터는 옵션 목록선택됨으로 설정된 요소와 일치합니다.

selectedIndex IDL 속성은 가져올 때 옵션의 인덱스를 반환해야 합니다. 이 옵션은 옵션 목록트리 순서에 따라 첫 번째 옵션 요소에서 선택됨으로 설정된 경우에 해당됩니다. 하나도 없으면 -1을 반환해야 합니다.

설정 시, selectedIndex 속성은 모든 옵션 요소의 선택됨을 false로 설정한 다음, 옵션 목록에서 주어진 새로운 값에 해당하는 옵션 요소를 true로 설정해야 하며, 이때 해당 요소의 변경됨 상태도 true로 설정해야 합니다.

이렇게 하면 선택됨으로 설정된 요소가 없을 수 있습니다. 이는 select 요소에 multiple 속성이 없고, 표시 크기가 1인 경우에도 해당됩니다.

value IDL 속성은 가져올 때 을 반환해야 합니다. 이 값은 옵션 목록트리 순서에 따라 첫 번째 옵션 요소에서 선택됨으로 설정된 경우에 해당됩니다. 그렇지 않으면 빈 문자열을 반환해야 합니다.

설정 시, value 속성은 모든 옵션 요소의 선택됨을 false로 설정한 다음, 주어진 새로운 값과 일치하는 옵션 목록의 첫 번째 옵션 요소를 true로 설정해야 하며, 이때 해당 요소의 변경됨 상태도 true로 설정해야 합니다.

이렇게 하면 선택됨으로 설정된 요소가 없을 수 있습니다. 이는 select 요소에 multiple 속성이 없고, 표시 크기가 1인 경우에도 해당됩니다.

multiple, required, 및 size IDL 속성은 각각 동일한 이름의 콘텐츠 속성을 반영해야 합니다. size IDL 속성의 기본 값은 0입니다.

역사적인 이유로, size IDL 속성의 기본 값은 실제 사용된 크기를 반환하지 않습니다. size 콘텐츠 속성이 없는 경우, 이 크기는 multiple 속성의 존재 여부에 따라 1 또는 4가 됩니다.

willValidate, validity, 및 validationMessage IDL 속성들과, checkValidity(), reportValidity(), 및 setCustomValidity() 메서드는 제약 조건 유효성 검사 API의 일부입니다. labels IDL 속성은 요소의 label 목록을 제공합니다. disabled, form, 및 name IDL 속성은 요소의 양식 API의 일부입니다.

다음 예제는 select 요소가 사용자가 선택할 수 있는 옵션 집합을 제공하는 데 어떻게 사용될 수 있는지를 보여줍니다. 기본 옵션은 미리 선택되어 있습니다.

<p>
<label for="unittype">단위 유형 선택:</label>
<select id="unittype" name="unittype">
<option value="1"> Miner </option>
<option value="2"> Puffer </option>
<option value="3" selected> Snipey </option>
<option value="4"> Max </option>
<option value="5"> Firebot </option>
</select>
</p>

기본 옵션이 없을 때는 플레이스홀더를 사용할 수 있습니다:

<select name="unittype" required>
<option value=""> 단위 유형 선택 </option>
<option value="1"> Miner </option>
<option value="2"> Puffer </option>
<option value="3"> Snipey </option> 
<option value="4"> Max </option>
<option value="5"> Firebot </option>
</select>

여기서 사용자는 여러 옵션 중에서 원하는 만큼 선택할 수 있습니다. 기본적으로 다섯 가지 옵션이 모두 선택되어 있습니다.

<p>
<label for="allowedunits">이 지도에서 활성화할 단위 유형 선택:</label>
<select id="allowedunits" name="allowedunits" multiple>
<option value="1" selected> Miner </option>
<option value="2" selected> Puffer </option>
<option value="3" selected> Snipey </option>
<option value="4" selected> Max </option>
<option value="5" selected> Firebot </option>
</select>
</p>

때로는 사용자가 하나 이상의 항목을 선택해야 합니다. 이 예제는 그러한 인터페이스를 보여줍니다.

<label>
이 Act II 믹스 테이프에 포함할 노래를 선택하세요:
<select multiple required name="act2">
<option value="s1">It Sucks to Be Me (Reprise)
<option value="s2">There is Life Outside Your Apartment
<option value="s3">The More You Ruv Someone
<option value="s4">Schadenfreude
<option value="s5">I Wish I Could Go Back to College
<option value="s6">The Money Song
<option value="s7">School for Monsters
<option value="s8">The Money Song (Reprise)
<option value="s9">There's a Fine, Fine Line (Reprise)
<option value="s10">What Do You Do With a B.A. in English? (Reprise)
<option value="s11">For Now
</select>
</label>

때때로 구분자가 유용할 수 있습니다:

<label>
다음에 재생할 노래 선택:
<select required name="next">
<option value="sr">랜덤
<hr>
<option value="s1">It Sucks to Be Me (Reprise)
<option value="s2">There is Life Outside Your Apartment
…

4.10.8 datalist 요소

Element/datalist

Firefox🔰 4+Safari12.1+Chrome20+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android🔰 79+Safari iOS?Chrome Android33+WebView Android?Samsung Internet?Opera Android?

HTMLDataListElement

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari12.1+Chrome20+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android12.1+
범주:
플로우 콘텐츠.
구문 콘텐츠.
이 요소가 사용될 수 있는 맥락:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
다음 중 하나: 구문 콘텐츠.
또는: 하나 이상의 option 요소 및 스크립트 지원 요소.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLDataListElement : HTMLElement {
  [HTMLConstructor] constructor();

  [SameObject] readonly attribute HTMLCollection options;
};

datalist 요소는 다른 컨트롤을 위한 사전 정의된 옵션을 나타내는 option 요소 집합을 나타냅니다. 렌더링에서 datalist 요소는 아무 것도 나타내지 않으며, 자식 요소와 함께 숨겨져야 합니다.

datalist 요소는 두 가지 방식으로 사용할 수 있습니다. 가장 간단한 경우, datalist 요소에는 option 자식 요소만 있습니다.

<label>
동물:
<input name=animal list=animals>
<datalist id=animals>
<option value="Cat">
<option value="Dog">
</datalist>
</label>

좀 더 정교한 경우, datalist 요소에 datalist를 지원하지 않는 하위 클라이언트를 위해 표시할 콘텐츠를 넣을 수 있습니다. 이 경우, option 요소는 select 요소 안에 제공됩니다.

<label>
동물:
<input name=animal list=animals>
</label>
<datalist id=animals>
<label>
또는 목록에서 선택:
<select name=animal>
<option value="">
<option>Cat
<option>Dog
</select>
</label>
</datalist>

datalist 요소는 input 요소의 list 속성을 사용하여 input 요소에 연결됩니다.

datalist 요소의 자손인 option 요소 중 비활성화되지 않았고, 이 빈 문자열이 아닌 문자열인 각 요소는 제안을 나타냅니다. 각 제안에는 레이블이 있습니다.

datalist.options

HTMLCollection을 반환하며, 이 컬렉션은 option 요소의 집합입니다.

options IDL 속성은 HTMLCollection을 반환해야 하며, 이 컬렉션은 datalist 노드에 근거하고, option 요소와 일치하는 필터를 가집니다.

제약 조건 유효성 검사: 요소에 datalist 요소의 상위 요소가 있는 경우, 제약 조건 유효성 검사에서 제외됩니다.

4.10.9 optgroup 요소

Element/optgroup

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLOptGroupElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
범주:
없음.
이 요소가 사용될 수 있는 맥락:
select 요소의 자식 요소로서.
콘텐츠 모델:
0개 이상의 option스크립트 지원 요소.
text/html에서 태그 생략:
optgroup 요소의 종료 태그optgroup 요소가 바로 뒤따르거나, hr 요소가 바로 뒤따르거나, 부모 요소에 더 이상 콘텐츠가 없는 경우 생략할 수 있습니다.
콘텐츠 속성:
전역 속성
disabled — 폼 컨트롤이 비활성화되었는지 여부
label — 사용자에게 표시되는 레이블
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLOptGroupElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  [CEReactions] attribute DOMString label;
};

optgroup 요소는 공통 레이블을 가진 option 요소 그룹을 나타냅니다.

요소의 option 요소 그룹은 optgroup 요소의 자식인 option 요소로 구성됩니다.

select 요소에서 option 요소를 표시할 때, 사용자 에이전트는 해당 그룹의 option 요소를 서로 관련 있고 다른 option 요소와는 별도로 표시해야 합니다.

속성/disabled

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

disabled 속성은 boolean 속성이며, 그룹 전체를 비활성화하는 데 사용할 수 있습니다.

label 속성은 필수입니다. 이 속성의 값은 사용자 인터페이스의 그룹 이름을 지정합니다. 사용자 에이전트는 select 요소 내에서 option 요소 그룹을 레이블링할 때 이 속성의 값을 사용해야 합니다.

disabledlabel 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다.

optgroup 요소를 선택할 방법은 없습니다. 오직 option 요소만 선택할 수 있습니다. optgroup 요소는 단지 option 요소 그룹에 대한 레이블만 제공합니다.

다음 코드는 세 가지 강의 중 일부 수업을 드롭다운 위젯에서 선택할 수 있도록 하는 방법을 보여줍니다:

<form action="courseselector.dll" method="get">
<p>어느 강의를 듣고 싶으신가요?
<p><label>강의:
<select name="c">
<optgroup label="8.01 물리학 I: 고전 역학">
<option value="8.01.1">강의 01: 10의 거듭제곱
<option value="8.01.2">강의 02: 1차원 운동학
<option value="8.01.3">강의 03: 벡터
<optgroup label="8.02 전기 및 자기">
<option value="8.02.1">강의 01: 우리의 세계를 무엇이 유지하는가?
<option value="8.02.2">강의 02: 전기장
<option value="8.02.3">강의 03: 전기 플럭스
<optgroup label="8.03 물리학 III: 진동 및 파동">
<option value="8.03.1">강의 01: 주기적 현상
<option value="8.03.2">강의 02: 비트
<option value="8.03.3">강의 03: 감쇠와 함께 강제 진동
</select>
</label>
<p><input type=submit value="▶ 재생">
</form>

4.10.10 option 요소

Element/option

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLOptionElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
없음.
이 요소를 사용할 수 있는 문맥:
select 요소의 자식 요소로 사용.
datalist 요소의 자식 요소로 사용.
optgroup 요소의 자식 요소로 사용.
콘텐츠 모델:
이 요소에 label 속성과 value 속성이 있는 경우: 아무것도 없음.
이 요소에 label 속성이 있지만 value 속성이 없는 경우: 텍스트.
이 요소에 label 속성이 없고 datalist 요소의 자식이 아닌 경우: 텍스트 (요소 간 공백 제외).
이 요소에 label 속성이 없고 datalist 요소의 자식인 경우: 텍스트.
text/html에서의 태그 생략:
태그 생략이 가능합니다.
콘텐츠 속성:
전역 속성
disabled — 폼 컨트롤이 비활성화되었는지 여부
label — 사용자에게 표시되는 레이블
selected — 기본적으로 선택되었는지 여부
value폼 제출 시 사용될 값
접근성 고려사항:
작성자를 위한 정보.
구현자를 위한 정보.
DOM 인터페이스:
[Exposed=Window,
LegacyFactoryFunction=Option(optional DOMString text = "", optional DOMString value, optional boolean defaultSelected = false, optional boolean selected = false)]
interface HTMLOptionElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString label;
  [CEReactions] attribute boolean defaultSelected;
  attribute boolean selected;
  [CEReactions] attribute DOMString value;

  [CEReactions] attribute DOMString text;
  readonly attribute long index;
};

option 요소는 select 요소의 옵션을 나타내거나, datalist 요소에서 제안 목록의 일부로 사용됩니다.

일부 상황에서 select 요소의 정의에 설명된 대로, option 요소는 select 요소의 플레이스홀더 레이블 옵션이 될 수 있습니다. 플레이스홀더 레이블 옵션은 실제 옵션을 나타내는 것이 아니라, select 컨트롤에 대한 레이블을 나타냅니다.

Attributes/disabled

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

disabled 속성은 불리언 속성입니다. option 요소는 disabled 속성이 있거나, optgroup 요소의 자식이며 그 요소에 disabled 속성이 있을 때 비활성화됩니다.

option 요소가 비활성화된 경우, 클릭 이벤트가 대기 중이거나 사용자 상호작용 태스크 소스에서 해당 요소로 전송되지 않도록 해야 합니다.

label 속성은 요소에 대한 레이블을 제공합니다. option 요소의 레이블label 콘텐츠 속성의 값이며, 만약 값이 비어 있지 않다면 그 값을 사용하고, 그렇지 않으면 요소의 text IDL 속성의 값을 사용합니다.

label 콘텐츠 속성이 지정된 경우, 그 값은 비어 있지 않아야 합니다.

value 속성은 요소에 대한 값을 제공합니다. option 요소의 value 콘텐츠 속성의 값이며, 만약 값이 없다면 요소의 text IDL 속성의 값을 사용합니다.

selected 속성은 불리언 속성입니다. 이 속성은 요소의 기본 선택 상태를 나타냅니다.

더티 상태option 요소의 불리언 상태로, 초기에는 false입니다. 이 상태는 selected 콘텐츠 속성을 추가하거나 제거할 때 어떤 영향을 미칠지를 제어합니다.

선택 상태option 요소의 불리언 상태로, 초기에는 false입니다. 별도로 명시되지 않는 한, 요소가 생성될 때 이 상태는 selected 속성이 있는 경우 true로 설정됩니다. option 요소의 selected 속성이 추가될 때, 만약 요소의 더티 상태가 false라면 선택 상태는 true로 설정되어야 합니다. option 요소의 selected 속성이 제거될 때, 만약 더티 상태가 false라면 선택 상태는 false로 설정되어야 합니다.

Option() 생성자는 세 개 이하의 인수로 호출될 때, 세 번째 인수가 true여도 선택 상태를 항상 false로 재설정합니다. 네 번째 인수는 생성자를 사용할 때 선택 상태를 명시적으로 설정하는 데 사용할 수 있습니다.

select 요소에 multiple 속성이 지정되지 않은 경우, 그 요소의 하위 요소 중 option 요소는 하나만 selected 속성이 설정될 수 있습니다.

option 요소의 인덱스는 같은 옵션 목록에 있는 앞에 위치한 다른 option 요소의 개수입니다. 만약 option 요소가 옵션 목록에 속하지 않는다면, 그 요소의 인덱스는 0입니다.

option.selected

요소가 선택된 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

요소의 현재 상태를 덮어쓰도록 설정할 수 있습니다.

option.index

요소의 select 요소의 options 목록에서 인덱스를 반환합니다.

option.form

요소의 form 요소를 반환하며, 그렇지 않으면 null을 반환합니다.

option.text

textContent와 동일하지만, 공백이 압축되고 script 요소는 생략됩니다.

option = new Option([ text [, value [, defaultSelected [, selected ] ] ] ])

새로운 option 요소를 반환합니다.

text 인수는 요소의 내용을 설정합니다.

value 인수는 value 속성을 설정합니다.

defaultSelected 인수는 selected 속성을 설정합니다.

selected 인수는 요소가 선택되었는지 여부를 설정합니다. 이 인수가 생략되면, defaultSelected 인수가 true여도 요소는 선택되지 않습니다.

disabled IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다. defaultSelected IDL 속성은 selected 콘텐츠 속성을 반영해야 합니다.

label IDL 속성은 가져올 때, label 콘텐츠 속성이 있으면 그 속성의 값을 반환해야 하며, 그렇지 않으면 요소의 라벨을 반환해야 합니다. 설정할 때는 요소의 label 콘텐츠 속성이 새 값으로 설정되어야 합니다.

value IDL 속성은 가져올 때 요소의 을 반환해야 합니다. 설정할 때는 요소의 value 콘텐츠 속성이 새 값으로 설정되어야 합니다.

selected IDL 속성은 가져올 때 요소의 선택 상태가 true이면 true를 반환하고, 그렇지 않으면 false를 반환해야 합니다. 설정할 때는 요소의 선택 상태를 새 값으로 설정하고, dirtiness를 true로 설정한 다음, 요소가 재설정을 요청하도록 해야 합니다.

index IDL 속성은 요소의 인덱스를 반환해야 합니다.

text IDL 속성은 가져올 때, ASCII 공백 제거 및 압축의 결과를 반환해야 합니다. 이는 모든 data의 연결로 구성된 것으로, Text 노드 자손을 option 요소의 트리 순서에서 제외하고, 스크립트 또는 SVG 스크립트 요소가 아닌 요소만 포함됩니다.

text 속성의 설정자는 이 요소 내에서 주어진 값으로 문자열을 모두 교체해야 합니다.

form IDL 속성의 동작은 option 요소가 select 요소 안에 있는지 여부에 따라 달라집니다. option 요소의 부모가 select 요소이거나, 부모가 optgroup 요소이고 그 optgroup 요소의 부모가 select 요소인 경우, form IDL 속성은 해당 select 요소의 form IDL 속성과 동일한 값을 반환해야 합니다. 그렇지 않으면 null을 반환해야 합니다.

레거시 팩토리 함수는 HTMLOptionElement 객체를 생성하기 위해 제공되며, DOM의 createElement()와 같은 팩토리 메서드 외에도 사용할 수 있습니다: Option(text, value, defaultSelected, selected). 이 레거시 팩토리 함수가 호출되면 다음 단계를 수행해야 합니다:

  1. document 현재 글로벌 객체 관련 Document로 설정합니다.

  2. optiondocument optionHTML 네임스페이스를 사용하여 요소 생성의 결과로 설정합니다.

  3. text가 빈 문자열이 아니면, option에 새 Text 노드를 추가하고, 그 데이터는 text로 설정합니다.

  4. value가 주어지면, option에 대해 "value"와 value를 사용하여 속성 값을 설정합니다.

  5. defaultSelected가 true이면, option에 대해 "selected"와 빈 문자열을 사용하여 속성 값을 설정합니다.

  6. selected가 true이면, optionselectedness를 true로 설정하고, 그렇지 않으면 selectedness를 false로 설정합니다 (defaultSelected가 true이더라도).

  7. option를 반환합니다.

4.10.11 textarea 요소

Element/textarea

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTextAreaElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
범주:
Flow content.
Phrasing content.
Interactive content.
Listed, labelable, submittable, resettable, autocapitalize-inheriting form-associated element.
Palpable content.
이 요소가 사용될 수 있는 맥락:
Phrasing content이 예상되는 곳.
내용 모델:
텍스트.
text/html에서의 태그 생략:
둘 중 어느 태그도 생략할 수 없습니다.
내용 속성:
Global 속성
autocomplete — 폼 자동 완성 기능을 위한 힌트
cols — 줄당 최대 문자 수
dirname — 폼 제출 시 요소의 방향성을 보내는 데 사용할 폼 제어의 이름
disabled — 폼 제어가 비활성화되었는지 여부
form — 요소를 form 요소와 연결
maxlength — 값의 최대 길이
minlength — 값의 최소 길이
name — 폼 제출 시 사용하기 위해 요소의 이름 또는 form.elements API 내에서 사용
placeholder — 폼 제어 내에 배치될 사용자에게 보이는 라벨
readonly — 사용자가 값을 편집할 수 있는지 여부
required — 폼 제출 시 제어가 필수인지 여부
rows — 표시할 줄 수
wrap — 폼 제출을 위해 폼 제어의 값이 어떻게 줄바꿈될지

textarea 요소는 요소의 raw value를 위한 여러 줄의 일반 텍스트 편집 제어를 나타냅니다. 제어의 내용은 제어의 기본 값을 나타냅니다.

textarea 제어의 raw value는 초기에는 빈 문자열이어야 합니다.

이 요소는 양방향 알고리즘과 관련된 렌더링 요구 사항을 가지고 있습니다.

readonly 속성은 사용자가 텍스트를 편집할 수 있는지 여부를 제어하는 boolean 속성입니다.

이 예에서는 텍스트 제어가 읽기 전용 파일을 나타내기 때문에 읽기 전용으로 표시됩니다:

Filename: <code>/etc/bash.bashrc</code>
    <textarea name="buffer" readonly>
    # System-wide .bashrc file for interactive bash(1) shells.
    
    # To enable the settings / commands in this file for login shells as well,
    # this file has to be sourced in /etc/profile.
    
    # If not running interactively, don't do anything
    [ -z "$PS1" ] &amp;&& return
    
    ...</textarea>

제약 조건 유효성 검사: readonly 속성이 textarea 요소에 지정된 경우, 해당 요소는 제약 조건 유효성 검사에서 제외됩니다.

textarea 요소는 readonly 속성이 지정되지 않고 disabled되지 않은 경우 변경 가능 상태입니다.

textarea 요소가 변경 가능 상태인 경우, 사용자는 해당 raw value를 편집할 수 있어야 합니다: 사용자 에이전트는 사용자가 텍스트를 편집하고 삽입하며 삭제할 수 있도록 허용해야 하며, U+000A LINE FEED (LF) 문자 형태로 줄 바꿈을 삽입하고 제거할 수 있도록 해야 합니다. 사용자가 요소의 raw value를 변경할 때마다, 사용자 에이전트는 요소 작업을 큐에 추가하고, 사용자 상호작용 작업 소스input 이벤트를 textarea 요소에서 발생시켜야 하며, 이때 bubblescomposed 속성은 true로 초기화되어야 합니다. 사용자 에이전트는 작업을 큐에 추가하기 전에 사용자의 상호작용에 적절한 중단이 있을 때까지 기다릴 수 있습니다; 예를 들어, 사용자 에이전트는 사용자가 100ms 동안 키를 누르지 않을 때까지 기다려 이벤트를 사용자가 멈췄을 때 발생시키고, 각각의 키 누름에 대해 연속적으로 이벤트를 발생시키지 않을 수 있습니다.

textarea 요소의 dirty value flag는 사용자가 raw value를 변경하는 방식으로 제어와 상호작용할 때마다 true로 설정되어야 합니다.

textarea 요소의 클로닝 단계는 복사되는 노드에서 raw valuedirty value flag를 복사본으로 전달해야 합니다.

textarea 요소의 자식 변경 단계는 요소의 dirty value flag가 false인 경우, 요소의 raw value자식 텍스트 내용으로 설정해야 합니다.

textarea 요소의 리셋 알고리즘사용자 유효성을 false로 설정하고, dirty value flag를 다시 false로 설정하며, 요소의 raw value자식 텍스트 내용으로 설정합니다.

textarea 요소가 열린 요소 스택에서 팝업될 때, 사용자 에이전트는 요소의 리셋 알고리즘을 호출해야 합니다.

textarea 요소가 변경 가능 상태인 경우, 사용자 에이전트는 사용자가 요소의 글쓰기 방향을 왼쪽에서 오른쪽 또는 오른쪽에서 왼쪽으로 변경할 수 있도록 허용해야 합니다. 사용자가 이를 수행한 경우, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. 요소의 dir 속성을 사용자가 왼쪽에서 오른쪽 글쓰기 방향을 선택한 경우 "ltr"로, 오른쪽에서 왼쪽 글쓰기 방향을 선택한 경우 "rtl"로 설정합니다.

  2. 요소 작업을 큐에 추가하고, textarea 요소에 대해 input 이벤트를 발생시키며, bubblescomposed 속성을 true로 초기화합니다.

cols 속성은 줄당 예상 최대 문자 수를 지정합니다. cols 속성이 지정된 경우, 해당 값은 0보다 큰 유효한 0 이상의 정수여야 합니다. 속성 값에 대해 0 이상의 정수를 파싱하는 규칙을 적용한 결과가 0보다 큰 숫자가 나오면 요소의 문자 너비는 그 값입니다; 그렇지 않으면 20입니다.

사용자 에이전트는 textarea 요소의 문자 너비를 서버가 선호하는 줄당 문자 수에 대한 힌트로 사용할 수 있습니다(예: 시각적 사용자 에이전트의 경우 해당 문자 수로 제어 너비를 만듭니다). 시각적 렌더링에서 사용자 에이전트는 사용자의 입력을 렌더링에서 줄당 너비가 이 문자 수를 초과하지 않도록 줄바꿈해야 합니다.

rows 속성은 표시할 줄 수를 지정합니다. rows 속성이 지정된 경우, 해당 값은 0보다 큰 유효한 0 이상의 정수여야 합니다. 속성 값에 대해 0 이상의 정수를 파싱하는 규칙을 적용한 결과가 0보다 큰 숫자가 나오면 요소의 문자 높이는 그 값입니다; 그렇지 않으면 2입니다.

시각적 사용자 에이전트는 문자 높이에 지정된 줄 수만큼 제어의 높이를 설정해야 합니다.

wrap 속성은 다음 키워드와 상태를 가진 열거된 속성입니다:

키워드 상태 간단한 설명
soft 소프트 텍스트가 제출될 때는 줄바꿈되지 않습니다(그러나 렌더링 시에는 여전히 줄바꿈될 수 있음).
hard 하드 텍스트가 제출될 때 줄바꿈되도록 사용자 에이전트에 의해 새 줄이 추가됩니다.

속성의 누락된 값 기본값잘못된 값 기본값은 모두 소프트 상태입니다.

요소의 wrap 속성이 하드 상태인 경우, cols 속성이 지정되어야 합니다.

역사적 이유로 인해, 요소의 값은 세 가지 다른 목적을 위해 세 가지 다른 방식으로 정규화됩니다. raw value는 원래 설정된 값입니다. 이는 정규화되지 않습니다. API 값value IDL 속성, textLength IDL 속성, 및 maxlengthminlength 내용 속성에서 사용되는 값입니다. 이 값은 줄 바꿈이 U+000A LINE FEED (LF) 문자를 사용하도록 정규화됩니다. 마지막으로, 이 사양의 폼 제출 및 기타 처리 모델에서 사용되는 이 있습니다. 이는 API 값과 동일하게 정규화되며, 필요에 따라 요소의 wrap 속성을 감안하여 추가적인 줄 바꿈이 삽입됩니다.

요소의 API 값을 얻기 위한 알고리즘은 요소의 raw value를 반환하며, 줄 바꿈을 정규화합니다.

요소의 은 요소의 API 값textarea 줄 바꿈 변환을 적용한 것입니다. textarea 줄 바꿈 변환은 문자열에 적용되는 다음 알고리즘입니다:

  1. 요소의 wrap 속성이 하드 상태인 경우, 각 줄에 문자 너비를 초과하지 않도록 U+000A LINE FEED (LF) 문자를 사용하여 문자열에 줄 바꿈을 삽입합니다. 이 요구 사항을 위해 줄은 문자열의 시작, 끝, 및 U+000A LINE FEED (LF) 문자에 의해 구분됩니다.

maxlength 속성은 폼 제어 maxlength 속성입니다.

textarea 요소가 최대 허용 값 길이를 가지고 있는 경우, 요소의 자식은 요소의 값의 길이하위 텍스트 내용과 함께 줄 바꿈을 정규화한 후에도 요소의 최대 허용 값 길이보다 작거나 같아야 합니다.

minlength 속성은 폼 제어 minlength 속성입니다.

required 속성은 사용자가 값을 입력하기 전에 폼을 제출해야 하는지 여부를 나타내는 boolean 속성입니다.

제약 조건 유효성 검사: 요소에 required 속성이 지정되어 있고, 요소가 변경 가능 상태이며, 요소의 이 빈 문자열인 경우, 해당 요소는 값이 누락된 상태입니다.

placeholder 속성은 제어에 값이 없을 때 사용자의 데이터 입력을 돕기 위한 짧은 힌트(단어 또는 짧은 구)를 나타냅니다. 힌트는 샘플 값이나 예상 형식에 대한 간단한 설명일 수 있습니다.

placeholder 속성은 label에 대한 대체로 사용해서는 안 됩니다. 더 긴 힌트나 기타 권고 텍스트의 경우 title 속성이 더 적합합니다.

이 메커니즘들은 매우 유사하지만 미묘하게 다릅니다: 제어의 label에 의해 제공되는 힌트는 항상 표시됩니다; placeholder 속성에 제공된 짧은 힌트는 사용자가 값을 입력하기 전에 표시됩니다; title 속성에 제공된 힌트는 사용자가 추가적인 도움을 요청할 때 표시됩니다.

사용자 에이전트는 제어의 값이 빈 문자열이고 제어가 포커스되지 않은 경우 이 힌트를 사용자에게 제시해야 합니다(예: 빈 포커스되지 않은 제어 내에 표시). 힌트에서 모든 U+000D CARRIAGE RETURN U+000A LINE FEED 문자 쌍(CRLF)과 힌트의 모든 다른 U+000D CARRIAGE RETURN (CR) 및 U+000A LINE FEED (LF) 문자는 렌더링 시 줄 바꿈으로 처리되어야 합니다.

사용자 에이전트가 제어에 포커스가 있을 때 이 힌트를 사용자에게 표시하지 않는 경우, 사용자가 제어를 포커스하기 전에 제어를 검사할 기회를 가지지 못했기 때문에, autofocus 속성의 결과로 포커스된 경우에는 제어에 대한 힌트를 여전히 표시해야 합니다.

name 속성은 요소의 이름을 나타냅니다. dirname 속성은 요소의 방향성이 제출되는 방식을 제어합니다. disabled 속성은 제어를 비활성화하고 그 값이 제출되지 않도록 합니다. form 속성은 textarea 요소를 명시적으로 폼 소유자와 연결하는 데 사용됩니다. autocomplete 속성은 사용자 에이전트가 자동 완성 동작을 제공하는 방식을 제어합니다.

textarea.type

"textarea" 문자열을 반환합니다.

textarea.value

요소의 현재 값을 반환합니다.

값을 변경하기 위해 설정할 수 있습니다.

cols, placeholder, required, rows, 및 wrap IDL 속성은 각각 동일한 이름의 내용 속성을 반영해야 합니다. colsrows 속성은 0보다 큰 양수로 제한되며, cols IDL 속성의 기본 값은 20입니다. rows IDL 속성의 기본 값은 2입니다. dirName IDL 속성은 dirname 내용 속성을 반영해야 합니다. maxLength IDL 속성은 반영해야 하며, maxlength 내용 속성은 0 이상의 양수로 제한됩니다. minLength IDL 속성은 반영해야 하며, minlength 내용 속성은 0 이상의 양수로 제한됩니다. readOnly IDL 속성은 반영해야 하며, readonly 내용 속성을 반영해야 합니다.

type IDL 속성은 "textarea" 값을 반환해야 합니다.

defaultValue 속성의 getter는 요소의 자식 텍스트 내용을 반환해야 합니다.

defaultValue 속성의 setter는 이 요소 내에서 주어진 값으로 모든 문자열을 대체해야 합니다.

value IDL 속성은 getter에서 요소의 API 값을 반환해야 하며, setter에서 다음 단계를 수행해야 합니다:

  1. oldAPIValue를 이 요소의 API 값으로 설정합니다.

  2. 이 요소의 raw value를 새 값으로 설정합니다.

  3. 이 요소의 dirty value flag를 true로 설정합니다.

  4. API 값oldAPIValue와 다르면, 텍스트 입력 커서 위치를 텍스트 제어의 끝으로 이동하고, 선택된 텍스트를 선택 해제하고, 선택 방향을 "none"으로 재설정합니다.

textLength IDL 속성은 요소의 길이를 반환해야 합니다.

willValidate, validity, 및 validationMessage IDL 속성들과 checkValidity(), reportValidity(), setCustomValidity() 메서드는 제약 조건 유효성 검사 API의 일부입니다. labels IDL 속성은 요소의 label 목록을 제공합니다. select(), selectionStart, selectionEnd, selectionDirection, setRangeText(), 및 setSelectionRange() 메서드와 IDL 속성은 요소의 텍스트 선택을 노출합니다.

다음은 폼에서 자유 형식의 텍스트 입력을 위한 textarea의 예입니다:

<p>If you have any comments, please let us know: <textarea cols=80 name=comments></textarea></p>

댓글에 최대 길이를 지정하려면 maxlength 속성을 사용할 수 있습니다:

<p>If you have any short comments, please let us know: <textarea cols=80 name=comments maxlength=200></textarea></p>

기본 값을 제공하려면 텍스트를 요소 내에 포함할 수 있습니다:

<p>If you have any comments, please let us know: <textarea cols=80 name=comments>You rock!</textarea></p>

최소 길이도 지정할 수 있습니다. 여기에서는 사용자가 채워야 하는 편지가 있습니다; 템플릿(최소 길이보다 짧음)이 제공되지만, 폼을 제출하기에는 충분하지 않습니다:

<textarea required minlength="500">Dear Madam Speaker,

Regarding your letter dated ...

...

Yours Sincerely,

...</textarea>

명시적인 템플릿을 제공하지 않고도 사용자에게 기본 형식을 제안하기 위해 placeholder를 사용할 수도 있습니다:

<textarea placeholder="Dear Francine,

They closed the parks this week, so we won't be able to
meet your there. Should we just have dinner?

Love,
Daddy"></textarea>

브라우저가 요소의 방향성을 값과 함께 제출하도록 하려면 dirname 속성을 지정할 수 있습니다:

<p>If you have any comments, please let us know (you may use either English or Hebrew for your comments):
<textarea cols=80 name=comments dirname=comments.dir></textarea></p>

4.10.12 output 요소

Element/output

모든 최신 엔진에서 지원됨.

Firefox4+Safari7+Chrome10+
Opera11+Edge79+
Edge (Legacy)18Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

HTMLOutputElement

모든 최신 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)14+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+
카테고리:
Flow content.
Phrasing content.
목록화됨, 레이블 가능, 재설정 가능, 및 자동 대문자화 상속 양식 관련 요소.
Palpable content.
이 요소를 사용할 수 있는 맥락:
어디서든 Phrasing content이 기대됨.
컨텐츠 모델:
Phrasing content.
text/html에서 태그 생략:
태그를 생략할 수 없음.
컨텐츠 속성:
글로벌 속성
for — 계산이 수행된 컨트롤 지정
form — 요소를 양식 요소와 연결
nameform.elements API에서 사용할 요소의 이름.
접근성 고려 사항:
저자에게.
구현자에게.
DOM 인터페이스:
[Exposed=Window]
interface HTMLOutputElement : HTMLElement {
  [HTMLConstructor] constructor();

  [SameObject, PutForwards=value] readonly attribute DOMTokenList htmlFor;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString name;

  readonly attribute DOMString type;
  [CEReactions] attribute DOMString defaultValue;
  [CEReactions] attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity()(DOMString error);

  readonly attribute NodeList labels;
};

output 요소는 애플리케이션에서 수행된 계산의 결과 또는 사용자 작업의 결과를 나타냅니다.

이 요소는 이전에 실행된 다른 프로그램의 출력을 인용하는 데 적합한 samp 요소와 대조될 수 있습니다.

Attributes/for

모든 최신 엔진에서 지원됨.

Firefox4+Safari7+Chrome10+
Opera11+Edge79+
Edge (Legacy)18Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

for 컨텐츠 속성은 계산 결과와 계산에 사용된 값 또는 계산에 영향을 준 요소들 간의 명확한 관계를 설정할 수 있도록 합니다. for 속성이 지정된 경우, 고유한 공백으로 구분된 토큰 집합으로 구성된 문자열을 포함해야 하며, 이 중 어떤 것도 다른 토큰과 동일하지 않아야 하며 각각은 동일한 트리 내의 요소 ID 값을 가져야 합니다.

form 속성은 output 요소를 폼 소유자와 명시적으로 연결하는 데 사용됩니다. name 속성은 요소의 이름을 나타냅니다. output 요소는 폼 컨트롤의 이벤트 핸들러에서 쉽게 참조될 수 있도록 폼과 연결되며, 요소의 값 자체는 폼이 제출될 때 제출되지 않습니다.

이 요소에는 기본값 재정의(null 또는 문자열)이 있습니다. 초기에는 null이어야 합니다.

요소의 기본값은 다음 단계에 따라 결정됩니다:

  1. 이 요소의 기본값 재정의가 null이 아닌 경우, 해당 값을 반환합니다.

  2. 이 요소의 하위 텍스트 내용을 반환합니다.

output 요소의 재설정 알고리즘은 다음 단계를 실행합니다:

  1. 모든 문자열을 대체하여 이 요소의 기본값을 이 요소 내에서 대체합니다.

  2. 이 요소의 기본값 재정의를 null로 설정합니다.

output.value [ = value ]

요소의 현재 값을 반환합니다.

설정할 수 있으며, 값을 변경할 수 있습니다.

output.defaultValue [ = value ]

요소의 현재 기본값을 반환합니다.

설정할 수 있으며, 기본값을 변경할 수 있습니다.

output.type

문자열 "output"을 반환합니다.

value getter 단계는 this하위 텍스트 내용을 반환하는 것입니다.

value setter 단계는 다음과 같습니다:

  1. this기본값 재정의기본값으로 설정합니다.

  2. 모든 문자열을 대체하여 this 내에서 주어진 값으로 대체합니다.

defaultValue getter 단계는 this기본값을 반환하는 것입니다.

defaultValue setter 단계는 다음과 같습니다:

  1. this기본값 재정의가 null인 경우, 모든 문자열을 대체하여 주어진 값으로 this 내에서 대체하고 반환합니다.

  2. this기본값 재정의를 주어진 값으로 설정합니다.

type getter 단계는 "output"을 반환하는 것입니다.

htmlFor IDL 속성은 반영하여 for 컨텐츠 속성을 반영해야 합니다.

willValidate, validity, 및 validationMessage IDL 속성, 그리고 checkValidity(), reportValidity(), 및 setCustomValidity() 메서드는 제약 조건 유효성 검사 API의 일부입니다. labels IDL 속성은 요소의 레이블 목록을 제공합니다. formname IDL 속성은 요소의 폼 API의 일부입니다.

간단한 계산기는 output을 사용하여 계산된 결과를 표시할 수 있습니다:

<form onsubmit="return false" oninput="o.value = a.valueAsNumber + b.valueAsNumber">
<input id=a type=number step=any> +
<input id=b type=number step=any> =
<output id=o for="a b"></output>
</form>

이 예에서는 output 요소가 원격 서버에서 수행된 계산의 결과를 실시간으로 보고하는 데 사용됩니다:

<output id="result"></output>
<script>
var primeSource = new WebSocket('ws://primes.example.net/'); primeSource.onmessage = function (event) {
document.getElementById('result').value = event.data; }</script>

4.10.13 progress 요소

Element/progress

현재 모든 엔진에서 지원됩니다.

Firefox6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

HTMLProgressElement

현재 모든 엔진에서 지원됩니다.

Firefox6+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
플로우 콘텐츠.
프레이징 콘텐츠.
라벨이 가능한 요소.
감지 가능한 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
프레이징 콘텐츠가 예상되는 곳.
콘텐츠 모델:
프레이징 콘텐츠, 하지만 progress 요소의 하위 요소는 없어야 합니다.
텍스트/html에서의 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
value — 요소의 현재 값
max — 범위의 상한선
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLProgressElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute double value;
  [CEReactions] attribute double max;
  readonly attribute double position;
  readonly attribute NodeList labels;
};

progress 요소는 작업의 완료 진행 상황을 나타냅니다. 진행 상황은 불확정일 수 있으며, 이는 작업이 진행 중이지만 작업이 완료되기까지 남은 작업량이 명확하지 않음을 의미합니다(예: 작업이 원격 호스트의 응답을 기다리고 있음). 또는 진행 상황은 0에서 최대치까지의 숫자로 표현되며, 지금까지 완료된 작업의 비율을 나타냅니다.

속성/max

현재 모든 엔진에서 지원됩니다.

Firefox6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS7+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

이 요소는 현재 작업 완료 상황을 나타내는 두 가지 속성을 가집니다. value 속성은 작업의 얼마나 완료되었는지를 지정하며, max 속성은 작업이 총 몇 단계를 요구하는지를 지정합니다. 단위는 임의이며 지정되지 않습니다.

결정적 진행 표시줄을 만들려면 value 속성을 추가하여 현재 진행 상황을 지정합니다(0.0에서 1.0까지의 숫자이거나, max 속성이 지정된 경우 max 속성 값까지의 숫자). 불확정적 진행 표시줄을 만들려면 value 속성을 제거합니다.

저자들은 레거시 사용자 에이전트 사용자를 위해 진행 상황을 요소 내 텍스트로 현재 값과 최대 값을 포함하는 것을 권장합니다.

다음은 자동화된 작업의 진행 상황을 보여주는 웹 애플리케이션의 코드 조각입니다:

<section>
<h2>작업 진행 상황</h2>
<p>진행: <progress id=p max=100><span>0</span>%</progress></p>
<script>
var progressBar = document.getElementById('p');
function updateProgress(newValue) {
  progressBar.value = newValue;
  progressBar.getElementsByTagName('span')[0].textContent = newValue;
}
</script>
</section>

(이 예제의 updateProgress() 메서드는 작업이 진행될 때 페이지의 다른 코드에 의해 실제 진행 표시줄을 업데이트하기 위해 호출됩니다.)

valuemax 속성은 존재할 경우 유효한 부동 소수점 숫자여야 합니다. value 속성이 존재하는 경우 그 값은 0보다 크거나 같고, max 속성 값보다 작거나 같아야 하며, 존재하지 않을 경우 1.0 이하여야 합니다. max 속성이 존재하는 경우 그 값은 0보다 커야 합니다.

progress 요소는 게이지일 뿐인 것을 나타내는 데는 부적합합니다. 예를 들어, progress를 사용하여 디스크 공간 사용량을 나타내는 것은 부적절합니다. 대신, meter 요소를 이러한 경우에 사용할 수 있습니다.

사용자 에이전트 요구사항: value 속성이 생략된 경우 진행 표시줄은 불확정적 진행 표시줄입니다. 그렇지 않으면, 결정적 진행 표시줄입니다.

진행 표시줄이 결정적 진행 표시줄이고 요소에 max 속성이 있는 경우, 사용자 에이전트는 max 속성 값을 부동 소수점 숫자 값을 구문 분석하는 규칙에 따라 구문 분석해야 합니다. 이 작업이 오류를 발생시키지 않고 구문 분석된 값이 0보다 크면, 진행 표시줄의 최대 값은 해당 값입니다. 그렇지 않으면, 요소에 max 속성이 없거나, 있더라도 구문 분석 중 오류가 발생했거나, 구문 분석된 값이 0보다 작거나 같은 경우, 진행 표시줄의 최대 값은 1.0입니다.

진행 표시줄이 결정적 진행 표시줄인 경우, 사용자 에이전트는 value 속성 값을 부동 소수점 숫자 값을 구문 분석하는 규칙에 따라 구문 분석해야 합니다. 이 작업이 오류를 발생시키지 않고 구문 분석된 값이 0보다 크면, 진행 표시줄의 은 해당 구문 분석된 값입니다. 그렇지 않으면, value 속성 값의 구문 분석이 오류로 이어졌거나 0보다 작거나 같은 경우, 진행 표시줄의 은 0입니다.

진행 표시줄이 결정적 진행 표시줄인 경우, 현재 값최대 값이며, 최대 값보다 크지 않으면 이 됩니다.

진행 표시줄 표시를 위한 UA 요구사항: progress 요소를 사용자에게 표시할 때, UA는 결정적 또는 불확정적 진행 표시줄인지 여부를 나타내야 하며, 전자의 경우 현재 값최대 값에 비해 상대적인 위치를 표시해야 합니다.

progress.position

결정적 진행 표시줄(현재 값과 최대 값이 알려진 경우)에 대해서는 현재 값을 최대 값으로 나눈 결과를 반환합니다.

불확정적 진행 표시줄에 대해서는 -1을 반환합니다.

진행 표시줄이 불확정적 진행 표시줄인 경우, position IDL 속성은 -1을 반환해야 합니다. 그렇지 않으면 현재 값최대 값으로 나눈 결과를 반환해야 합니다.

진행 표시줄이 불확정적 진행 표시줄인 경우, value IDL 속성은 가져올 때 0을 반환해야 하며, 그렇지 않으면 현재 값을 반환해야 합니다. 설정할 때, 주어진 값은 부동 소수점 숫자로서의 최적 표현으로 변환된 후 value 콘텐츠 속성에 설정되어야 합니다.

value IDL 속성을 자체에 설정하면 해당 콘텐츠 속성이 없는 경우 진행 표시줄이 불확정적 진행 표시줄에서 결정적 진행 표시줄로 변경되고 진행이 없게 됩니다.

max IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 하며, 0보다 큰 숫자만 제한됩니다. max기본 값은 1.0입니다.

labels IDL 속성은 요소의 라벨 목록을 제공합니다.

4.10.14 meter 요소

Element/meter

현재 모든 엔진에서 지원됩니다.

Firefox16+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)18Internet Explorer지원 안 됨
Firefox Android?Safari iOS10.3+Chrome Android?WebView Android지원 안 됨Samsung Internet?Opera Android11+

HTMLMeterElement

현재 모든 엔진에서 지원됩니다.

Firefox16+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)18Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android지원 안 됨Samsung Internet?Opera Android11+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
라벨링 가능 요소.
직관적 콘텐츠.
이 요소가 사용될 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
구문 콘텐츠, 그러나 meter 요소 자손이 없어야 함.
태그 생략:
태그를 생략할 수 없음.
콘텐츠 속성:
글로벌 속성
value — 요소의 현재 값
min — 범위의 하한값
max — 범위의 상한값
low — 낮은 범위의 상한값
high — 높은 범위의 하한값
optimum — 게이지의 최적 값
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLMeterElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute double value;
  [CEReactions] attribute double min;
  [CEReactions] attribute double max;
  [CEReactions] attribute double low;
  [CEReactions] attribute double high;
  [CEReactions] attribute double optimum;
  readonly attribute NodeList labels;
};

meter 요소는 알려진 범위 내에서의 스칼라 측정치나 분수 값을 나타냅니다. 예를 들어 디스크 사용량, 쿼리 결과의 관련성, 또는 특정 후보자를 선택한 유권자 비율 등을 나타낼 수 있습니다.

이것은 게이지(gauge)로도 알려져 있습니다.

meter 요소는 진행 상황을 표시하는 데 사용해서는 안 됩니다. 그 역할을 위해 HTML은 별도의 progress 요소를 제공합니다.

meter 요소는 또한 임의 범위의 스칼라 값을 나타내지 않습니다. 예를 들어, 이 요소를 사용하여 체중 또는 키를 보고하는 것은 적절하지 않습니다. 최대 값이 알려진 경우에만 사용해야 합니다.

이 요소는 게이지의 의미를 결정하는 6개의 속성을 가지고 있습니다.

Attributes/max

현재 모든 엔진에서 지원됩니다.

Firefox16+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)18Internet Explorer지원 안 됨
Firefox Android?Safari iOS10.3+Chrome Android?WebView Android지원 안 됨Samsung Internet?Opera Android11+

min 속성은 범위의 하한값을 지정하고, max 속성은 범위의 상한값을 지정합니다. value 속성은 게이지가 "측정된" 값으로 나타내야 할 값을 지정합니다.

나머지 세 가지 속성은 게이지의 범위를 "낮음", "중간", "높음" 부분으로 분할하고, 게이지의 "최적" 부분이 어디인지를 나타내는 데 사용할 수 있습니다. low 속성은 "낮음" 부분으로 간주되는 범위를 지정하고, high 속성은 "높음" 부분으로 간주되는 범위를 지정합니다. optimum 속성은 "최적" 위치를 제공합니다. 최적 값이 "높음" 값보다 높으면 값이 높을수록 더 나은 것으로 표시되며, "낮음" 값보다 낮으면 값이 낮을수록 더 나은 것으로 표시되며, 중간에 있으면 높은 값이나 낮은 값 모두가 좋지 않은 것으로 표시됩니다.

작성자 요구사항: value 속성은 필수입니다. value, min, low, high, max, 그리고 optimum 속성은 존재하는 경우 유효한 부동 소수점 숫자여야 합니다.

또한 속성 값은 추가로 제한됩니다:

valuevalue 속성의 숫자라고 합니다.

min 속성이 지정된 경우, minimum은 해당 속성의 값입니다. 그렇지 않으면 0입니다.

max 속성이 지정된 경우, maximum은 해당 속성의 값입니다. 그렇지 않으면 1.0입니다.

다음의 부등식이 적용 가능한 경우 적용됩니다:

최소값 또는 최대값이 지정되지 않은 경우, 범위는 0에서 1로 간주되며 값은 해당 범위 내에 있어야 합니다.

작성자는 사용자 에이전트가 meter 요소를 지원하지 않는 사용자를 위해 게이지 상태의 텍스트 표현을 요소 내용에 포함시키는 것이 좋습니다.

Microdata와 함께 사용할 때, meter 요소의 value 속성은 요소의 기계 가독 값을 제공합니다.

다음 예시는 4분의 3이 찬 세 가지 게이지를 보여줍니다:

저장 공간 사용량: <meter value=6 max=8>6 블록 사용됨 (전체 8 중)</meter>
유권자 참여율: <meter value=0.75><img alt="75%" src="graph75.png"></meter>
티켓 판매량: <meter min="0" max="100" value="75"></meter>

다음 예시는 잘못된 사용 예입니다. 범위를 지정하지 않았기 때문에 (기본 최대값이 1이므로 두 게이지 모두 최대값에 도달한 것으로 보일 것입니다):

<p>그레이프루트 파이의 반지름은 <meter value=12>12cm</meter>이고 높이는 <meter value=2>2cm</meter>입니다.</p> <!-- 잘못된 사용! -->

대신, meter 요소를 포함하지 않거나, 다른 파이와 비교하여 컨텍스트 내에서 치수를 제공하기 위해 정의된 범위를 사용해야 합니다:

<p>그레이프루트 파이의 반지름은 12cm이고 높이는 2cm입니다.</p>
<dl>
 <dt>반지름: <dd> <meter min=0 max=20 value=12>12cm</meter>
 <dt>높이: <dd> <meter min=0 max=10 value=2>2cm</meter>
</dl>

meter 요소에서는 명시적으로 단위를 지정할 방법이 없지만, title 속성에서 자유 형식의 텍스트로 단위를 지정할 수 있습니다.

위의 예시를 확장하여 단위를 언급할 수 있습니다:

<dl>
 <dt>반지름: <dd> <meter min=0 max=20 value=12 title="센티미터">12cm</meter>
 <dt>높이: <dd> <meter min=0 max=10 value=2 title="센티미터">2cm</meter>
</dl>

사용자 에이전트 요구사항: 사용자 에이전트는 min, max, value, low, high, 그리고 optimum 속성을 부동 소수점 숫자 값을 구문 분석하는 규칙에 따라 구문 분석해야 합니다.

그런 다음 사용자 에이전트는 모든 숫자를 사용하여 게이지의 여섯 가지 지점을 다음과 같이 얻어야 합니다. (일부 값이 이전 값을 참조하므로 평가 순서가 중요합니다.)

최소값

min 속성이 지정되고 해당 값이 구문 분석될 수 있으면 최소값은 해당 값입니다. 그렇지 않으면 최소값은 0입니다.

최대값

max 속성이 지정되고 해당 값이 구문 분석될 수 있으면 후보 최대값은 해당 값입니다. 그렇지 않으면 후보 최대값은 1.0입니다.

후보 최대값이 최소값보다 크거나 같으면 최대값은 후보 최대값입니다. 그렇지 않으면 최대값은 최소값과 동일합니다.

실제 값

value 속성이 지정되고 해당 값이 구문 분석될 수 있으면 해당 값이 후보 실제 값입니다. 그렇지 않으면 후보 실제 값은 0입니다.

후보 실제 값이 최소값보다 작으면 실제 값은 최소값입니다.

그렇지 않으면, 후보 실제 값이 최대값보다 크면 실제 값은 최대값입니다.

그렇지 않으면, 실제 값은 후보 실제 값입니다.

낮음 경계

low 속성이 지정되고 해당 값이 구문 분석될 수 있으면 후보 낮음 경계는 해당 값입니다. 그렇지 않으면 후보 낮음 경계는 최소값과 동일합니다.

후보 낮음 경계가 최소값보다 작으면 낮음 경계는 최소값입니다.

그렇지 않으면 후보 낮음 경계가 최대값보다 크면 낮음 경계는 최대값입니다.

그렇지 않으면, 낮음 경계는 후보 낮음 경계입니다.

높음 경계

high 속성이 지정되고 해당 값이 구문 분석될 수 있으면 후보 높음 경계는 해당 값입니다. 그렇지 않으면 후보 높음 경계는 최대값과 동일합니다.

후보 높음 경계가 낮음 경계보다 작으면 높음 경계는 낮음 경계입니다.

그렇지 않으면 후보 높음 경계가 최대값보다 크면 높음 경계는 최대값입니다.

그렇지 않으면, 높음 경계는 후보 높음 경계입니다.

최적 지점

optimum 속성이 지정되고 해당 값이 구문 분석될 수 있으면 후보 최적 지점은 해당 값입니다. 그렇지 않으면 후보 최적 지점은 최소값과 최대값 사이의 중간 지점입니다.

후보 최적 지점이 최소값보다 작으면 최적 지점은 최소값입니다.

그렇지 않으면 후보 최적 지점이 최대값보다 크면 최적 지점은 최대값입니다.

그렇지 않으면 최적 지점은 후보 최적 지점입니다.

모든 부등식이 다음과 같이 참이 됩니다:

게이지 영역에 대한 사용자 에이전트 요구사항: 최적 지점이 낮음 경계 또는 높음 경계와 같거나 그 사이에 있으면, 게이지의 낮음 및 높음 부분이 있는 경우, 해당 영역은 최적 영역으로 간주되며, 낮음 및 높음 부분은 비최적 영역으로 간주됩니다. 최적 지점이 낮음 경계보다 작으면 최소값과 낮음 경계 사이의 영역은 최적 영역으로 간주되고, 낮음 경계에서 높음 경계까지의 영역은 비최적 영역으로 간주되며, 나머지 영역은 더 나쁜 영역으로 간주됩니다. 최적 지점이 높음 경계보다 높으면 상황은 반대가 되어, 높음 경계와 최대값 사이의 영역이 최적 영역으로 간주되고, 높음 경계에서 낮음 경계까지의 영역은 비최적 영역으로 간주되며, 나머지 영역은 더 나쁜 영역으로 간주됩니다.

게이지 표시를 위한 사용자 에이전트 요구사항: meter 요소를 사용자에게 표시할 때, 사용자 에이전트는 실제 값이 최소값과 최대값에 대해 상대적으로 어떤 위치에 있는지, 그리고 실제 값과 게이지의 세 가지 영역 간의 관계를 나타내야 합니다.

다음 마크업:

<h3>추천 그룹</h3>
<menu>
 <li><a href="?cmd=hsg" onclick="hideSuggestedGroups()">추천 그룹 숨기기</a></li>
</menu>
<ul>
 <li>
  <p><a href="/group/comp.infosystems.www.authoring.stylesheets/view">comp.infosystems.www.authoring.stylesheets</a> - <a href="/group/comp.infosystems.www.authoring.stylesheets/subscribe">가입하기</a></p>
  <p>그룹 설명: <strong>웹의 레이아웃/프레젠테이션.</strong></p>
  <p><meter value="0.5">보통 활동성,</meter> Usenet, 618명의 가입자</p>
 </li>
 <li>
  <p><a href="/group/netscape.public.mozilla.xpinstall/view">netscape.public.mozilla.xpinstall</a> - <a href="/group/netscape.public.mozilla.xpinstall/subscribe">가입하기</a></p>
  <p>그룹 설명: <strong>Mozilla XPInstall 토론.</strong></p>
  <p><meter value="0.25">낮은 활동성,</meter> Usenet, 22명의 가입자</p>
 </li>
 </li>
  <p><a href="/group/mozilla.dev.general/view">mozilla.dev.general</a> - <a href="/group/mozilla.dev.general/subscribe">가입하기</a></p>
  <p><meter value="0.25">낮은 활동성,</meter> Usenet, 66명의 가입자</p>
 </li>
</ul>

다음과 같이 렌더링될 수 있습니다:

meter 요소가 다양한 길이의 인라인 초록색 막대로 렌더링된 모습.

사용자 에이전트는 title 속성의 값과 다른 속성의 값을 결합하여 문맥에 따라 달라지는 도움말 또는 실제 값을 설명하는 인라인 텍스트를 제공할 수 있습니다.

예를 들어, 다음 코드 조각은:

<meter min=0 max=60 value=23.2 title=></meter>

...사용자 에이전트가 "값: 60 중 23.2."라는 툴팁을 한 줄로 표시하고 "초"를 두 번째 줄에 표시하게 할 수 있습니다.

value IDL 속성은 값을 가져올 때 실제 값을 반환해야 합니다. 설정할 때 주어진 값은 부동 소수점 숫자로 가장 적합하게 표현된 값으로 변환된 다음, value 콘텐츠 속성에 해당 문자열로 설정해야 합니다.

min IDL 속성은 값을 가져올 때 최소 값을 반환해야 합니다. 설정할 때 주어진 값은 부동 소수점 숫자로 가장 적합하게 표현된 값으로 변환된 다음, min 콘텐츠 속성에 해당 문자열로 설정해야 합니다.

max IDL 속성은 값을 가져올 때 최대 값을 반환해야 합니다. 설정할 때 주어진 값은 부동 소수점 숫자로 가장 적합하게 표현된 값으로 변환된 다음, max 콘텐츠 속성에 해당 문자열로 설정해야 합니다.

low IDL 속성은 값을 가져올 때 낮은 경계를 반환해야 합니다. 설정할 때 주어진 값은 부동 소수점 숫자로 가장 적합하게 표현된 값으로 변환된 다음, low 콘텐츠 속성에 해당 문자열로 설정해야 합니다.

high IDL 속성은 값을 가져올 때 높은 경계를 반환해야 합니다. 설정할 때 주어진 값은 부동 소수점 숫자로 가장 적합하게 표현된 값으로 변환된 다음, high 콘텐츠 속성에 해당 문자열로 설정해야 합니다.

optimum IDL 속성은 값을 가져올 때 최적 값을 반환해야 합니다. 설정할 때 주어진 값은 부동 소수점 숫자로 가장 적합하게 표현된 값으로 변환된 다음, optimum 콘텐츠 속성에 해당 문자열로 설정해야 합니다.

labels IDL 속성은 요소의 label 리스트를 제공합니다.

다음 예제는 게이지가 어떻게 로컬화된 텍스트나 보기 좋은 형태의 텍스트로 대체될 수 있는지를 보여줍니다.

<p>디스크 사용량: <meter min=0 value=170261928 max=233257824>총 233,257,824 바이트 중 170,261,928 바이트 사용됨</meter></p>

4.10.15 fieldset 요소

요소/fieldset

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari4+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

HTMLFieldSetElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
카테고리:
흐름 콘텐츠.
목록화자동 대문자화 상속 폼 연관 요소.
감지 가능한 콘텐츠.
이 요소가 사용할 수 있는 맥락:
흐름 콘텐츠가 예상되는 곳.
콘텐츠 모델:
전설 요소(선택 사항), 그 뒤에 흐름 콘텐츠.
text/html에서의 태그 생략:
태그 생략 불가.
콘텐츠 속성:
글로벌 속성
비활성화 — 하위 폼 컨트롤이 비활성화될지 여부(전설 안에 있는 것은 제외).
— 요소를 요소와 연결.
이름폼.요소들 API에서 사용할 요소의 이름.
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLFieldSetElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString name;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLCollection elements;

  readonly attribute boolean willValidate;
  [SameObject] readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);
};

fieldset 요소는 여러 폼 컨트롤(또는 기타 콘텐츠)을 함께 그룹화한 집합을 나타내며, 선택적으로 캡션을 포함할 수 있습니다. 캡션은 legend 요소에서 제공되며, fieldset 요소의 첫 번째 자식인 경우에만 표시됩니다. 나머지 하위 요소는 그룹을 형성합니다.

요소/fieldset#attr-disabled

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari6+Chrome20+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

지정된 경우, disabled 속성은 모든 하위 폼 컨트롤을 fieldset 요소에서 제외하고 fieldset 요소의 첫 번째 legend 요소 자손을 제외하여 비활성화시킵니다.

fieldset 요소는 다음 조건 중 하나와 일치하는 경우 비활성화된 fieldset입니다:

form 속성은 fieldset 요소를 폼 소유자와 명시적으로 연결하는 데 사용됩니다. name 속성은 요소의 이름을 나타냅니다.

fieldset.type

문자열 "fieldset"을 반환합니다.

fieldset.elements

해당 요소의 폼 컨트롤에 대한 HTMLCollection을 반환합니다.

disabled IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

type IDL 속성은 문자열 "fieldset"을 반환해야 합니다.

elements IDL 속성은 HTMLCollection을 반환해야 하며, 이 컬렉션은 fieldset 요소에 뿌리를 두고 있으며, 필터는 목록에 포함된 요소와 일치합니다.

willValidate, validity, validationMessage 속성 및 checkValidity(), reportValidity(), setCustomValidity() 메서드는 제약 조건 유효성 검사 API의 일부입니다. 이름 IDL 속성은 요소의 폼 API의 일부입니다.

이 예제는 관련 컨트롤 집합을 그룹화하는 데 사용되는 fieldset 요소를 보여줍니다:

<fieldset>
 <legend>Display</legend>
 <p><label><input type=radio name=c value=0 checked> Black on White</label>
 <p><label><input type=radio name=c value=1> White on Black</label>
 <p><label><input type=checkbox name=g> Use grayscale</label>
 <p><label>Enhance contrast <input type=range name=e list=contrast min=0 max=100 value=0 step=1></label>
 <datalist id=contrast>
  <option label=Normal value=0>
  <option label=Maximum value=100>
 </datalist>
</fieldset>

다음 스니펫은 필드셋을 활성화하거나 비활성화하는 전설에 체크박스가 포함된 필드셋을 보여줍니다. 필드셋의 내용은 두 개의 필수 텍스트 컨트롤과 선택 가능한 연도/월 컨트롤로 구성됩니다.

<fieldset name="clubfields" disabled>
 <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
 </label> </legend>
 <p><label>Name on card: <input name=clubname required></label></p>
 <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
 <p><label>Expiry date: <input name=clubexp type=month></label></p>
</fieldset>

또한 fieldset 요소를 중첩할 수도 있습니다. 이전 예제를 확장하여 이를 구현한 예제가 있습니다:

<fieldset name="clubfields" disabled>
 <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
 </label> </legend>
 <p><label>Name on card: <input name=clubname required></label></p>
 <fieldset name="numfields">
  <legend> <label>
   <input type=radio checked name=clubtype onchange="form.numfields.disabled = !checked">
   My card has numbers on it
  </label> </legend>
  <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
 </fieldset>
 <fieldset name="letfields" disabled>
  <legend> <label>
   <input type=radio name=clubtype onchange="form.letfields.disabled = !checked">
   My card has letters on it
  </label> </legend>
  <p><label>Card code: <input name=clublet required pattern="[A-Za-z]+"></label></p>
 </fieldset>
</fieldset>

이 예제에서는 외부 "Use Club Card" 체크박스가 선택되지 않은 경우, 외부 fieldset 내부의 모든 요소(두 개의 내장 fieldset의 전설에 있는 두 개의 라디오 버튼 포함)가 비활성화됩니다. 그러나 체크박스가 선택된 경우, 두 개의 라디오 버튼이 모두 활성화되어 두 개의 내부 fieldset 중 어느 것이 활성화될지를 선택할 수 있습니다.

이 예제는 legend 요소가 그룹화를 라벨링하고, 중첩된 제목 요소가 문서 개요에 그룹화를 노출하는 컨트롤 그룹을 보여줍니다:

<fieldset>
 <legend> <h2>
  How can we best reach you?
 </h2> </legend>
 <p> <label>
 <input type=radio checked name=contact_pref> Phone
 </label> </p>
 <p> <label>
  <input type=radio name=contact_pref> Text
 </label> </p>
 <p> <label>
  <input type=radio name=contact_pref> Email
 </label> </p>
</fieldset>

4.10.16 legend 요소

요소/legend

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+인터넷 익스플로러6+
Firefox 안드로이드?Safari iOS1+Chrome 안드로이드?WebView 안드로이드?삼성 인터넷?Opera 안드로이드12.1+

HTMLLegendElement

모든 최신 엔진에서 지원.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (레거시)12+인터넷 익스플로러6+
Firefox 안드로이드?Safari iOS?Chrome 안드로이드?WebView 안드로이드?삼성 인터넷?Opera 안드로이드12.1+
카테고리:
없음.
이 요소가 사용될 수 있는 맥락:
첫 번째 자식으로서 fieldset 요소의.
내용 모델:
구문 콘텐츠, 선택적으로 제목 콘텐츠와 혼합됨.
텍스트/HTML에서 태그 생략:
태그 생략 불가.
콘텐츠 속성:
전역 속성
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLLegendElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute HTMLFormElement? form;

  // 이전 멤버들도 포함됩니다
};

legend 요소는 나머지 콘텐츠에 대한 캡션을 나타냅니다 legend 요소의 부모 fieldset 요소가 있는 경우.

legend.form

요소의 form 요소를 반환합니다, 있을 경우, 또는 그렇지 않으면 null을 반환합니다.

form IDL 속성의 동작은 legend 요소가 fieldset 요소 안에 있는지 여부에 따라 다릅니다. legendfieldset 요소를 부모로 가지고 있는 경우, form IDL 속성은 form IDL 속성에서와 동일한 값을 반환해야 합니다 fieldset 요소. 그렇지 않으면 null을 반환해야 합니다.

4.10.17 폼 컨트롤 인프라스트럭처

4.10.17.1 폼 컨트롤의 값

대부분의 폼 컨트롤은 체크 상태를 가집니다. (후자는 input 요소에만 사용됩니다.) 이는 사용자가 컨트롤과 상호작용하는 방식을 설명하는 데 사용됩니다.

컨트롤의 은 내부 상태입니다. 따라서 사용자의 현재 입력과 일치하지 않을 수 있습니다.

예를 들어, 사용자가 숫자를 기대하는 숫자 필드에 "three"라는 단어를 입력하면, 사용자의 입력은 "three"라는 문자열이지만 컨트롤의 은 변경되지 않습니다. 또는 사용자가 "awesome@example.com"(앞에 공백이 있는)을 이메일 필드에 입력하면, 사용자의 입력은 " awesome@example.com"이라는 문자열이지만 브라우저의 이메일 필드 UI는 이를 "awesome@example.com"이라는 으로 변환할 수 있습니다 (앞의 공백 없이).

inputtextarea 요소는 더티 값 플래그를 가집니다. 이는 과 기본 값 사이의 상호작용을 추적하는 데 사용됩니다. 이 값이 false인 경우, 이 기본 값을 반영합니다. true인 경우, 기본 값은 무시됩니다.

input, textareaselect 요소는 사용자 유효성이라는 불리언 값을 가집니다. 이 값은 처음에 false로 설정됩니다.

input 요소의 multiple 속성의 제약 조건 유효성 검사 동작을 정의하기 위해, input 요소는 별도로 정의된 을 가질 수 있습니다.

maxlengthminlength 속성의 동작을 정의하기 위해, 그리고 textarea 요소와 관련된 다른 API를 위해, 모든 값이 있는 폼 컨트롤은 에 대해 API 값을 얻는 알고리즘을 가집니다. 기본적으로 이 알고리즘은 단순히 컨트롤의 을 반환하는 것입니다.

select 요소는 을 가지지 않습니다. 대신 선택 상태option 요소들에서 사용됩니다.

4.10.17.2 변경 가능성

폼 컨트롤은 변경 가능으로 지정될 수 있습니다.

이는 사용자가 폼 컨트롤의 이나 체크 상태를 수정할 수 있는지, 또는 컨트롤이 자동으로 미리 채워질 수 있는지 여부를 결정합니다.

4.10.17.3 컨트롤과 폼의 연관성

폼 연관 요소 요소와의 관계를 가질 수 있으며, 이를 요소의 폼 소유자라고 합니다. 폼 연관 요소 요소와 연관되지 않은 경우, 그 폼 소유자는 null로 간주됩니다.

폼 연관 요소는 연관된 파서 삽입 플래그를 가집니다.

Element/input#form

현재 모든 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Attributes#attr-form

현재 모든 엔진에서 지원합니다.

Firefox1+Safari≤4+Chrome1+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer≤6+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android≤12.1+

폼 연관 요소는 기본적으로 가장 가까운 상위 요소와 연관됩니다(아래 설명 참조), 하지만 리스트된 요소인 경우, 이를 무시하기 위해 form 속성이 지정될 수 있습니다.

이 기능은 중첩된 요소에 대한 지원 부족을 해결하기 위해 저자들에게 유용합니다.

리스트된 폼 연관 요소form 속성을 지정한 경우, 해당 속성의 값은 요소의 ID이어야 합니다. 이 요소는 요소의 트리 내에 있어야 합니다.

이 섹션의 규칙은 중첩된 요소를 포함하지 않는 문서 또는 트리와 관련된 규칙에 의해 복잡해집니다. 그러나 스크립트를 사용하여 DOM 조작을 수행하는 등 중첩된 트리를 생성할 수 있습니다. 또한 HTML 파서에서의 규칙은 역사적인 이유로 인해 폼 연관 요소가 조상의 요소와 연관되지 않을 수 있습니다.

폼 연관 요소가 생성되면, 해당 요소의 폼 소유자는 null(소유자 없음)로 초기화되어야 합니다.

폼 연관 요소가 폼과 연관되도록 설정될 때, 해당 요소의 폼 소유자는 그 폼으로 설정되어야 합니다.

리스트된 폼 연관 요소form 속성이 설정, 변경 또는 제거되면 사용자 에이전트는 해당 요소의 폼 소유자 초기화를 수행해야 합니다.

리스트된 폼 연관 요소form 속성을 가지고 있으며 ID가 있는 요소가 트리 내에서 변경되면, 사용자 에이전트는 해당 폼 연관 요소폼 소유자 초기화를 수행해야 합니다.

리스트된 폼 연관 요소form 속성을 가지고 있으며 ID를 가진 요소가 문서에 삽입되거나 문서에서 제거되면 사용자 에이전트는 해당 폼 연관 요소폼 소유자 초기화를 수행해야 합니다.

폼 소유자는 HTML 표준의 삽입 단계제거 단계에 의해 초기화됩니다.

폼 소유자 초기화폼 연관 요소 요소에서 수행하는 방법:

  1. 요소파서 삽입 플래그를 해제합니다.

  2. 다음이 모두 true일 경우:

    그렇다면 반환합니다.

  3. 요소폼 소유자를 null로 설정합니다.

  4. 요소리스트된 요소이고 form 콘텐츠 속성을 가지며 연결된 경우:

    1. 요소트리에서 트리 순서에 따라 요소form 콘텐츠 속성 값과 동일한 ID를 가진 첫 번째 요소가 요소인 경우, 요소를 해당 요소와 연관시킵니다.

  5. 그렇지 않으면, 요소의 조상 요소가 있는 경우, 해당 요소와 연관시킵니다.

다음의 비준수 코드 스니펫에서

...
 <form id="a">
  <div id="b"></div>
 </form>
 <script>
  document.getElementById('b').innerHTML =
     '<table><tr><td></form><form id="c"><input id="d"></table>' +
     '<input id="e">';
 </script>
...

"d"의 폼 소유자는 내부에 중첩된 폼 "c"가 되고, "e"의 폼 소유자는 외부 폼 "a"가 됩니다.

이 과정은 다음과 같이 진행됩니다: 먼저, "e" 노드는 HTML 파서에서 "c"와 연관됩니다. 그런 다음, innerHTML 알고리즘이 임시 문서에서 "b" 요소로 노드를 이동시킵니다. 이 시점에서 노드들은 조상 체인이 변경되었음을 인식하고, 파서에서 수행된 모든 "마법" 연관이 정상적인 조상 연관으로 재설정됩니다.

이 예제는 비준수 문서로, 요소를 중첩하는 것이 콘텐츠 모델 위반이기 때문에 비준수 코드입니다. 또한 </form> 태그에 대해 구문 오류가 발생합니다.

element.form

HTMLObjectElement/form

현재 모든 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLSelectElement/form

현재 모든 엔진에서 지원합니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

요소의 폼 소유자를 반환합니다.

폼 소유자가 없는 경우 null을 반환합니다.

리스트된 폼 연관 요소들폼 연관 커스텀 요소를 제외하고 form IDL 속성을 가지고 있습니다. 이 속성은 요소의 폼 소유자를 반환해야 하며, 없을 경우 null을 반환해야 합니다.

ElementInternals/form

현재 모든 엔진에서 지원합니다.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

폼 연관 커스텀 요소form IDL 속성을 가지고 있지 않습니다. 대신, 그들의 ElementInternals 객체는 form IDL 속성을 가지고 있습니다. 이 속성을 읽을 때, "NotSupportedError" DOMException이 발생해야 합니다. 만약 대상 요소폼 연관 커스텀 요소가 아니라면, 그렇지 않다면 해당 요소의 폼 소유자를 반환해야 하며, 없을 경우 null을 반환해야 합니다.

4.10.18 폼 컨트롤에 공통된 속성

4.10.18.1 폼 컨트롤의 이름 지정: name 속성

Element/input#name

현재 모든 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

name 콘텐츠 속성은 폼 컨트롤의 이름을 제공하며, 폼 제출form 요소의 elements 객체에서 사용됩니다. 이 속성이 지정된 경우, 값은 빈 문자열이거나 isindex가 되어서는 안 됩니다.

과거 여러 사용자 에이전트는 isindex라는 이름을 가진 폼의 첫 번째 텍스트 컨트롤에 대한 특별한 지원을 구현했습니다. 이 사양은 이전에 관련 사용자 에이전트 요구 사항을 정의했으나, 이후 일부 사용자 에이전트가 그 특별한 지원을 중단하고 관련 요구 사항이 이 사양에서 제거되었습니다. 따라서 레거시 사용자 에이전트에서의 문제가 발생하지 않도록 isindex 이름은 더 이상 허용되지 않습니다.

isindex를 제외하고, name의 모든 비어 있지 않은 값은 허용됩니다. ASCII 대소문자 구분 없이 일치하는 _charset_이라는 이름은 특별합니다. 이 이름이 value 속성이 없는 숨겨진(Hidden) 컨트롤의 이름으로 사용되는 경우, 제출 시 value 속성에 제출 문자 인코딩 값이 자동으로 부여됩니다.

name IDL 속성은 반영해야 합니다. name 콘텐츠 속성을.

DOM 클로버링은 보안 문제의 일반적인 원인입니다. name 콘텐츠 속성에 내장된 폼 속성 이름을 사용하지 않도록 하세요.

이 예에서 input 요소가 내장된 method 속성을 재정의합니다:

let form = document.createElement("form");
let input = document.createElement("input");
form.appendChild(input);

form.method;           // => "get"
input.name = "method"; // DOM 클로버링이 여기에서 발생합니다
form.method === input; // => true

입력 이름이 내장된 폼 속성보다 우선 순위를 가지므로, JavaScript 참조 form.method는 내장된 method 속성 대신 "method"라는 이름의 input 요소를 가리키게 됩니다.

4.10.18.2 요소 방향성 제출: dirname 속성

Element/input#dirname

현재 모든 엔진에서 지원합니다.

Firefox116+Safari6+Chrome17+
Opera12.1+Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

dirname 속성은 폼 컨트롤 요소의 방향성을 제출할 수 있게 하며, 폼 제출 시 이 값을 포함하는 컨트롤의 이름을 지정합니다. 이 속성이 지정된 경우, 그 값은 빈 문자열이 되어서는 안 됩니다.

이 예제에서 폼은 텍스트 컨트롤과 제출 버튼을 포함합니다:

<form action="addcomment.cgi" method=post>
 <p><label>댓글: <input type=text name="comment" dirname="comment.dir" required></label></p>
 <p><button name="mode" type=submit value="add">댓글 게시</button></p>
</form>

사용자가 폼을 제출할 때, 사용자 에이전트는 "comment", "comment.dir" 및 "mode"라는 세 가지 필드를 포함하며, 사용자가 "Hello"라고 입력한 경우 제출 본문은 다음과 같을 수 있습니다:

comment=Hello&comment.dir=ltr&mode=add

사용자가 오른쪽에서 왼쪽으로 쓰는 방향으로 수동으로 전환하고 "مرحبا"를 입력하면, 제출 본문은 다음과 같을 수 있습니다:

comment=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&comment.dir=rtl&mode=add
4.10.18.3 사용자 입력 길이 제한: maxlength 속성

폼 컨트롤 maxlength 속성더티 값 플래그에 의해 제어되며, 사용자가 입력할 수 있는 문자 수에 제한을 둡니다. 문자의 수는 길이를 사용하여 측정되며, textarea 요소의 경우, 모든 줄바꿈이 하나의 문자로 정규화됩니다(CRLF 쌍이 아닌 경우).

요소에 폼 컨트롤 maxlength 속성이 지정된 경우, 해당 속성의 값은 유효한 비음수 정수여야 합니다. 속성이 지정되고 해당 값에 비음수 정수를 파싱하기 위한 규칙을 적용한 결과 숫자가 나오면, 그 숫자가 요소의 최대 허용 값 길이입니다. 속성이 생략되거나 해당 값을 파싱한 결과 오류가 발생하면, 최대 허용 값 길이가 없습니다.

제약 조건 유효성 검사: 요소에 최대 허용 값 길이가 있고, 더티 값 플래그가 true이며, 요소의 이 마지막으로 사용자 편집에 의해 변경되었고(스크립트에 의한 변경이 아닌), 요소의 길이가 요소의 최대 허용 값 길이보다 크면, 그 요소는 너무 길어서 고통받고 있습니다.

사용자 에이전트는 사용자가 요소의 API 값을 요소의 길이가 요소의 최대 허용 값 길이를 초과하는 값으로 설정하지 못하도록 할 수 있습니다.

textarea 요소의 경우, API 값이 다를 수 있습니다. 특히, 줄바꿈 정규화최대 허용 값 길이를 확인하기 전에 적용됩니다(textarea 래핑 변환은 적용되지 않음).

4.10.18.4 최소 입력 길이 요구사항 설정: minlength 속성

폼 컨트롤 minlength 속성더티 값 플래그에 의해 제어되며, 사용자가 입력할 수 있는 문자 수에 대한 하한을 선언합니다. "문자 수"는 길이를 사용하여 측정되며, textarea 요소의 경우, 모든 줄바꿈이 하나의 문자로 정규화됩니다(CRLF 쌍이 아닌 경우).

minlength 속성은 required 속성을 의미하지 않습니다. 폼 컨트롤에 required 속성이 없는 경우 값은 여전히 생략될 수 있으며, minlength 속성은 사용자가 값을 입력한 후에만 작동합니다. 빈 문자열이 허용되지 않는 경우 required 속성도 설정되어야 합니다.

요소에 폼 컨트롤 minlength 속성이 지정된 경우, 해당 속성의 값은 유효한 비음수 정수여야 합니다. 속성이 지정되고 해당 값에 비음수 정수를 파싱하기 위한 규칙을 적용한 결과 숫자가 나오면, 그 숫자가 요소의 최소 허용 값 길이입니다. 속성이 생략되거나 해당 값을 파싱한 결과 오류가 발생하면, 최소 허용 값 길이가 없습니다.

요소에 최대 허용 값 길이최소 허용 값 길이가 모두 있는 경우, 최소 허용 값 길이최대 허용 값 길이보다 작거나 같아야 합니다.

제약 조건 유효성 검사: 요소에 최소 허용 값 길이가 있고, 더티 값 플래그가 true이며, 요소의 이 마지막으로 사용자 편집에 의해 변경되었고(스크립트에 의한 변경이 아닌), 요소의 이 빈 문자열이 아니며, 요소의 길이가 요소의 최소 허용 값 길이보다 작으면, 그 요소는 너무 짧아서 고통받고 있습니다.

다음 예제에서는 네 개의 텍스트 컨트롤이 있습니다. 첫 번째는 필수 항목이며, 최소 5자 이상이어야 합니다. 나머지 세 개는 선택 사항이지만 사용자가 하나를 입력하면 최소 10자를 입력해야 합니다.

<form action="/events/menu.cgi" method="post">
<p><label>행사 이름: <input required minlength=5 maxlength=50 name=event></label></p>
<p><label>아침으로 무엇을 먹고 싶은지 설명하십시오(있다면): <textarea name="breakfast" minlength="10"></textarea></label></p>
<p><label>점심으로 무엇을 먹고 싶은지 설명하십시오(있다면): <textarea name="lunch" minlength="10"></textarea></label></p>
<p><label>저녁으로 무엇을 먹고 싶은지 설명하십시오(있다면): <textarea name="dinner" minlength="10"></textarea></label></p>
<p><input type=submit value="요청 제출"></p>
</form>
4.10.18.5 양식 컨트롤 활성화 및 비활성화: disabled 속성

Attributes/disabled

모든 최신 엔진에서 지원.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Attributes/disabled

모든 최신 엔진에서 지원.

Firefox4+Safari6+Chrome20+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Attributes/disabled

모든 최신 엔진에서 지원.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Attributes/disabled

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Attributes/disabled

모든 최신 엔진에서 지원.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

disabled 콘텐츠 속성은 boolean 속성입니다.

disabled 속성은 option 요소에 대해, 그리고 disabled 속성은 optgroup 요소에 대해 별도로 정의됩니다.

다음 중 하나가 참인 경우 양식 컨트롤은 비활성화됩니다:

비활성화된 양식 컨트롤은 비활성화 상태에서 click 이벤트가 큐에 추가되는 것을 방지해야 합니다.

제약 조건 검증: 요소가 비활성화된 경우, 제약 조건 검증에서 제외됩니다.

HTMLButtonElement/disabled

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLSelectElement/disabled

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

disabled IDL 속성은 반영되어야 합니다. disabled 콘텐츠 속성을 반영해야 합니다.

4.10.18.6 양식 제출 속성

Element/form#Attributes_for_form_submission

모든 최신 엔진에서 지원.

Firefox4+Safari10.1+Chrome10+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?

양식 제출을 위한 속성form 요소와 제출 버튼에 지정할 수 있습니다 (예: input 요소의 type 속성이 제출 버튼 상태에 있는 경우).

양식 제출 속성form 요소에 지정될 수 있는 속성으로는 action, enctype, method, novalidate, 및 target이 있습니다.

해당 양식 제출 속성제출 버튼에 지정될 수 있으며, formaction, formenctype, formmethod, formnovalidate, 및 formtarget이 있습니다. 생략되면, form 요소의 해당 속성에 설정된 값으로 기본 설정됩니다.


Element/input#formaction

모든 최신 엔진에서 지원.

Firefox4+Safari5+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

actionformaction 콘텐츠 속성은, 지정된 경우 유효한 비어있지 않은 URL이면서 공백으로 둘러싸일 수 있는 값을 가져야 합니다.

요소의 action은 해당 요소의 formaction 속성의 값이며, 요소가 제출 버튼이고 해당 속성이 있을 경우, 또는 그 속성 값은 폼 소유자action 속성의 값이 됩니다. 해당 속성이 없다면 빈 문자열이 됩니다.


Element/input#formmethod

모든 최신 엔진에서 지원.

Firefox4+Safari5+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

methodformmethod 콘텐츠 속성은 열거된 속성이며 다음과 같은 키워드와 상태를 가집니다:

키워드 상태 간략 설명
get GET form이 HTTP GET 메서드를 사용함을 나타냅니다.
post POST form이 HTTP POST 메서드를 사용함을 나타냅니다.
dialog Dialog form이 해당 양식이 포함된 대화 상자를 닫기 위한 것임을 나타내며, 그렇지 않으면 제출하지 않습니다.

method 속성의 누락된 값 기본값잘못된 값 기본값 둘 다 GET 상태입니다.

formmethod 속성에는 누락된 값 기본값이 없으며, 잘못된 값 기본값GET 상태입니다.

요소의 method는 이러한 상태 중 하나입니다. 요소가 제출 버튼이고 formmethod 속성이 있는 경우, 해당 요소의 method는 그 속성의 상태입니다. 그렇지 않으면, 폼 소유자method 속성의 상태가 됩니다.

여기에서는 method 속성이 기본 값인 "get"으로 명시적으로 지정되어 검색 쿼리가 URL에 제출됩니다:

<form method="get" action="/search.cgi">
 <p><label>Search terms: <input type=search name=q></label></p>
 <p><input type=submit></p>
</form>

반면, 여기서는 method 속성이 "post" 값으로 지정되어 사용자의 메시지가 HTTP 요청의 본문에 제출됩니다:

<form method="post" action="/post-message.cgi">
 <p><label>Message: <input type=text name=m></label></p>
 <p><input type=submit value="Submit message"></p>
</form>

이 예제에서는 form대화 상자와 함께 사용됩니다. method 속성의 "dialog" 키워드가 사용되어 양식이 제출될 때 대화 상자가 자동으로 닫히도록 합니다.

<dialog id="ship">
 <form method=dialog>
  <p>A ship has arrived in the harbour.</p>
  <button type=submit value="board">Board the ship</button>
  <button type=submit value="call">Call to the captain</button>
 </form>
</dialog>
<script>
 var ship = document.getElementById('ship');
 ship.showModal();
 ship.onclose = function (event) {
   if (ship.returnValue == 'board') {
     // ...
   } else {
     // ...
   }
 };
</script>

Element/input#formenctype

모든 최신 엔진에서 지원.

Firefox4+Safari5+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

enctypeformenctype 콘텐츠 속성은 열거된 속성이며 다음과 같은 키워드와 상태를 가집니다:

속성의 누락된 값 기본값잘못된 값 기본값은 모두 application/x-www-form-urlencoded 상태입니다.

formenctype 속성에는 누락된 값 기본값이 없으며, 잘못된 값 기본값application/x-www-form-urlencoded 상태입니다.

요소의 enctype은 이러한 세 가지 상태 중 하나입니다. 요소가 제출 버튼이고 formenctype 속성이 있는 경우, 해당 요소의 enctype은 그 속성의 상태이며, 그렇지 않으면 폼 소유자enctype 속성의 상태가 됩니다.


Element/input#formtarget

모든 최신 엔진에서 지원.

Firefox4+Safari5+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12.1+

targetformtarget 콘텐츠 속성은, 지정된 경우 유효한 탐색 가능 대상 이름 또는 키워드 값을 가져야 합니다.


Element/input#formnovalidate

모든 최신 엔진에서 지원.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

novalidateformnovalidate 콘텐츠 속성은 boolean 속성입니다. 지정된 경우, 양식 제출 시 검증을 수행하지 않음을 나타냅니다.

요소의 검증 안 함 상태은 요소가 제출 버튼이고 해당 요소의 formnovalidate 속성이 있거나, 요소의 폼 소유자novalidate 속성이 있으면 참이며, 그렇지 않으면 거짓입니다.

이 속성은 검증 제약 조건이 있는 양식에서 "저장" 버튼을 포함하는 데 유용하며, 사용자가 아직 양식의 데이터를 모두 입력하지 않았더라도 진행 상황을 저장할 수 있습니다. 다음 예제는 필수 필드가 두 개인 간단한 양식을 보여줍니다. 세 개의 버튼이 있습니다: 양식을 제출하는 버튼으로, 두 필드를 모두 작성해야 합니다; 나중에 양식을 채우기 위해 사용자가 진행 상황을 저장할 수 있는 버튼; 그리고 양식을 완전히 취소하는 버튼입니다.

<form action="editor.cgi" method="post">
 <p><label>Name: <input required name=fn></label></p>
 <p><label>Essay: <textarea required name=essay></textarea></label></p>
 <p><input type=submit name=submit value="Submit essay"></p>
 <p><input type=submit formnovalidate name=save value="Save essay"></p>
 <p><input type=submit formnovalidate name=cancel value="Cancel"></p>
</form>

HTMLFormElement/action

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLFormElement/target

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLFormElement/method

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLFormElement/enctype

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLFormElement/encoding

모든 최신 엔진에서 지원.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

action IDL 속성은 reflect해야 하며, 동일한 이름의 콘텐츠 속성이며, 콘텐츠 속성이 없거나 값이 빈 문자열인 경우 요소의 노드 문서URL을 반환해야 합니다. target IDL 속성은 동일한 이름의 콘텐츠 속성을 reflect해야 합니다. methodenctype IDL 속성은 동일한 이름의 각각의 콘텐츠 속성을 reflect해야 하며, 알려진 값만으로 제한됩니다. encoding IDL 속성은 reflect해야 하며, enctype 콘텐츠 속성을 알려진 값만으로 제한해야 합니다. noValidate IDL 속성은 reflect해야 하며, novalidate 콘텐츠 속성을 reflect해야 합니다. formAction IDL 속성은 formaction 콘텐츠 속성을 reflect해야 하며, 콘텐츠 속성이 없거나 값이 빈 문자열인 경우 요소의 노드 문서URL을 반환해야 합니다. formEnctype IDL 속성은 reflect해야 하며, formenctype 콘텐츠 속성을 reflect해야 하며, 알려진 값만으로 제한해야 합니다. formMethod IDL 속성은 reflect해야 하며, formmethod 콘텐츠 속성을 reflect해야 하며, 알려진 값만으로 제한해야 합니다. formNoValidate IDL 속성은 reflect해야 하며, formnovalidate 콘텐츠 속성을 reflect해야 합니다. formTarget IDL 속성은 reflect해야 하며, formtarget 콘텐츠 속성을 reflect해야 합니다.

4.10.18.7 자동 완성
4.10.18.7.1 양식 제어 자동 채우기: autocomplete 속성

Attributes/autocomplete

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari6+Chrome14+
Opera12.1+Edge79+
Edge (Legacy)지원 안 됨Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

사용자 에이전트는 종종 사용자가 양식을 채우는 데 도움을 주는 기능을 가지고 있습니다. 예를 들어, 이전 사용자 입력을 기반으로 사용자의 주소를 미리 채울 수 있습니다. autocomplete 콘텐츠 속성은 사용자 에이전트에게 이러한 기능을 제공할 방법 또는 제공 여부에 대한 힌트를 제공하는 데 사용할 수 있습니다.

이 속성이 사용되는 두 가지 방법이 있습니다. 자동 채우기 예상 망토를 입었을 때, autocomplete 속성은 사용자로부터 예상되는 입력을 설명합니다. 자동 채우기 앵커 망토를 입었을 때, autocomplete 속성은 주어진 값의 의미를 설명합니다.

속성의 input 요소의 type 속성이 숨김 상태일 때, autocomplete 속성은 자동 채우기 앵커 망토를 입습니다. 다른 모든 경우에는 자동 채우기 예상 망토를 입습니다.

자동 채우기 예상 망토를 입었을 때, autocomplete 속성은 지정된 경우 공백으로 구분된 토큰 집합으로서, "off" 문자열에 대해 ASCII 대소문자 구분 없음을 가진 단일 토큰이거나 "on" 문자열에 대해 ASCII 대소문자 구분 없음을 가진 단일 토큰, 또는 자동 채우기 세부 토큰으로 구성된 집합이어야 합니다.

자동 채우기 앵커 망토를 입었을 때, autocomplete 속성은 지정된 경우 "자동 채우기 세부 토큰"(즉, "on" 및 "off" 키워드는 허용되지 않음)으로만 구성된 공백으로 구분된 토큰 집합이어야 합니다.

자동 채우기 세부 토큰은 아래 순서대로 다음과 같습니다:

  1. 선택적으로, 첫 8자가 "section-" 문자열과 ASCII 대소문자 구분 없이 일치하는 토큰으로, 해당 필드가 명명된 그룹에 속함을 의미합니다.

    예를 들어, 양식에 두 개의 배송 주소가 있는 경우 다음과 같이 표시할 수 있습니다:

    <fieldset>
         <legend>파란 선물을 배송할 주소...</legend>
         <p> <label> 주소:     <textarea name=ba autocomplete="section-blue shipping street-address"></textarea> </label>
         <p> <label> 도시:        <input name=bc autocomplete="section-blue shipping address-level2"> </label>
         <p> <label> 우편번호: <input name=bp autocomplete="section-blue shipping postal-code"> </label>
        </fieldset>
        <fieldset>
         <legend>빨간 선물을 배송할 주소...</legend>
         <p> <label> 주소:     <textarea name=ra autocomplete="section-red shipping street-address"></textarea> </label>
         <p> <label> 도시:        <input name=rc autocomplete="section-red shipping address-level2"> </label>
         <p> <label> 우편번호: <input name=rp autocomplete="section-red shipping postal-code"> </label> 
        </fieldset>
  2. 선택적으로, 다음 문자열 중 하나와 ASCII 대소문자 구분 없이 일치하는 토큰:

  3. 다음 두 가지 옵션 중 하나:

  4. 선택적으로, "webauthn" 문자열과 ASCII 대소문자 구분 없이 일치하는 토큰으로, 사용자가 양식 컨트롤과 상호작용할 때 사용자 에이전트가 공개 키 자격 증명조건부 중재를 통해 표시해야 함을 의미합니다. webauthninputtextarea 요소에만 유효합니다.

앞서 언급한 바와 같이, 이 속성과 그 키워드의 의미는 속성이 어떤 망토를 입고 있는지에 따라 달라집니다.

자동 채우기 예상 망토를 입고 있을 때 autofill expectation mantle...

"off" 키워드는 컨트롤의 입력 데이터가 특히 민감하거나(예: 핵무기 활성화 코드), 절대로 재사용되지 않는 값(예: 은행 로그인용 일회용 키)이므로 사용자가 값을 미리 입력해 두는 대신 매번 명시적으로 데이터를 입력해야 함을 의미하거나, 문서 자체에서 자동 완성 메커니즘을 제공하고자 하며 사용자 에이전트가 자동 완성 값을 제공하지 않기를 원하는 경우에 사용됩니다.

"on" 키워드는 사용자 에이전트가 사용자에게 자동 완성 값을 제공할 수 있음을 나타내지만, 사용자가 입력할 수 있는 데이터 유형에 대한 추가 정보는 제공하지 않습니다. 사용자 에이전트는 어떤 자동 완성 값을 제안할지 결정하기 위해 휴리스틱을 사용해야 합니다.

위에 나열된 자동 채우기 필드는 사용자 에이전트가 사용자에게 자동 완성 값을 제공할 수 있음을 나타내며, 예상되는 값의 유형을 지정합니다. 이러한 키워드 각각의 의미는 아래 표에서 설명합니다.

autocomplete 속성이 생략된 경우, 요소의 form ownerautocomplete 속성에 해당하는 기본 값이 대신 사용됩니다( "on" 또는 "off"). form owner가 없으면 "on" 값이 사용됩니다.

자동 채우기 앵커 망토를 입고 있을 때 autofill anchor mantle...

위에 나열된 자동 채우기 필드는 특정 값이 이 요소에 제공되었음을 나타냅니다. 이러한 키워드 각각의 의미는 아래 표에서 설명합니다.

이 예제에서는 페이지가 거래의 통화와 금액을 명시적으로 지정했습니다. 양식에서는 신용 카드 및 기타 청구 세부 정보를 요청합니다. 사용자 에이전트는 이 정보를 사용하여 충분한 잔액이 있고 관련 통화를 지원하는 신용 카드를 제안할 수 있습니다.

<form method=post action="step2.cgi">
 <input type=hidden autocomplete=transaction-currency value="CHF">
 <input type=hidden autocomplete=transaction-amount value="15.00">
 <p><label>Credit card number: <input type=text inputmode=numeric autocomplete=cc-number></label>
 <p><label>Expiry Date: <input type=month autocomplete=cc-exp></label>
 <p><input type=submit value="Continue...">
</form>

자동 채우기 필드 키워드는 아래 표에 설명된 대로 서로 관련이 있습니다. 이 표의 각 행에 나열된 필드 이름은 "의미"라는 열에 주어진 설명과 일치합니다. 일부 필드는 다른 필드의 하위 부분과 대응됩니다. 예를 들어, 신용 카드 만료일은 만료 월과 연도를 모두 포함하는 하나의 필드로 표현될 수 있습니다 ("cc-exp") 또는 두 개의 필드로, 하나는 월 ("cc-exp-month")을, 다른 하나는 연도 ("cc-exp-year")를 나타냅니다. 이러한 경우, 더 넓은 필드의 이름은 여러 행에 걸쳐 있으며, 그 안에서 더 좁은 필드가 정의됩니다.

일반적으로 저자들은 더 좁은 필드보다 더 넓은 필드를 사용하는 것이 좋습니다. 더 좁은 필드는 서구적인 편견을 드러내는 경향이 있기 때문입니다. 예를 들어, 서구의 일부 문화에서는 주어진 이름과 성을 순서대로 가지고 있으며(따라서 이름이라고도 함), 많은 문화에서는 성을 먼저 두고 이름을 두 번째로 두며, 다른 많은 문화에서는 단 하나의 이름만 사용하는 경우도 있습니다 (단일명). 따라서 단일 필드를 사용하는 것이 더 유연합니다.

일부 필드는 특정 양식 컨트롤에만 적합합니다. 자동 채우기 필드 이름은 해당 자동 채우기 필드를 설명하는 첫 번째 행의 다섯 번째 열에 나열된 그룹에 해당 컨트롤이 속하지 않는 경우, 그 컨트롤에 대해 부적합한 것입니다. 각 그룹에 어떤 컨트롤이 속하는지는 표 아래에 설명되어 있습니다.

필드 이름 의미 표준 형식 표준 형식 예시 컨트롤 그룹
"name" 전체 이름 자유형 텍스트, 줄 바꿈 없음 Sir Timothy John Berners-Lee, OM, KBE, FRS, FREng, FRSA 텍스트
"honorific-prefix" 접두사 또는 칭호 (예: "Mr.", "Ms.", "Dr.", "Mlle") 자유형 텍스트, 줄 바꿈 없음 Sir 텍스트
"given-name" 이름 (일부 서구 문화에서는 이름으로도 알려져 있음) 자유형 텍스트, 줄 바꿈 없음 Timothy 텍스트
"additional-name" 추가 이름 (일부 서구 문화에서는 중간 이름, 첫 이름 외의 이름으로도 알려져 있음) 자유형 텍스트, 줄 바꿈 없음 John 텍스트
"family-name" 성 (일부 서구 문화에서는 또는 성이름으로도 알려져 있음) 자유형 텍스트, 줄 바꿈 없음 Berners-Lee 텍스트
"honorific-suffix" 접미사 (예: "Jr.", "B.Sc.", "MBASW", "II") 자유형 텍스트, 줄 바꿈 없음 OM, KBE, FRS, FREng, FRSA 텍스트
"nickname" 별명, 스크린 이름, 핸들: 일반적으로 전체 이름 대신 사용되는 짧은 이름 자유형 텍스트, 줄 바꿈 없음 Tim 텍스트
"organization-title" 직책 (예: "Software Engineer", "Senior Vice President", "Deputy Managing Director") 자유형 텍스트, 줄 바꿈 없음 Professor 텍스트
"username" 사용자 이름 자유형 텍스트, 줄 바꿈 없음 timbl 사용자 이름
"new-password" 새 비밀번호 (예: 계정을 생성하거나 비밀번호를 변경할 때) 자유형 텍스트, 줄 바꿈 없음 GUMFXbadyrS3 비밀번호
"current-password" 사용자 이름 필드로 식별된 계정의 현재 비밀번호 (예: 로그인할 때) 자유형 텍스트, 줄 바꿈 없음 qwerty 비밀번호
"one-time-code" 사용자 신원을 확인하는 데 사용되는 일회용 코드 자유형 텍스트, 줄 바꿈 없음 123456 비밀번호
"organization" 이 필드와 연결된 다른 필드에 있는 사람, 주소 또는 연락처 정보에 해당하는 회사 이름 자유형 텍스트, 줄 바꿈 없음 World Wide Web Consortium 텍스트
"street-address" 거리 주소 (여러 줄, 줄 바꿈 유지) 자유형 텍스트 32 Vassar Street
MIT Room 32-G524
멀티라인
"address-line1" 거리 주소 (필드당 한 줄) 자유형 텍스트, 줄 바꿈 없음 32 Vassar Street 텍스트
"address-line2" 자유형 텍스트, 줄 바꿈 없음 MIT Room 32-G524 텍스트
"address-line3" 자유형 텍스트, 줄 바꿈 없음 텍스트
"address-level4" 4단계 행정 구역에서 가장 세분화된 행정 레벨 자유형 텍스트, 줄 바꿈 없음 텍스트
"address-level3" 3단계 행정 레벨, 3개 이상의 행정 레벨이 있는 주소에서 자유형 텍스트, 줄 바꿈 없음 텍스트
"address-level2" 2단계 행정 레벨, 2개 이상의 행정 레벨이 있는 주소에서; 2단계 행정 레벨이 있는 국가에서는, 일반적으로 관련 거리 주소가 있는 시, 마을, 마을 또는 기타 지역 자유형 텍스트, 줄 바꿈 없음 Cambridge 텍스트
"address-level1" 주소의 가장 광범위한 행정 레벨, 즉 해당 지역이 있는 지방; 예를 들어, 미국에서는 주; 스위스에서는 주; 영국에서는 우편 도시 자유형 텍스트, 줄 바꿈 없음 MA 텍스트
"country" 국가 코드 유효한 ISO 3166-1-alpha-2 국가 코드 [ISO3166] US 텍스트
"country-name" 국가 이름 자유형 텍스트, 줄 바꿈 없음; 국가에서 파생된 것 일부 경우에 US 텍스트
"postal-code" 우편번호, 우편 번호, 우편 코드, CEDEX 코드 (CEDEX의 경우, "CEDEX"를 추가하고, 관련 있는 경우 구역주소-레벨2 필드에 추가) 자유형 텍스트, 줄 바꿈 없음 02139 텍스트
"cc-name" 지불 수단에 명시된 전체 이름 자유형 텍스트, 줄 바꿈 없음 Tim Berners-Lee 텍스트
"cc-given-name" 지불 수단에 명시된 이름 (일부 서구 문화에서는 이름으로도 알려져 있음) 자유형 텍스트, 줄 바꿈 없음 Tim 텍스트
"cc-additional-name" 지불 수단에 명시된 추가 이름 (일부 서구 문화에서는 중간 이름으로도 알려져 있음, 첫 이름 외의 이름) 자유형 텍스트, 줄 바꿈 없음 텍스트
"cc-family-name" 지불 수단에 명시된 성 (일부 서구 문화에서는 성이름 또는 으로도 알려져 있음) 자유형 텍스트, 줄 바꿈 없음 Berners-Lee 텍스트
"cc-number" 지불 수단을 식별하는 코드 (예: 신용 카드 번호) ASCII 숫자 4114360123456785 텍스트
"cc-exp" 지불 수단의 만료일 유효한 월 문자열 2014-12
"cc-exp-month" 지불 수단의 만료일의 월 구성 요소 유효한 정수 1..12 범위 내에서 12 숫자
"cc-exp-year" 지불 수단의 만료일의 연도 구성 요소 유효한 정수 0보다 큼 2014 숫자
"cc-csc" 지불 수단의 보안 코드 (카드 보안 코드(CSC), 카드 유효성 검사 코드(CVC), 카드 인증 값(CVV), 서명 패널 코드(SPC), 신용 카드 ID(CCID) 등으로도 알려져 있음) ASCII 숫자 419 텍스트
"cc-type" 지불 수단의 유형 자유형 텍스트, 줄 바꿈 없음 Visa 텍스트
"transaction-currency" 사용자가 거래에 사용할 선호 통화 ISO 4217 통화 코드 [ISO4217] GBP 텍스트
"transaction-amount" 사용자가 거래에 대해 원하는 금액 (예: 입찰 또는 판매 가격을 입력할 때) 유효한 부동 소수점 수 401.00 숫자
"language" 선호하는 언어 유효한 BCP 47 언어 태그 [BCP47] en 텍스트
"bday" 생일 유효한 날짜 문자열 1955-06-08 날짜
"bday-day" 생일의 일 구성 요소 유효한 정수 1..31 범위 내에서 8 숫자
"bday-month" 생일의 월 구성 요소 유효한 정수 1..12 범위 내에서 6 숫자
"bday-year" 생일의 연도 구성 요소 유효한 정수 0보다 큼 1955 숫자
"sex" 성 정체성 (예: Female, Fa'afafine) 자유형 텍스트, 줄 바꿈 없음 Male 텍스트
"url" 이 필드와 연결된 다른 필드에 있는 회사, 사람, 주소 또는 연락처 정보에 해당하는 홈페이지 또는 기타 웹 페이지 유효한 URL 문자열 https://www.w3.org/People/Berners-Lee/ URL
"photo" 이 필드와 연결된 다른 필드에 있는 회사, 사람, 주소 또는 연락처 정보에 해당하는 사진, 아이콘 또는 기타 이미지 유효한 URL 문자열 https://www.w3.org/Press/Stock/Berners-Lee/2001-europaeum-eighth.jpg URL
"tel" 국가 코드를 포함한 전체 전화번호 ASCII 숫자 및 U+0020 SPACE 문자, U+002B PLUS SIGN 문자(+)로 접두어를 붙임 +1 617 253 5702 전화
"tel-country-code" 전화번호의 국가 코드 구성 요소 ASCII 숫자 U+002B PLUS SIGN 문자(+)로 접두어를 붙임 +1 텍스트
"tel-national" 국내 접두사가 적용된 국가 코드 구성 요소가 없는 전화번호 ASCII 숫자 및 U+0020 SPACE 문자 617 253 5702 텍스트
"tel-area-code" 국내 접두사가 적용된 전화번호의 지역 코드 구성 요소 ASCII 숫자 617 텍스트
"tel-local" 국가 코드 및 지역 코드 구성 요소가 없는 전화번호 ASCII 숫자 2535702 텍스트
"tel-local-prefix" 구성 요소가 두 개로 나뉘어 있을 때, 지역 코드 다음에 오는 전화번호 구성 요소의 첫 번째 부분 ASCII 숫자 253 텍스트
"tel-local-suffix" 구성 요소가 두 개로 나뉘어 있을 때, 지역 코드 다음에 오는 전화번호 구성 요소의 두 번째 부분 ASCII 숫자 5702 텍스트
"tel-extension" 전화번호 내선 코드 ASCII 숫자 1000 텍스트
"email" 이메일 주소 유효한 이메일 주소 timbl@w3.org 사용자 이름
"impp" 즉시 메시징 프로토콜 엔드포인트를 나타내는 URL (예: "aim:goim?screenname=example" 또는 "xmpp:fred@example.net") 유효한 URL 문자열 irc://example.org/timbl,isuser URL

그룹은 다음과 같은 컨트롤에 해당합니다:

텍스트
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
textarea 요소들
select 요소들
다중라인
input 요소로 type 속성이 숨김 상태에 있는 요소들
textarea 요소들
select 요소들
비밀번호
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 비밀번호 상태에 있는 요소들
textarea 요소들
select 요소들
URL
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 URL 상태에 있는 요소들
textarea 요소들
select 요소들
사용자 이름
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 이메일 상태에 있는 요소들
textarea 요소들
select 요소들
전화번호
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 전화 상태에 있는 요소들
textarea 요소들
select 요소들
숫자
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 숫자 상태에 있는 요소들
textarea 요소들
select 요소들
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 상태에 있는 요소들
textarea 요소들
select 요소들
날짜
input 요소로 type 속성이 숨김 상태에 있는 요소들
input 요소로 type 속성이 텍스트 상태에 있는 요소들
input 요소로 type 속성이 검색 상태에 있는 요소들
input 요소로 type 속성이 날짜 상태에 있는 요소들
textarea 요소들
select 요소들

주소 레벨: "주소 레벨 1" – "주소 레벨 4" 필드는 도로 주소의 지역성을 설명하는 데 사용됩니다. 각 지역마다 레벨 수가 다릅니다. 예를 들어, 미국은 두 개의 레벨(주와 마을)을 사용하고, 영국은 주소에 따라 한 개 또는 두 개(우편 마을, 경우에 따라 지역)를 사용하며, 중국은 세 개(도, 시, 구)를 사용할 수 있습니다. "주소 레벨 1" 필드는 가장 넓은 행정 구역을 나타냅니다. 지역마다 필드를 배열하는 방식이 다릅니다. 예를 들어, 미국에서는 마을(레벨 2)이 주(레벨 1) 앞에 오지만, 일본에서는 도(레벨 1)가 도시(레벨 2) 앞에 오며, 그 뒤에 구(레벨 3)가 옵니다. 저자는 사용자가 국가를 변경할 때마다 필드를 숨기거나, 표시하거나, 재배치하는 방식으로 국가의 관례에 맞게 양식을 제공하는 것이 좋습니다.

4.10.18.7.2 처리 모델

input 요소에 autocomplete 속성이 적용되며, 각 select 요소 및 각 textarea 요소는 자동 완성 힌트 세트, 자동 완성 범위, 자동 완성 필드 이름, 비자동 완성 자격 유형, IDL에 노출된 자동 완성 값을 가지고 있습니다.

자동 완성 필드 이름은 필드에서 기대되는 특정 데이터 종류를 지정하며, 예를 들어 "street-address" 또는 "cc-exp"와 같은 것입니다.

자동 완성 힌트 세트는 사용자 에이전트가 참고해야 할 주소나 연락처 정보 유형을 식별하며, 예를 들어 "shipping fax" 또는 "billing"와 같습니다.

비자동 완성 자격 유형은 사용자가 필드와 상호작용할 때 사용자 에이전트가 제공할 수 있는 자격 유형을 식별합니다. 이 값이 "webauthn"이고 null이 아닌 경우, 해당 유형의 자격을 선택하면 보류 중인 조건부 중재 navigator.credentials.get() 요청을 해결하게 됩니다.

예를 들어, 로그인 페이지는 사용자 에이전트에게 저장된 비밀번호를 자동으로 완성하거나, 보류 중인 공개 키 자격을 보여줄 수 있으며, 사용자는 로그인 시 어느 하나를 선택할 수 있습니다.

<input name=password type=password autocomplete="current-password webauthn">

자동 완성 범위는 동일한 주체와 관련된 정보 필드 그룹을 식별하며, 자동 완성 힌트 세트와, 해당하는 경우 "section-*" 접두어로 구성됩니다. 예를 들어 "billing", "section-parent shipping", 또는 "section-child shipping home"와 같습니다.

이 값들은 다음 알고리즘을 실행한 결과로 정의됩니다:

  1. 요소에 autocomplete 속성이 없으면, default로 표시된 단계로 이동합니다.

  2. tokens을(를) 속성 값에서 ASCII 공백을 기준으로 분할한 결과로 설정합니다.

  3. tokens이(가) 비어 있으면, default로 표시된 단계로 이동합니다.

  4. indextokens에서 마지막 토큰의 인덱스로 설정합니다.

  5. fieldtokens에서 index번째 토큰으로 설정합니다.

  6. category, maximum tokens 쌍을 field에 주어진 필드의 범주를 결정하는 결과로 설정합니다.

  7. category이(가) null이면, default로 표시된 단계로 이동합니다.

  8. tokens의 토큰 수가 maximum tokens보다 많으면, default로 표시된 단계로 이동합니다.

  9. category가 Off 또는 Automatic이고 요소의 autocomplete 속성이 autofill anchor mantle을 착용하고 있는 경우, default로 표시된 단계로 이동합니다.

  10. category가 Off인 경우, 요소의 autofill 필드 이름을 "off" 문자열로 설정하고, autofill 힌트 세트를 비워두며, IDL 노출 autofill 값을 "off" 문자열로 설정합니다. 그런 다음, 종료합니다.

  11. category가 Automatic인 경우, 요소의 autofill 필드 이름을 "on" 문자열로 설정하고, autofill 힌트 세트를 비워두며, IDL 노출 autofill 값을 "on" 문자열로 설정합니다. 그런 다음, 종료합니다.

  12. scope tokens을(를) 빈 리스트로 설정합니다.

  13. hint tokens을(를) 빈 세트로 설정합니다.

  14. credential type을(를) null로 설정합니다.

  15. IDL value을(를) field와 동일한 값으로 설정합니다.

  16. category가 Credential이고 tokens에서 index번째 토큰이 "webauthn"와 ASCII 대소문자 구분 없이 일치하는 경우, 다음 하위 단계를 수행합니다:

    1. credential type을 "webauthn"으로 설정합니다.

    2. tokens에서 index번째 토큰이 첫 번째 항목인 경우, done로 표시된 단계로 건너뜁니다.

    3. index을(를) 하나 감소시킵니다.

    4. category, maximum tokens 쌍을 tokens에서 index번째 토큰에 주어진 필드의 범주를 결정하는 결과로 설정합니다.

    5. category가 Normal 또는 Contact이 아니면, default로 표시된 단계로 이동합니다.

    6. indexmaximum tokens에서 1을 뺀 값보다 크면(즉, 남은 토큰 수가 maximum tokens보다 많으면), default로 표시된 단계로 이동합니다.

    7. IDL value을(를) tokens에서 index번째 토큰, U+0020 SPACE 문자 및 이전 IDL value의 값을 연결한 값으로 설정합니다.

  17. tokens에서 index번째 토큰이 첫 번째 항목인 경우, done로 표시된 단계로 건너뜁니다.

  18. index을(를) 하나 감소시킵니다.

  19. category가 Contact이고 tokens에서 index번째 토큰이 다음 목록에 있는 문자열 중 하나와 ASCII 대소문자 구분 없이 일치하는 경우, 다음 하위 단계를 수행합니다:

    하위 단계는 다음과 같습니다:

    1. contact을(를) 위 목록에서 일치하는 문자열로 설정합니다.

    2. contact을(를) scope tokens의 시작 부분에 삽입합니다.

    3. contact을(를) hint tokens에 추가합니다.

    4. IDL value을(를) contact, U+0020 SPACE 문자 및 이전 IDL value의 값을 연결한 값으로 설정합니다.

    5. tokens에서 index번째 항목이 첫 번째 항목인 경우, done로 표시된 단계로 건너뜁니다.

    6. index을(를) 하나 감소시킵니다.

  20. tokens에서 index번째 토큰이 다음 목록에 있는 문자열 중 하나와 ASCII 대소문자 구분 없이 일치하는 경우, 다음 하위 단계를 수행합니다:

    하위 단계는 다음과 같습니다:

    1. mode을(를) 위 목록에서 일치하는 문자열로 설정합니다.

    2. mode을(를) scope tokens의 시작 부분에 삽입합니다.

    3. mode을(를) hint tokens에 추가합니다.

    4. IDL value을(를) mode, U+0020 SPACE 문자 및 이전 IDL value의 값을 연결한 값으로 설정합니다.

    5. tokens에서 index번째 항목이 첫 번째 항목인 경우, done로 표시된 단계로 건너뜁니다.

    6. index을(를) 하나 감소시킵니다.

  21. tokens에서 index번째 항목이 첫 번째 항목이 아닌 경우, default로 표시된 단계로 이동합니다.

  22. tokens에서 index번째 토큰의 첫 여덟 글자가 "section-" 문자열과 ASCII 대소문자 구분 없이 일치하지 않으면, default로 표시된 단계로 이동합니다.

  23. section을(를) tokens에서 index번째 토큰, ASCII 소문자로 변환된 값으로 설정합니다.

  24. section을(를) scope tokens의 시작 부분에 삽입합니다.

  25. IDL value을(를) section, U+0020 SPACE 문자 및 이전 IDL value의 값을 연결한 값으로 설정합니다.

  26. 완료: 요소의 autofill 힌트 세트hint tokens로 설정합니다.

  27. 요소의 비-autofill 자격 증명 유형credential type으로 설정합니다.

  28. 요소의 autofill 범위scope tokens으로 설정합니다.

  29. 요소의 autofill 필드 이름field로 설정합니다.

  30. 요소의 IDL 노출 autofill 값IDL value로 설정합니다.

  31. 종료합니다.

  32. 기본값: 요소의 IDL 노출 autofill 값을 빈 문자열로 설정하고, autofill 힌트 세트autofill 범위를 비웁니다.

  33. 요소의 autocomplete 속성이 autofill anchor mantle을 착용하고 있는 경우, 요소의 autofill 필드 이름을 빈 문자열로 설정하고 종료합니다.

  34. form을(를) 요소의 양식 소유자로 설정하되, 해당 소유자가 없으면 null로 설정합니다.

  35. form이 null이 아니고 formautocomplete 속성이 off 상태에 있으면, 요소의 autofill 필드 이름을 "off"로 설정합니다.

    그렇지 않으면, 요소의 autofill 필드 이름을 "on"으로 설정합니다.

field을(를) 주어진 상태에서 필드의 범주를 결정하기:

  1. field이(가) 다음 표의 첫 번째 열에 주어진 토큰 중 하나와 ASCII 대소문자 구분 없이 일치하지 않으면, 쌍 (null, null)을 반환합니다.

    토큰 최대 토큰 수 범주
    "off" 1 Off
    "on" 1 Automatic
    "name" 3 Normal
    "honorific-prefix" 3 Normal
    "given-name" 3 Normal
    "additional-name" 3 Normal
    "family-name" 3 Normal
    "honorific-suffix" 3 Normal
    "nickname" 3 Normal
    "organization-title" 3 Normal
    "username" 3 Normal
    "new-password" 3 Normal
    "current-password" 3 Normal
    "one-time-code" 3 Normal
    "organization" 3 Normal
    "street-address" 3 Normal
    "address-line1" 3 Normal
    "address-line2" 3 Normal
    "address-line3" 3 Normal
    "address-level4" 3 Normal
    "address-level3" 3 Normal
    "address-level2" 3 Normal
    "address-level1" 3 Normal
    "country" 3 Normal
    "country-name" 3 Normal
    "postal-code" 3 Normal
    "cc-name" 3 Normal
    "cc-given-name" 3 Normal
    "cc-additional-name" 3 Normal
    "cc-family-name" 3 Normal
    "cc-number" 3 Normal
    "cc-exp" 3 Normal
    "cc-exp-month" 3 Normal
    "cc-exp-year" 3 Normal
    "cc-csc" 3 Normal
    "cc-type" 3 Normal
    "transaction-currency" 3 Normal
    "transaction-amount" 3 Normal
    "language" 3 Normal
    "bday" 3 Normal
    "bday-day" 3 Normal
    "bday-month" 3 Normal
    "bday-year" 3 Normal
    "sex" 3 Normal
    "url" 3 Normal
    "photo" 3 Normal
    "tel" 4 Contact
    "tel-country-code" 4 Contact
    "tel-national" 4 Contact
    "tel-area-code" 4 Contact
    "tel-local" 4 Contact
    "tel-local-prefix" 4 Contact
    "tel-local-suffix" 4 Contact
    "tel-extension" 4 Contact
    "email" 4 Contact
    "impp" 4 Contact
    "webauthn" 5 Credential
  2. 그렇지 않은 경우, maximum tokenscategory을(를) 해당 행의 두 번째 및 세 번째 열에 있는 값으로 설정합니다.

  3. 쌍 (category, maximum tokens)을 반환합니다.


자동 완성의 목적을 위해, 컨트롤의 데이터는 컨트롤의 종류에 따라 달라집니다:

input 요소로, type 속성이 Email 상태에 있으며 multiple 속성이 지정된 경우
요소의 s입니다.
다른 모든 input 요소
textarea 요소
요소의 입니다.
select 요소로, multiple 속성이 지정된 경우
option 요소들 중에서 옵션 목록에서 선택 여부가 true로 설정된 항목입니다.
다른 모든 select 요소
option 요소로, 옵션 목록에서 선택 여부가 true로 설정된 항목입니다.

자동 완성 힌트 세트, 자동 완성 범위, 및 자동 완성 필드 이름을 처리하는 방법은 자동 완성 속성이 착용한 맨틀에 따라 달라집니다.

자동 완성 기대 맨틀을 착용할 때...

요소의 자동 완성 필드 이름이 "off"인 경우, 사용자 에이전트는 컨트롤의 데이터를 기억하지 않아야 하며, 이전 값을 사용자에게 제안하지 않아야 합니다.

또한, 요소의 자동 완성 필드 이름이 "off"인 경우, 값이 초기화됩니다 문서를 다시 활성화할 때.

은행은 자주 사용자 에이전트가 로그인 정보를 미리 채우는 것을 원하지 않습니다:

<p><label>Account: <input type="text" name="ac" autocomplete="off"></label></p>
<p><label>PIN: <input type="password" name="pin" autocomplete="off"></label></p>

요소의 자동 완성 필드 이름이 "off"가 아닌 경우, 사용자 에이전트는 컨트롤의 데이터를 저장하고, 이전에 저장된 값을 사용자에게 제안할 수 있습니다.

예를 들어, 사용자가 이 컨트롤이 포함된 페이지를 방문했다고 가정해 봅시다:

<select name="country">
 <option>Afghanistan</option>
 <option>Albania</option>
 <option>Algeria</option>
 <option>Andorra</option>
 <option>Angola</option>
 <option>Antigua and Barbuda</option>
 <option>Argentina</option>
 <option>Armenia</option>
 <!-- ... -->
 <option>Yemen</option>
 <option>Zambia</option>
 <option>Zimbabwe</option>
</select>

이것은 다음과 같이 렌더링될 수 있습니다:

알파벳순으로 나열된 국가 목록이 있는 드롭다운 컨트롤.

이 페이지를 처음 방문했을 때 사용자가 "Zambia"를 선택했다고 가정합니다. 두 번째 방문 시, 사용자 에이전트는 목록의 맨 위에 "Zambia" 항목을 복제하여 인터페이스가 다음과 같이 보이도록 할 수 있습니다:

알파벳순으로 나열된 국가 목록이 있는 동일한 드롭다운 컨트롤, 하지만 Zambia가 맨 위에 위치해 있음.

자동 완성 필드 이름이 "on"인 경우, 사용자 에이전트는 요소의 name 값, 요소의 트리 내 위치, 양식 내 다른 필드 등을 기반으로 사용자에게 가장 적절한 값을 제공하기 위해 휴리스틱을 사용해야 합니다.

자동 완성 필드 이름이 위에서 설명한 자동 완성 필드 중 하나인 경우, 사용자 에이전트는 필드 이름의 의미에 맞는 제안을 제공해야 합니다. 자동 완성 힌트 세트는 여러 가능한 제안 중에서 선택하는 데 사용되어야 합니다.

예를 들어, 사용자가 한 번은 "shipping" 키워드를 사용한 필드에 한 주소를 입력하고, "billing" 키워드를 사용한 필드에 다른 주소를 입력했다면, 이후 양식에서는 "자동 완성 힌트 세트"에 "shipping" 키워드가 포함된 경우에만 첫 번째 주소가 제안됩니다. 반면, 자동 완성 힌트 세트에 이러한 키워드가 포함되지 않은 주소 관련 필드에서는 두 주소가 모두 제안될 수 있습니다.

자동 완성 앵커 맨틀을 착용할 때...

자동 완성 필드 이름이 빈 문자열이 아닌 경우, 사용자 에이전트는 주어진 컨트롤의 데이터, 자동 완성 힌트 세트, 자동 완성 범위자동 완성 필드 이름 조합에 대해 사용자가 명시한 것처럼 행동해야 합니다.

사용자 에이전트가 양식 컨트롤을 자동 완성할 때, 동일한 양식 소유자와 동일한 자동 완성 범위를 가진 요소들은 동일한 사람, 주소, 결제 수단, 연락처 정보와 관련된 데이터를 사용해야 합니다. 사용자 에이전트가 동일한 양식 소유자자동 완성 범위를 가진 "country" 및 "country-name" 필드를 자동 완성할 때, 사용자 에이전트가 "country" 필드에 대한 값을 가지고 있다면, "country-name" 필드는 동일한 국가에 대한 사람이 읽을 수 있는 이름으로 채워져야 합니다. 사용자 에이전트가 여러 필드를 한 번에 채울 때, 동일한 자동 완성 필드 이름, 양식 소유자, 자동 완성 범위를 가진 모든 필드는 동일한 값으로 채워져야 합니다.

예를 들어, 사용자 에이전트가 +1 555 123 1234와 +1 555 666 7777이라는 두 개의 전화번호를 알고 있다고 가정합니다. 자동 완성을 하는 과정에서 autocomplete="shipping tel-local-prefix" 필드에 "123" 값을, 동일한 양식 내 다른 필드에 autocomplete="shipping tel-local-suffix" 값을 "7777"으로 채우는 것은 적합하지 않습니다. 위에 언급된 정보에 따라 유효한 자동 완성 값은 각각 "123"과 "1234" 또는 "666"과 "7777"이어야 합니다.

비슷하게, 어떤 이유로 양식에 "cc-exp" 필드와 "cc-exp-month" 필드가 모두 포함되어 있고, 사용자 에이전트가 양식을 미리 채운다면, 전자의 월 구성 요소는 후자와 일치해야 합니다.

이 요구사항은 자동 완성 앵커 맨틀과도 상호작용합니다. 다음 마크업 스니펫을 고려해 보십시오:

<form>
 <input type="hidden" autocomplete="nickname" value="TreePlate">
 <input type="text" autocomplete="nickname">
</form>

준수하는 사용자 에이전트가 텍스트 컨트롤에 제안할 수 있는 유일한 값은 숨겨진 input 요소에서 제공된 값인 "TreePlate"입니다.

"section-*" 토큰은 자동 완성 범위에서 불투명하며, 사용자 에이전트는 이러한 토큰의 정확한 값에서 의미를 도출하려고 해서는 안 됩니다.

예를 들어, 사용자 에이전트가 "section-child"에 대해 사용자의 자녀의 주소를 제안하고 "section-spouse"에 대해 사용자의 배우자의 주소를 제안하기로 결정하는 것은 준수하지 않을 것입니다.

자동 완성 메커니즘은 사용자 에이전트가 사용자가 컨트롤의 데이터를 수정한 것처럼 행동하고, 요소가 변경 가능한 상태 (예: 요소가 문서에 삽입된 직후 또는 사용자 에이전트가 구문 분석을 중지할 때)일 때 수행되어야 합니다. 사용자 에이전트는 사용자가 입력할 수 있었던 값만 사용하여 컨트롤을 미리 채워야 합니다.

예를 들어, select 요소에 "Steve", "Rebecca", "Jay", "Bob" 값만 있는 option 요소들이 있고, 자동 완성 필드 이름이 "given-name"로 되어 있으며, 사용자 에이전트가 자동 완성하려고 하는 유일한 값이 "Evan"인 경우, 사용자 에이전트는 필드를 미리 채울 수 없습니다. 사용자가 직접 그렇게 할 수 없었기 때문에, 사용자 에이전트가 어떻게든 select 요소를 "Evan" 값으로 설정하는 것은 준수하지 않을 것입니다.

양식 컨트롤을 미리 채우는 사용자 에이전트는 문서 트리 내에 있는 양식 컨트롤과 연결된 양식 컨트롤 간에 차별해서는 안 됩니다; 즉, 요소의 루트섀도우 루트인지 document인지에 따라 자동 완성 여부를 결정하는 것은 준수하지 않습니다.

양식 컨트롤의 을 미리 채우는 사용자 에이전트는 해당 컨트롤이 유형 불일치로 인한 문제, 너무 길어짐으로 인한 문제, 너무 짧아짐으로 인한 문제, 언더플로우로 인한 문제, 오버플로우로 인한 문제, 단계 불일치로 인한 문제를 겪지 않도록 해야 합니다. 또한, 사용자 에이전트는 패턴 불일치로 인한 문제를 유발해서는 안 됩니다. 컨트롤의 제약 사항을 고려하여 가능한 경우, 사용자 에이전트는 이전에 언급된 표에서 정식으로 제공된 형식을 사용해야 합니다. 정식 형식을 사용할 수 없는 경우, 사용자 에이전트는 값을 변환하여 사용할 수 있도록 휴리스틱을 사용해야 합니다.

예를 들어, 사용자 에이전트가 사용자의 중간 이름이 "Ines"라는 것을 알고 있고, 다음과 같은 양식 컨트롤을 미리 채우려고 한다고 가정해 보십시오:

<input name="middle-initial" maxlength="1" autocomplete="additional-name">

...이 경우, 사용자 에이전트는 "Ines"를 "I"로 변환하여 미리 채울 수 있습니다.

더 정교한 예로는 월 값이 있을 수 있습니다. 사용자 에이전트가 사용자의 생일이 2012년 7월 27일이라는 것을 알고 있다면, 다음과 같이 약간 다른 값을 가지고 모든 컨트롤을 미리 채우려고 할 수 있습니다:

<input name="b" type="month" autocomplete="bday">
2012-07 일은 생략됩니다. 왜냐하면 상태는 월/년 조합만을 허용하기 때문입니다. (이 예는 준수하지 않는데, 그 이유는 자동 완성 필드 이름 bday 상태와 허용되지 않기 때문입니다.)
<select name="c" autocomplete="bday">
 <option>Jan</option>
 <option>Feb</option>
 <!-- ... -->
 <option>Jul</option>
 <option>Aug</option>
 <!-- ... -->
</select>
7월 사용자 에이전트는 열두 개의 옵션이 있는 것을 확인하고 7번째를 선택하거나, "Jul"이라는 문자열(세 글자 "Jul" 다음에 줄 바꿈 및 공백)이 사용자 에이전트의 지원 언어 중 하나로 월 이름(July)과 가까운 일치라고 인식하거나, 다른 유사한 메커니즘을 통해 옵션 목록에서 월을 선택합니다.
<input name="a" type="number" min="1" max="12" autocomplete="bday-month">
7 사용자 에이전트는 "July"를 1..12 범위의 월 숫자로 변환하여 필드를 채웁니다.
<input name="a" type="number" min="0" max="11" autocomplete="bday-month">
6 사용자 에이전트는 "July"를 0..11 범위의 월 숫자로 변환하여 필드를 채웁니다.
<input name="a" type="number" min="1" max="11" autocomplete="bday-month">
사용자 에이전트는 양식이 기대하는 내용을 잘 추측할 수 없기 때문에 필드를 채우지 않습니다.

사용자 에이전트는 사용자가 요소의 자동 완성 필드 이름을 무시하도록 허용할 수 있습니다. 예를 들어, 페이지 작성자의 반대에도 불구하고 값을 기억하고 미리 채울 수 있도록 "off"에서 "on"으로 변경하거나, 값을 절대 기억하지 않도록 항상 "off"로 설정할 수 있습니다.

더 구체적으로, 사용자 에이전트는 특히 다음 표의 첫 번째 열에 주어진 설명과 일치하는 양식 컨트롤의 자동 완성 필드 이름을 "on" 또는 "off"인 경우, 해당 행의 두 번째 셀에 주어진 값으로 교체하는 것을 고려할 수 있습니다. 이 표가 사용되는 경우, 모든 행을 트리 순서로 교체해야 합니다. 첫 번째 행을 제외한 모든 행은 이전 요소의 자동 완성 필드 이름을 참조합니다. 아래 설명에서 양식 컨트롤이 다른 요소 앞이나 뒤에 위치한다고 할 때, 이는 동일한 양식 소유자를 공유하는 목록에 있는 요소들을 의미합니다.

양식 컨트롤 새로운 자동 완성 필드 이름
input 요소로, type 속성이 Text 상태에 있고, 뒤에 input 요소가 있으며, type 속성이 Password 상태에 있습니다. "username"
input 요소로, type 속성이 Password 상태에 있고, 앞에 input 요소가 있으며, 자동 완성 필드 이름이 "username"입니다. "current-password"
input 요소로, type 속성이 Password 상태에 있고, 앞에 input 요소가 있으며, 자동 완성 필드 이름이 "current-password"입니다. "new-password"
input 요소로, type 속성이 Password 상태에 있고, 앞에 input 요소가 있으며, 자동 완성 필드 이름이 "new-password"입니다. "new-password"

autocomplete IDL 속성은 가져올 때 요소의 IDL로 노출된 자동 완성 값을 반환해야 하며, 설정할 때는 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

4.10.19 텍스트 컨트롤 선택을 위한 API

inputtextarea 요소는 선택을 처리하기 위한 여러 속성과 메서드를 정의합니다. 이들의 공통 알고리즘은 여기에서 정의됩니다.

element.select()

텍스트 컨트롤의 모든 내용을 선택합니다.

element.selectionStart [ = value ]

선택의 시작 오프셋을 반환합니다.

선택의 시작을 변경하기 위해 설정할 수 있습니다.

element.selectionEnd [ = value ]

선택의 끝 오프셋을 반환합니다.

선택의 끝을 변경하기 위해 설정할 수 있습니다.

element.selectionDirection [ = value ]

선택의 현재 방향을 반환합니다.

선택의 방향을 변경하기 위해 설정할 수 있습니다.

가능한 값은 "forward", "backward", "none"입니다.

element.setSelectionRange(start, end [, direction])

HTMLInputElement/setSelectionRange

모든 현재 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

선택을 주어진 방향의 하위 문자열을 포함하도록 변경합니다. 방향이 생략되면 기본 플랫폼 값(없음 또는 forward)으로 재설정됩니다.

element.setRangeText(replacement [, start, end [, selectionMode ] ])

HTMLInputElement/setRangeText

모든 현재 엔진에서 지원됨.

Firefox27+Safari7+Chrome24+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

텍스트 범위를 새 텍스트로 대체합니다. startend 인수가 제공되지 않은 경우 범위는 선택으로 간주됩니다.

마지막 인수는 텍스트가 대체된 후 선택이 어떻게 설정될지를 결정합니다. 가능한 값은 다음과 같습니다:

"select"
새로 삽입된 텍스트를 선택합니다.
"start"
선택을 삽입된 텍스트 바로 앞에 이동시킵니다.
"end"
선택을 선택된 텍스트 바로 뒤로 이동시킵니다.
"preserve"
선택을 유지하려고 시도합니다. 이것이 기본값입니다.

모든 input 요소와 이 API가 적용되는 모든 textarea 요소는 항상 선택 또는 텍스트 입력 커서 위치를 가지고 있으며, 이는 제어의 코드 유닛의 오프셋으로 측정됩니다. 초기 상태는 제어의 시작 부분에 텍스트 입력 커서로 구성되어야 합니다.

이 API는 input 요소의 에 대해 작동해야 하며, textarea 요소의 경우, 이 API는 요소의 API 값에 대해 작동해야 합니다. 아래 알고리즘에서, 우리가 작업 중인 값 문자열을 관련 값이라고 부릅니다.

API 값 대신 원시 값을 사용하는 것은 U+000D (CR) 문자가 정규화된다는 것을 의미합니다. 예를 들어,

<textarea id="demo"></textarea>
<script>
 demo.value = "A\r\nB";
 demo.setRangeText("replaced", 0, 2);
 assert(demo.value === "replacedB");
</script>

원시 값 "A\r\nB"에 대해 작업했다면, "A\r" 문자를 대체하여 "replaced\nB"의 결과를 얻었을 것입니다. 그러나 "A\nB"의 API 값을 사용했기 때문에 "A\n" 문자를 대체하여 "replacedB"를 얻었습니다.

U+200D ZERO WIDTH JOINER와 같이 보이지 않는 렌더링을 가진 문자도 여전히 문자로 계산됩니다. 따라서 예를 들어, 선택은 보이지 않는 문자만을 포함할 수 있으며, 텍스트 삽입 커서는 그러한 문자의 한쪽 또는 다른 쪽에 배치될 수 있습니다.

이 API가 적용되는 요소에 대해 관련 값이 변경될 때마다 다음 단계를 실행합니다:

  1. 요소에 선택이 있는 경우:

    1. 선택의 시작이 이제 관련 값의 끝을 지나면, 이를 관련 값의 끝으로 설정합니다.

    2. 선택의 끝이 이제 관련 값의 끝을 지나면, 이를 관련 값의 끝으로 설정합니다.

    3. 사용자 에이전트가 빈 선택을 지원하지 않으며, 선택의 시작과 끝이 모두 관련 값의 끝을 가리키는 경우, 대신 요소의 텍스트 입력 커서 위치관련 값의 끝으로 설정하고, 선택을 제거합니다.

  2. 그렇지 않으면, 요소는 텍스트 입력 커서 위치를 가져야 합니다. 이제 이것이 관련 값의 끝을 지났다면, 이를 관련 값의 끝으로 설정합니다.

관련 값이 변경되는 경우에 따라, 사양의 다른 부분에서도 위의 클램핑 단계 외에 텍스트 입력 커서 위치를 수정할 수 있습니다. 예를 들어, value 세터를 참고하세요.

가능한 경우, inputtextarea 요소의 텍스트 선택을 변경하기 위한 사용자 인터페이스 기능은 선택 범위 설정 알고리즘을 사용하여 구현해야 합니다. 예를 들어, 모든 동일한 이벤트가 발생하도록 합니다.

inputtextarea 요소의 선택에는 "forward", "backward", "none" 중 하나의 선택 방향이 있습니다. 선택 방향의 정확한 의미는 플랫폼에 따라 다릅니다. 이 방향은 사용자가 선택을 조작할 때 설정됩니다. 초기 선택 방향은 플랫폼이 그 방향을 지원하면 "none", 그렇지 않으면 "forward"여야 합니다.

요소의 선택 방향을 주어진 방향으로 설정하려면, 플랫폼이 그 방향을 지원하지 않으면 "none"으로 설정하고, 그렇지 않으면 요소의 선택 방향을 주어진 방향으로 업데이트합니다. 그렇지 않으면, 요소의 선택 방향을 "forward"로 업데이트합니다.

Windows에서는 방향이 선택과의 관계에서 캐럿의 위치를 나타냅니다: "forward" 선택은 선택의 끝에 캐럿이 있고, "backward" 선택은 선택의 시작에 캐럿이 있습니다. Windows에는 "none" 방향이 없습니다.

Mac에서는 방향이 사용자가 Shift 수정자를 사용하여 화살표 키로 선택의 크기를 조정할 때 영향을 받는 선택의 끝을 나타냅니다: "forward" 방향은 선택의 끝이 수정됨을 의미하고, "backward" 방향은 선택의 시작이 수정됨을 의미합니다. Mac의 기본 방향은 "none"으로, 아직 특정 방향이 선택되지 않았음을 나타냅니다. 사용자는 첫 번째 방향 화살표 키를 사용하여 선택을 조정할 때 방향을 암묵적으로 설정합니다.

HTMLInputElement/select

모든 현재 엔진에서 지원됨.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLInputElement/select

select() 메서드는 호출될 때 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, select()가 이 요소에 적용되지 않거나 해당 컨트롤에 선택할 수 있는 텍스트가 없으면, 반환합니다.

    예를 들어, <input type=color>이 텍스트 컨트롤이 아닌 색상 코드를 허용하는 헥사 값 입력으로 렌더링된 사용자 에이전트에서는 선택할 수 있는 텍스트가 없으므로 메서드 호출이 무시됩니다.

  2. 선택 범위 설정을 0 및 무한대로 설정합니다.

selectionStart 속성의 getter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, selectionStart가 이 요소에 적용되지 않으면, null을 반환합니다.

  2. 선택이 없으면, 코드 유닛 오프셋을 관련 값 내에서 텍스트 입력 커서 뒤에 있는 문자로 반환합니다.

  3. 코드 유닛 오프셋을 관련 값 내에서 선택의 시작 바로 뒤에 있는 문자로 반환합니다.

selectionStart 속성의 setter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, selectionStart가 이 요소에 적용되지 않으면, "InvalidStateError" DOMException을 throw합니다.

  2. 이 요소의 selectionEnd 속성 값을 end로 설정합니다.

  3. end가 주어진 값보다 작으면, end를 주어진 값으로 설정합니다.

  4. 선택 범위 설정을 주어진 값, end, 그리고 이 요소의 selectionDirection 속성 값으로 설정합니다.

selectionEnd 속성의 getter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, selectionEnd가 이 요소에 적용되지 않으면, null을 반환합니다.

  2. 선택이 없으면, 코드 유닛 오프셋을 관련 값 내에서 텍스트 입력 커서 뒤에 있는 문자로 반환합니다.

  3. 코드 유닛 오프셋을 관련 값 내에서 선택의 끝 바로 뒤에 있는 문자로 반환합니다.

selectionEnd 속성의 setter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, selectionEnd가 이 요소에 적용되지 않으면, "InvalidStateError" DOMException을 throw합니다.

  2. 선택 범위 설정을 이 요소의 selectionStart 속성 값, 주어진 값, 그리고 이 요소의 selectionDirection 속성 값으로 설정합니다.

selectionDirection 속성의 getter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, selectionDirection이 이 요소에 적용되지 않으면, null을 반환합니다.

  2. 이 요소의 selection direction을 반환합니다.

selectionDirection 속성의 setter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, selectionDirection이 이 요소에 적용되지 않으면, "InvalidStateError" DOMException을 throw합니다.

  2. 선택 범위 설정을 이 요소의 selectionStart 속성 값, 이 요소의 selectionEnd 속성 값 및 주어진 값으로 설정합니다.

setSelectionRange(start, end, direction) 메서드는 호출될 때 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, setSelectionRange()이 이 요소에 적용되지 않으면, "InvalidStateError" DOMException을 throw합니다.

  2. 선택 범위 설정start, enddirection으로 설정합니다.

선택 범위 설정을 정수 또는 null start, 정수 또는 null 또는 특수 값 infinity end와 선택적으로 문자열 direction을 사용하여 실행하려면, 다음 단계를 실행합니다:

  1. start가 null이면, start를 0으로 설정합니다.

  2. end가 null이면, end를 0으로 설정합니다.

  3. 텍스트 컨트롤의 선택start 위치에서 시작하여 (end-1) 위치에서 끝나는 코드 유닛 시퀀스로 설정합니다. 텍스트 컨트롤의 관련 값길이보다 큰 인수(특수 값 infinity 포함)는 텍스트 컨트롤의 끝을 가리키는 것으로 처리해야 합니다. endstart보다 작거나 같으면 선택의 시작과 끝을 모두 end 오프셋 바로 앞에 배치해야 합니다. 빈 선택의 개념이 없는 사용자 에이전트에서는 이 커서를 end 오프셋 바로 앞에 설정해야 합니다.

  4. direction이 "backward" 또는 "forward"와 동일하지 않거나, direction 인수가 제공되지 않은 경우, direction을 "none"으로 설정합니다.

  5. 텍스트 컨트롤의 선택 방향 설정direction으로 설정합니다.

  6. 이전 단계로 인해 텍스트 컨트롤의 선택이 (범위 또는 방향에서) 수정되었다면, 요소를 기준으로 이벤트를 발생시키기 위해 요소 작업을 큐에 넣습니다. 이 이벤트의 이름은 select이고, bubbles 속성은 true로 초기화되어야 합니다.

setRangeText(replacement, start, end, selectMode) 메서드는 호출될 때 다음 단계를 실행해야 합니다:

  1. 이 요소가 input 요소이고, setRangeText()이 이 요소에 적용되지 않으면, "InvalidStateError" DOMException을 throw합니다.

  2. 이 요소의 더티 값 플래그를 true로 설정합니다.

  3. 메서드에 인수가 하나만 있는 경우, startendselectionStart 속성 및 selectionEnd 속성의 값을 각각 설정합니다.

    그렇지 않으면, startend에 각각 두 번째 및 세 번째 인수의 값을 설정합니다.

  4. startend보다 크면, "IndexSizeError" DOMException을 throw합니다.

  5. start가 텍스트 컨트롤의 길이보다 크면, 이를 텍스트 컨트롤의 관련 값길이로 설정합니다.

  6. end가 텍스트 컨트롤의 길이보다 크면, 이를 텍스트 컨트롤의 관련 값길이로 설정합니다.

  7. selection startselectionStart 속성의 현재 값으로 설정합니다.

  8. selection endselectionEnd 속성의 현재 값으로 설정합니다.

  9. startend보다 작으면, 요소의 관련 값 내에서 start 위치에서 시작하여 (end-1) 위치에서 끝나는 코드 유닛 시퀀스를 삭제합니다.

  10. 텍스트 컨트롤의 관련 값 텍스트에 첫 번째 인수의 값을 start번째 코드 유닛 바로 앞에 삽입합니다.

  11. new length를 첫 번째 인수의 길이로 설정합니다.

  12. new endstartnew length의 합으로 설정합니다.

  13. 다음 목록에서 적절한 하위 단계를 실행합니다:

    네 번째 인수의 값이 "select"인 경우

    selection startstart로 설정합니다.

    selection endnew end로 설정합니다.

    네 번째 인수의 값이 "start"인 경우

    selection startselection endstart로 설정합니다.

    네 번째 인수의 값이 "end"인 경우

    selection startselection endnew end로 설정합니다.

    네 번째 인수의 값이 "preserve"인 경우
    메서드에 인수가 하나만 있는 경우
    1. old lengthend에서 start를 뺀 값으로 설정합니다.

    2. deltanew length에서 old length를 뺀 값으로 설정합니다.

    3. selection startend보다 크면, delta만큼 증가시킵니다. (delta가 음수이면, 즉 새로운 텍스트가 이전 텍스트보다 짧으면, selection start의 값이 감소됩니다.)

      그렇지 않으면: selection startstart보다 크면, start로 설정합니다. (이것은 선택의 시작을 대체된 텍스트의 시작 부분으로 맞춥니다.)

    4. selection endend보다 크면, delta만큼 동일한 방식으로 증가시킵니다.

      그렇지 않으면: selection endstart보다 크면, new end로 설정합니다. (이것은 선택의 끝을 대체된 텍스트의 끝 부분으로 맞춥니다.)

  14. 선택 범위 설정selection startselection end로 설정합니다.

setRangeText() 메서드는 다음 열거형을 사용합니다:

enum SelectionMode {
  "select",
  "start",
  "end",
  "preserve" // 기본값
};

현재 선택된 텍스트를 얻으려면 다음 JavaScript 코드로 충분합니다:

var selectionText = control.value.substring(control.selectionStart, control.selectionEnd);

...여기서 controlinput 또는 textarea 요소입니다.

텍스트 컨트롤의 시작 부분에 일부 텍스트를 추가하면서 텍스트 선택을 유지하려면, 세 가지 속성을 유지해야 합니다:

var oldStart = control.selectionStart;
var oldEnd = control.selectionEnd;
var oldDirection = control.selectionDirection;
var prefix = "http://";
control.value = prefix + control.value;
control.setSelectionRange(oldStart + prefix.length, oldEnd + prefix.length, oldDirection);

...여기서 controlinput 또는 textarea 요소입니다.

4.10.20 제약 조건

4.10.20.1 정의

제출 가능한 요소제약 조건 유효성 검사 후보이며, 어떤 조건이 제약 조건 유효성 검사에서 제외되었을 때 제외되지 않은 경우에만 해당합니다. (예를 들어, 요소에 datalist 요소 조상이 있으면 제약 조건 유효성 검사에서 제외됩니다.)

요소는 사용자 정의 유효성 오류 메시지를 가질 수 있습니다. 처음에는 요소의 사용자 정의 유효성 오류 메시지를 빈 문자열로 설정해야 합니다. 값이 빈 문자열이 아니면 요소는 사용자 정의 오류로 인해 문제가 발생한 상태가 됩니다. 이는 setCustomValidity() 메서드를 사용하여 설정할 수 있으며, 폼 연관 커스텀 요소는 예외입니다. 폼 연관 커스텀 요소ElementInternals 객체의 setValidity() 메서드를 통해 사용자 정의 유효성 오류 메시지를 설정할 수 있습니다. 사용자 에이전트는 해당 컨트롤에서 문제가 발생했을 때 사용자 정의 유효성 오류 메시지를 사용해 사용자에게 경고해야 합니다.

요소는 다양한 방식으로 제한될 수 있습니다. 다음은 폼 컨트롤이 제약 조건 유효성 검사에서 유효하지 않게 만드는 유효성 상태 목록입니다. (아래 정의는 비표준적이며, 다른 부분에서 각 상태가 언제 적용되는지 또는 적용되지 않는지 더 정확하게 정의합니다.)

누락으로 인해 문제가 발생한 상태

컨트롤에 required 속성 (input required, textarea required)이 있으나 이 없는 경우; 또는 더 복잡한 규칙이 select 요소와 라디오 버튼 그룹의 컨트롤에 적용됩니다.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 valueMissing 플래그를 true로 설정할 때.

타입 불일치로 인해 문제가 발생한 상태

임의의 사용자 입력을 허용하는 컨트롤에 올바른 구문이 아닌 이 있는 경우 (이메일, URL).

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 typeMismatch 플래그를 true로 설정할 때.

패턴 불일치로 인해 문제가 발생한 상태

컨트롤에 이 있으며, 패턴 속성을 만족하지 않는 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 patternMismatch 플래그를 true로 설정할 때.

너무 길어서 문제가 발생한 상태

컨트롤에 이 있으며, 폼 컨트롤 maxlength 속성 (input maxlength, textarea maxlength)에 비해 너무 긴 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 tooLong 플래그를 true로 설정할 때.

너무 짧아서 문제가 발생한 상태

컨트롤에 이 있으며, 폼 컨트롤 minlength 속성 (input minlength, textarea minlength)에 비해 너무 짧은 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 tooShort 플래그를 true로 설정할 때.

언더플로우로 인해 문제가 발생한 상태

컨트롤에 이 있으며, 비어 있지 않고 min 속성에 비해 너무 낮은 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 rangeUnderflow 플래그를 true로 설정할 때.

오버플로우로 인해 문제가 발생한 상태

컨트롤에 이 있으며, 비어 있지 않고 max 속성에 비해 너무 높은 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 rangeOverflow 플래그를 true로 설정할 때.

스텝 불일치로 인해 문제가 발생한 상태

컨트롤에 이 있으며, step 속성에 정의된 규칙에 맞지 않는 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 stepMismatch 플래그를 true로 설정할 때.

잘못된 입력으로 인해 문제가 발생한 상태

사용자가 입력한 내용이 불완전하고, 사용자 에이전트가 사용자가 현재 상태에서 폼을 제출할 수 있다고 판단하지 않는 경우.

setValidity() 메서드가 폼 연관 사용자 정의 요소에 대해 badInput 플래그를 true로 설정할 때.

사용자 정의 오류로 인해 문제가 발생한 상태

컨트롤의 사용자 정의 유효성 오류 메시지 (요소의 setCustomValidity() 메서드 또는 ElementInternalssetValidity() 메서드를 통해 설정됨)가 빈 문자열이 아닌 경우.

요소가 비활성화된 상태에서도 이러한 상태로 인해 문제가 발생할 수 있습니다. 따라서 제출 시 폼을 유효성 검사할 때 사용자에게 문제가 발생하지 않더라도 이러한 상태가 DOM에 나타날 수 있습니다.

요소가 위에 나열된 유효성 상태 중 어느 하나도 발생하지 않으면 제약 조건을 충족한 상태입니다.

4.10.20.2 제약 조건 유효성 검사

사용자 에이전트가 제약 조건을 정적으로 유효성 검사해야 할 때, form 요소 form에 대해 다음 단계를 실행해야 합니다. 이 단계는 긍정적 결과(폼의 모든 컨트롤이 유효함) 또는 부정적 결과(유효하지 않은 컨트롤이 있음)와 함께 스크립트가 책임을 주장하지 않은 유효하지 않은 요소들의 목록(비어 있을 수도 있음)을 반환합니다:

  1. controlsform폼 소유자form제출 가능한 요소들의 목록으로, 트리 순서로 설정합니다.

  2. invalid controls를 처음에는 비어 있는 요소들의 목록으로 설정합니다.

  3. controls의 각 field 요소에 대해, 트리 순서로:

    1. 만약 field제약 조건 유효성 검사 후보가 아니라면, 다음 요소로 넘어갑니다.

    2. 그렇지 않고, field제약 조건을 충족한다면, 다음 요소로 넘어갑니다.

    3. 그렇지 않으면, fieldinvalid controls에 추가합니다.

  4. invalid controls가 비어 있으면, 긍정적 결과를 반환합니다.

  5. unhandled invalid controls를 처음에는 비어 있는 요소들의 목록으로 설정합니다.

  6. 만약 invalid controls에 요소가 있다면, 각 field 요소에 대해 트리 순서로:

    1. notCanceledfield에서 invalid이라는 이름의 이벤트를 cancelable 속성이 true로 초기화된 상태로 발생시킨 결과로 설정합니다.

    2. 만약 notCanceled이 true라면, fieldunhandled invalid controls에 추가합니다.

  7. unhandled invalid controls 목록에 있는 요소들의 목록과 함께 부정적 결과를 반환합니다.

사용자 에이전트가 form 요소 form에 대해 제약 조건을 대화식으로 유효성 검사해야 하는 경우, 다음 단계를 실행해야 합니다:

  1. 제약 조건을 정적으로 유효성 검사하고, 결과가 부정적이었다면 반환된 목록을 unhandled invalid controls로 설정합니다.

  2. 결과가 긍정적이었다면, 그 결과를 반환합니다.

  3. unhandled invalid controls에 있는 요소들 중 적어도 하나의 제약 조건 문제를 사용자에게 보고합니다.

  4. 부정적 결과를 반환합니다.

4.10.20.3 제약 조건 유효성 검사 API
element.willValidate

HTMLObjectElement/willValidate

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

폼이 제출될 때 요소가 유효성 검사를 받는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.setCustomValidity(message)

HTMLObjectElement/setCustomValidity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

HTMLSelectElement/setCustomValidity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

사용자 정의 오류를 설정하여 요소가 유효성 검사를 통과하지 못하게 합니다. 제공된 메시지는 사용자에게 문제를 보고할 때 사용자에게 표시될 메시지입니다.

인수가 빈 문자열인 경우, 사용자 정의 오류를 지웁니다.

element.validity.valueMissing

ValidityState/valueMissing

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

필수 필드이지만 요소에 값이 없는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.typeMismatch

요소의 값이 올바른 구문이 아닌 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.patternMismatch

요소의 값이 제공된 패턴과 일치하지 않는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.tooLong

ValidityState/tooLong

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android64+Safari iOS5+Chrome Android?WebView Android4+Samsung Internet?Opera Android12.1+

요소의 값이 제공된 최대 길이보다 긴 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.tooShort

ValidityState/tooShort

모든 현재 엔진에서 지원됨.

Firefox51+Safari10+Chrome40+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer지원 안 됨
Firefox Android64+Safari iOS?Chrome Android?WebView Android67+Samsung Internet?Opera Android?

요소의 값이 빈 문자열이 아닌 경우 제공된 최소 길이보다 짧은 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.rangeUnderflow

요소의 값이 제공된 최소값보다 낮은 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.rangeOverflow

요소의 값이 제공된 최대값보다 높은 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.stepMismatch

요소의 값이 step 속성에 의해 제공된 규칙에 맞지 않는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.badInput

ValidityState/badInput

모든 현재 엔진에서 지원됨.

Firefox29+Safari7+Chrome25+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원 안 됨
Firefox Android64+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

사용자가 UI에서 입력한 값을 사용자 에이전트가 값으로 변환할 수 없는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.customError

요소에 사용자 정의 오류가 있는 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

element.validity.valid

요소의 값에 유효성 문제 없을 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

valid = element.checkValidity()

HTMLInputElement/checkValidity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

HTMLObjectElement/checkValidity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+

HTMLSelectElement/checkValidity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

요소의 값에 유효성 문제가 없으면 true를 반환하고, 그렇지 않으면 false를 반환합니다. 후자의 경우 요소에서 invalid 이벤트를 발생시킵니다.

valid = element.reportValidity()

HTMLFormElement/reportValidity

모든 현재 엔진에서 지원됨.

Firefox49+Safari10.1+Chrome40+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLInputElement/reportValidity

모든 현재 엔진에서 지원됨.

Firefox49+Safari10.1+Chrome40+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer지원 안 됨
Firefox Android64+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

요소의 값에 유효성 문제가 없으면 true를 반환하고, 그렇지 않으면 false를 반환하며, 요소에서 invalid 이벤트를 발생시키고(이벤트가 취소되지 않은 경우) 문제를 사용자에게 보고합니다.

element.validationMessage

HTMLObjectElement/validationMessage

모든 현재 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

요소의 유효성을 검사할 경우 사용자에게 표시될 오류 메시지를 반환합니다.

willValidate 속성의 getter는 이 요소가 제약 조건 유효성 검사 후보인 경우 true를, 그렇지 않은 경우(즉, 제약 조건 유효성 검사가 차단된 조건이 있는 경우) false를 반환해야 합니다.

ElementInternals/willValidate

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

willValidate 속성의 getter는 ElementInternals 인터페이스에서, "NotSupportedError" DOMException을 발생시켜야 합니다. 대상 요소양식 관련 커스텀 요소가 아닌 경우, 그렇지 않은 경우, 대상 요소제약 조건 유효성 검사 후보인 경우 true를, 그렇지 않은 경우 false를 반환해야 합니다.

HTMLInputElement/setCustomValidity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

setCustomValidity(error) 메서드의 단계는 다음과 같습니다:

  1. error줄 바꿈을 정규화하는 결과로 설정합니다.

  2. 사용자 정의 유효성 오류 메시지error로 설정합니다.

다음 예제에서 스크립트는 폼 컨트롤의 값을 편집할 때마다 확인하고, 유효하지 않은 값이 있는 경우 setCustomValidity() 메서드를 사용하여 적절한 메시지를 설정합니다.

<label>Feeling: <input name=f type="text" oninput="check(this)"></label>
<script>
 function check(input) {
   if (input.value == "good" ||
       input.value == "fine" ||
       input.value == "tired") {
     input.setCustomValidity('"' + input.value + '" is not a feeling.');
   } else {
     // 입력이 정상입니다. -- 오류 메시지를 재설정합니다.
     input.setCustomValidity('');
   }
 }
</script>

HTMLObjectElement/validity

모든 현재 엔진에서 지원됨.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

validity 속성의 getter는 이 요소의 유효성 상태를 나타내는 ValidityState 객체를 반환해야 합니다. 이 객체는 실시간입니다.

ElementInternals/validity

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

validity 속성의 getter는 ElementInternals 인터페이스에서, "NotSupportedError" DOMException을 발생시켜야 합니다. 대상 요소양식 관련 커스텀 요소가 아닌 경우, 그렇지 않은 경우, ValidityState 객체를 반환해야 하며, 이는 유효성 상태를 나타냅니다. 이 객체는 실시간입니다.

[Exposed=Window]
interface ValidityState {
  readonly attribute boolean valueMissing;
  readonly attribute boolean typeMismatch;
  readonly attribute boolean patternMismatch;
  readonly attribute boolean tooLong;
  readonly attribute boolean tooShort;
  readonly attribute boolean rangeUnderflow;
  readonly attribute boolean rangeOverflow;
  readonly attribute boolean stepMismatch;
  readonly attribute boolean badInput;
  readonly attribute boolean customError;
  readonly attribute boolean valid;
};

ValidityState 객체에는 다음 속성이 있습니다. getter를 호출하면 다음 목록에 제공된 해당 조건이 true인 경우 true를 반환하고, 그렇지 않은 경우 false를 반환해야 합니다.

valueMissing

컨트롤이 값이 누락된 상태입니다.

typeMismatch

ValidityState/typeMismatch

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

컨트롤이 유형 불일치 상태입니다.

patternMismatch

ValidityState/patternMismatch

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

컨트롤이 패턴 불일치 상태입니다.

tooLong

컨트롤이 값이 너무 긴 상태입니다.

tooShort

컨트롤이 값이 너무 짧은 상태입니다.

rangeUnderflow

ValidityState/rangeUnderflow

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

컨트롤이 범위 언더플로 상태입니다.

rangeOverflow

ValidityState/rangeOverflow

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

컨트롤이 범위 오버플로 상태입니다.

stepMismatch

ValidityState/stepMismatch

모든 현재 엔진에서 지원됨.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

컨트롤이 단계 불일치 상태입니다.

badInput

컨트롤이 잘못된 입력 상태입니다.

customError

컨트롤이 사용자 정의 오류 상태입니다.

valid

다른 조건이 모두 false인 경우입니다.

유효성 검사 단계는 요소 element에 대해 다음과 같습니다:

  1. element제약 조건 유효성 검사 후보이고 제약 조건을 만족하지 못하는 경우:

    1. 이벤트invalid라는 이름으로 element에서 발생시키고, 취소 가능 속성을 true로 초기화합니다(단, 취소는 효과가 없음).

    2. false를 반환합니다.

  2. true를 반환합니다.

checkValidity() 메서드는 호출될 때 이 요소에 대해 유효성 검사 단계를 실행해야 합니다.

ElementInternals/checkValidity

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

checkValidity() 메서드는 ElementInternals 인터페이스에서 다음 단계를 실행해야 합니다:

  1. element를 이 ElementInternals대상 요소로 설정합니다.

  2. element양식 관련 커스텀 요소가 아닌 경우, "NotSupportedError" DOMException을 발생시킵니다.

  3. element에 대해 유효성 검사 단계를 실행합니다.

유효성 보고 단계는 요소 element에 대해 다음과 같습니다:

  1. element제약 조건 유효성 검사 후보이고 제약 조건을 만족하지 못하는 경우:

    1. report이벤트 발생의 결과로 설정하고, 이 이벤트를 element에서 invalid라는 이름으로 발생시킵니다. 취소 가능 속성은 true로 초기화됩니다.

    2. report가 true이면, 이 요소의 제약 조건에 대한 문제를 사용자에게 보고합니다. 제약 조건 문제를 사용자에게 보고할 때, 사용자 에이전트는 포커싱 단계element에 대해 실행할 수 있으며, 문서의 스크롤 위치를 변경하거나 element를 사용자가 주목할 수 있는 위치로 가져오는 등의 작업을 수행할 수 있습니다. element에 여러 가지 문제가 동시에 발생한 경우, 사용자 에이전트는 하나 이상의 제약 조건 위반을 보고할 수 있습니다.

    3. false를 반환합니다.

  2. true를 반환합니다.

reportValidity() 메서드는 호출될 때 이 요소에 대해 유효성 보고 단계를 실행해야 합니다.

ElementInternals/reportValidity

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

reportValidity() 메서드는 ElementInternals 인터페이스에서 다음 단계를 실행해야 합니다:

  1. element를 이 ElementInternals대상 요소로 설정합니다.

  2. element양식 관련 커스텀 요소가 아닌 경우, "NotSupportedError" DOMException을 발생시킵니다.

  3. element에 대해 유효성 보고 단계를 실행합니다.

validationMessage 속성의 getter는 다음 단계를 실행해야 합니다:

  1. 이 요소가 제약 조건 유효성 검사 후보가 아니거나 이 요소가 제약 조건을 만족하는 경우에는 빈 문자열을 반환합니다.

  2. 이 요소만 유효성 제약 문제를 가진 폼 컨트롤인 경우 사용자 에이전트가 사용자에게 표시할 적절한 현지화된 메시지를 반환합니다. 사용자 에이전트가 실제로 그러한 상황에서 텍스트 메시지를 표시하지 않는 경우(예: 그래픽적 표시를 대신 보여주는 경우), 폼 컨트롤이 충족하지 않는 유효성 제약을 표현하는 적절한 현지화된 메시지를 반환합니다. 이 요소가 제약 조건 유효성 검사 후보이고 사용자 정의 오류 상태라면, 사용자 정의 오류 메시지가 반환 값에 포함되어야 합니다.

4.10.20.4 보안

서버는 클라이언트 측 유효성 검사에 의존해서는 안 됩니다. 클라이언트 측 유효성 검사는 악의적인 사용자가 의도적으로 우회할 수 있으며, 구형 사용자 에이전트 또는 이러한 기능을 구현하지 않는 자동화 도구를 사용하는 사용자가 무의식적으로 우회할 수 있습니다. 제약 조건 유효성 검사 기능은 사용자 경험을 개선하기 위한 것이며, 어떠한 종류의 보안 메커니즘도 제공하려는 의도가 없습니다.

4.10.21 양식 제출

4.10.21.1 소개

이 섹션은 규범적이지 않습니다.

양식이 제출되면 양식의 데이터는 enctype에 의해 지정된 구조로 변환된 후, action에 의해 지정된 목적지로 주어진 method를 사용하여 전송됩니다.

예를 들어, 다음과 같은 양식을 보십시오:

<form action="/find.cgi" method=get>
 <input type=text name=t>
 <input type=search name=q>
 <input type=submit>
</form>

사용자가 첫 번째 필드에 "cats"를 입력하고 두 번째 필드에 "fur"를 입력한 다음 제출 버튼을 누르면 사용자 에이전트는 /find.cgi?t=cats&q=fur을(를) 로드합니다.

반면에, 다음 양식을 고려해 보십시오:

<form action="/find.cgi" method=post enctype="multipart/form-data">
 <input type=text name=t>
 <input type=search name=q>
 <input type=submit>
</form>

동일한 사용자 입력이 주어진 경우 제출 결과는 매우 다릅니다. 대신 사용자 에이전트는 주어진 URL로 HTTP POST를 수행하고, 엔티티 본문은 다음과 같은 텍스트와 유사하게 전송됩니다:

------kYFrd4jNJEgCervE
Content-Disposition: form-data; name="t"

cats
------kYFrd4jNJEgCervE
Content-Disposition: form-data; name="q"

fur
------kYFrd4jNJEgCervE--
4.10.21.2 암묵적 제출

양식 요소의 기본 버튼제출 버튼 중에서 트리 순서로 첫 번째에 위치하며, 양식 소유자가 해당 양식 요소입니다.

사용자 에이전트가 사용자가 양식을 암묵적으로 제출하도록 허용하는 것을 지원하는 경우(예: 일부 플랫폼에서는 텍스트 컨트롤에 포커스가 있을 때 "Enter" 키를 누르면 양식이 암묵적으로 제출됩니다), 해당 양식의 기본 버튼활성화 동작이 있고 비활성화되지 않은 경우, 사용자 에이전트는 해당 기본 버튼에서 click 이벤트를 발생시켜야 합니다.

웹에는 양식을 암묵적으로 제출할 수 있는 방법이 있어야만 사용할 수 있는 페이지가 존재하므로, 사용자 에이전트는 이를 지원하는 것이 강력히 권장됩니다.

양식에 제출 버튼이 없으면, 암묵적 제출 메커니즘은 다음 단계를 수행해야 합니다:

  1. 양식에 암묵적 제출을 차단하는 필드가 둘 이상 있는 경우, 반환합니다.

  2. 제출양식 요소에서 userInvolvement를 "activation"으로 설정하여 수행합니다.

이전 문단의 목적을 위해, 요소가 암묵적 제출을 차단하는 필드이 되는 경우는 해당 요소가 양식 요소의 양식 소유자이고, 해당 요소의 type 속성이 다음 상태 중 하나인 경우입니다: 텍스트, 검색, 전화번호, URL, 이메일, 비밀번호, 날짜, , , 시간, 현지 날짜 및 시간, 숫자

4.10.21.3 양식 제출 알고리즘

양식 요소는 엔트리 목록 구성이라는 부울 값을 가지며, 초기 값은 false입니다.

양식 요소는 제출 이벤트 발생이라는 부울 값을 가지며, 초기 값은 false입니다.

특정 요소 submitter(일반적으로 버튼)에서 form 요소를 제출하려면, 선택적으로 부울 submit() 메서드에서 제출된 경우(기본값은 false)와 선택적 사용자 탐색 관여 userInvolvement(기본값은 "none")을 받아야 합니다.

  1. form탐색할 수 없는 경우, 반환합니다.

  2. form엔트리 목록 구성이 true이면, 반환합니다.

  3. form documentform노드 문서로 설정합니다.

  4. form document활성 샌드박싱 플래그 세트샌드박스된 양식 브라우징 컨텍스트 플래그가 설정된 경우, 반환합니다.

  5. submit() 메서드에서 제출되지 않은 경우, 다음을 수행합니다:

    1. form제출 이벤트 발생이 true이면, 반환합니다.

    2. form제출 이벤트 발생을 true로 설정합니다.

    3. 양식 소유자가 form제출 가능한 요소 목록의 각 요소 field에 대해, field사용자 유효성을 true로 설정합니다.

    4. submitter 요소의 no-validate 상태가 false이면, form제약 조건을 상호작용적으로 유효성 검사하고 결과를 확인합니다. 결과가 부정적이면(즉, 제약 조건 검사가 유효하지 않은 필드가 있다고 결론짓고 사용자에게 이를 알렸을 가능성이 있는 경우), 다음을 수행합니다:

      1. form제출 이벤트 발생을 false로 설정합니다.

      2. 반환합니다.

    5. submitterButtonsubmitterform인 경우 null로 설정합니다. 그렇지 않은 경우, submitterButtonsubmitter로 설정합니다.

    6. shouldContinue이벤트 발생 결과로 설정합니다. 이 이벤트는 submit이라는 이름으로 form에서 발생하며, SubmitEvent을 사용하여 발생하며, submitter 속성이 submitterButton으로 초기화되고, bubbles 속성이 true로, cancelable 속성이 true로 초기화됩니다.

    7. form제출 이벤트 발생을 false로 설정합니다.

    8. shouldContinue가 false인 경우, 반환합니다.

    9. form탐색할 수 없는 경우, 반환합니다.

      탐색할 수 없음이 다시 실행되며, submit 이벤트를 디스패치하는 동안 결과가 변경될 수 있습니다.

  6. encoding양식에 대한 인코딩 선택의 결과로 설정합니다.

  7. entry list양식 데이터 세트 구성의 결과로 설정합니다. 이때 form, submitter, encoding을 사용합니다.

  8. 단언: entry list가 null이 아닙니다.

  9. form탐색할 수 없는 경우, 반환합니다.

    탐색할 수 없음이 다시 실행되며, 양식 데이터 세트 구성에서 formdata 이벤트를 디스패치하는 동안 결과가 변경될 수 있습니다.

  10. methodsubmitter 요소의 method로 설정합니다.

  11. methoddialog인 경우, 다음을 수행합니다:

    1. form에 조상 dialog 요소가 없으면, 반환합니다.

    2. subjectform의 가장 가까운 조상 dialog 요소로 설정합니다.

    3. result를 null로 설정합니다.

    4. submitterinput 요소이며, 해당 type 속성이 이미지 버튼 상태에 있는 경우, 다음을 수행합니다:

      1. (x, y)를 선택된 좌표로 설정합니다.

      2. resultx, ",", y의 연결 결과로 설정합니다.

    5. 그렇지 않으면, submitter이 있으면, result를 해당 으로 설정합니다.

    6. 대화상자 닫기result와 함께 subject에 대해 수행합니다.

    7. 반환합니다.

  12. actionsubmitter 요소의 action으로 설정합니다.

  13. action이 빈 문자열이면, action문서의 주소(URL)로 설정합니다.

  14. parsed actionURL 인코딩 구문 분석의 결과로 설정합니다. 이때 actionsubmitter노드 문서에 상대적으로 설정합니다.

  15. parsed action이 실패하면, 반환합니다.

  16. schemeURL 스킴의 결과로 설정합니다.

  17. enctypesubmitter 요소의 enctype으로 설정합니다.

  18. formTarget을 null로 설정합니다.

  19. submitter 요소가 제출 버튼이며, formtarget 속성이 있으면, formTarget을 해당 formtarget 속성 값으로 설정합니다.

  20. target요소의 타겟 가져오기의 결과로 설정합니다. 이때 submitter양식 소유자formTarget을 사용합니다.

  21. noopener요소의 noopener 가져오기의 결과로 설정합니다. 이때 formtarget을 사용합니다.

  22. targetNavigable탐색할 대상 선택 규칙을 적용한 첫 번째 결과로 설정합니다. 이때 target, form노드 탐색 가능성, noopener를 사용합니다.

  23. targetNavigable이 null이면, 반환합니다.

  24. historyHandling을 "auto"로 설정합니다.

  25. form documenttargetNavigable활성 문서와 같고, form document가 아직 완전히 로드되지 않았으면, historyHandling을 "replace"로 설정합니다.

  26. 다음 표의 첫 번째 셀에 주어진 scheme에 따라 적절한 행을 선택합니다. 그런 다음 첫 번째 셀에 주어진 method에 따라 해당 행의 적절한 셀을 선택합니다. 그런 다음 해당 셀에 나열된 단계를 아래에서 정의된 단계로 건너뜁니다.

    GET POST
    http 액션 URL 변경 엔터티 본문으로 제출
    https 액션 URL 변경 엔터티 본문으로 제출
    ftp 액션 URL 가져오기 액션 URL 가져오기
    javascript 액션 URL 가져오기 액션 URL 가져오기
    data 액션 URL 변경 액션 URL 가져오기
    mailto 헤더와 함께 메일 보내기 본문으로 메일 보내기

    scheme이 이 표에 나열된 것 중 하나가 아닌 경우, 이 사양에서는 동작을 정의하지 않습니다. 다른 사양이 이를 정의하지 않는 경우, 유사한 스킴에 대해 이 사양에서 정의된 것과 유사한 방식으로 동작해야 합니다.

    양식 요소는 계획된 탐색을 가지며, 이는 null이거나 작업입니다. 양식이 처음 생성될 때, 계획된 탐색은 null로 설정되어야 합니다. 아래에서 설명한 동작에서, 사용자 에이전트가 선택적으로 URL url에 대해 탐색을 계획해야 하는 경우 POST 리소스-또는-null postResource(기본값은 null)를 사용해야 합니다. 다음 단계를 실행해야 합니다:

    1. referrerPolicy을 빈 문자열로 설정합니다.

    2. 양식 요소의 링크 유형noreferrer 키워드가 포함되어 있으면, referrerPolicy를 "no-referrer"로 설정합니다.

    3. 양식계획된 탐색이 null이 아니면, 이를 작업 큐에서 제거합니다.

    4. 양식 요소와 함께 요소 작업을 큐에 추가합니다. 이때 DOM 조작 작업 소스를 사용하고, 다음 단계를 실행합니다:

      1. 양식계획된 탐색을 null로 설정합니다.

      2. 탐색targetNavigable로 수행하고, 양식 요소의 노드 문서를 사용하여 historyHandlinghistoryHandling으로 설정하고, userInvolvementuserInvolvement으로 설정하며, referrerPolicyreferrerPolicy으로 설정하고, documentResourcepostResource로 설정하고, formDataEntryListentry list로 설정합니다.

    5. 양식계획된 탐색을 방금 큐에 추가된 작업으로 설정합니다.

    동작은 다음과 같습니다:

    액션 URL 변경

    pairs이름-값 쌍 목록으로 변환의 결과로 설정합니다. 이때 entry list를 사용합니다.

    queryapplication/x-www-form-urlencoded 직렬화 프로그램의 결과로 설정합니다. 이때 pairsencoding을 사용합니다.

    parsed action쿼리 구성 요소를 query로 설정합니다.

    탐색 계획parsed action으로 수행합니다.

    엔터티 본문으로 제출

    단언: methodPOST입니다.

    enctype에 따라 전환합니다:

    application/x-www-form-urlencoded

    pairs이름-값 쌍 목록으로 변환의 결과로 설정합니다. 이때 entry list를 사용합니다.

    bodyapplication/x-www-form-urlencoded 직렬화 프로그램의 결과로 설정합니다. 이때 pairsencoding을 사용합니다.

    bodyUTF-8로 인코딩의 결과로 설정합니다.

    mimeType을 `application/x-www-form-urlencoded`으로 설정합니다.

    multipart/form-data

    bodymultipart/form-data 인코딩 알고리즘의 결과로 설정합니다. 이때 entry listencoding을 사용합니다.

    mimeType동형 인코딩의 결과로 설정합니다. 이때 "multipart/form-data; boundary="와 multipart/form-data 경계 문자열을 연결한 결과를 사용합니다. 이때 multipart/form-data 인코딩 알고리즘을 사용합니다.

    text/plain

    pairs이름-값 쌍 목록으로 변환의 결과로 설정합니다. 이때 entry list를 사용합니다.

    bodytext/plain 인코딩 알고리즘의 결과로 설정합니다. 이때 pairs를 사용합니다.

    body인코딩의 결과로 설정합니다. 이때 encoding을 사용합니다.

    mimeType을 `text/plain`으로 설정합니다.

    탐색 계획parsed action으로 수행합니다. 이때 POST 리소스요청 본문body이고, 요청 콘텐츠 유형mimeType인 경우를 설정합니다.

    액션 URL 가져오기

    탐색 계획parsed action으로 수행합니다.

    entry list는 폐기됩니다.

    헤더와 함께 메일 보내기

    pairs이름-값 쌍 목록으로 변환의 결과로 설정합니다. 이때 entry list를 사용합니다.

    headersapplication/x-www-form-urlencoded 직렬화 프로그램의 결과로 설정합니다. 이때 pairsencoding을 사용합니다.

    headers의 U+002B PLUS SIGN 문자(+)를 "%20" 문자열로 대체합니다.

    parsed action쿼리headers로 설정합니다.

    탐색 계획parsed action으로 수행합니다.

    본문으로 메일 보내기

    pairs이름-값 쌍 목록으로 변환의 결과로 설정합니다. 이때 entry list를 사용합니다.

    enctype에 따라 전환합니다:

    text/plain

    bodytext/plain 인코딩 알고리즘의 결과로 설정합니다. 이때 pairs를 사용합니다.

    bodyUTF-8 퍼센트 인코딩의 결과로 설정합니다. 이때 기본 인코딩 세트를 사용합니다. [URL]

    그렇지 않은 경우

    bodyapplication/x-www-form-urlencoded 직렬화 프로그램의 결과로 설정합니다. 이때 pairsencoding을 사용합니다.

    parsed action쿼리가 null이면, 이를 빈 문자열로 설정합니다.

    parsed action쿼리가 빈 문자열이 아니면, 여기에 U+0026 AMPERSAND 문자(&)를 추가합니다.

    parsed action쿼리에 "body="를 추가합니다.

    parsed action쿼리body를 추가합니다.

    탐색 계획parsed action으로 수행합니다.

4.10.21.4 엔트리 목록 구성

엔트리 목록은 일반적으로 양식의 내용을 나타내는 목록입니다. 엔트리이름(스칼라 값 문자열)과 (스칼라 값 문자열 또는 파일 객체 중 하나)으로 구성된 튜플입니다.

name 문자열과 문자열 또는 Blob 객체 value, 선택적으로 스칼라 값 문자열 filename이 주어졌을 때, 엔트리를 생성하는 방법은 다음과 같습니다:

  1. name변환하여 스칼라 값 문자열로 설정합니다.

  2. value가 문자열인 경우, value변환하여 스칼라 값 문자열로 설정합니다.

  3. 그 외의 경우:

    1. value파일 객체가 아닌 경우, value를 동일한 바이트를 나타내는 새 파일 객체로 설정하고, 이름 속성 값을 "blob"으로 설정합니다.

    2. filename이 주어지면, value를 동일한 바이트를 나타내는 새 파일 객체로 설정하고, 이름 속성을 filename으로 설정합니다.

    이러한 작업은 filename이 제공되거나 전달된 Blob파일 객체가 아닌 경우, 새로운 파일 객체를 생성합니다. 이러한 경우 전달된 Blob 객체의 정체성은 유지되지 않습니다.

  4. name이름이고 value엔트리를 반환합니다.

form과 선택적 submitter(기본값 null) 및 선택적 encoding(기본값 UTF-8)이 주어졌을 때, 엔트리 목록을 구성하는 방법은 다음과 같습니다:

  1. form엔트리 목록 구성 중이 true이면, null을 반환합니다.

  2. form엔트리 목록 구성 중을 true로 설정합니다.

  3. controlsform양식 소유자form제출 가능한 요소의 목록으로 설정합니다. 이 목록은 트리 순서로 설정됩니다.

  4. entry list를 새 빈 엔트리 목록으로 설정합니다.

  5. controls의 각 field 요소에 대해 트리 순서로 다음을 수행합니다:

    1. 다음 중 하나가 참인 경우:

      그렇다면 계속합니다.

    2. field 요소가 input 요소이며 해당 type 속성이 이미지 버튼 상태인 경우, 다음을 수행합니다:

      1. field 요소가 submitter가 아니면, 계속합니다.

      2. field 요소에 name 속성이 지정되어 있고 값이 빈 문자열이 아닌 경우, name을 해당 값에 U+002E(.)을 추가한 값으로 설정합니다. 그렇지 않으면, name을 빈 문자열로 설정합니다.

      3. namexname과 U+0078(x)을 연결한 값으로 설정합니다.

      4. nameyname과 U+0079(y)을 연결한 값으로 설정합니다.

      5. (x, y)선택된 좌표로 설정합니다.

      6. 엔트리 생성namexx로 수행하고, 이를 entry list추가합니다.

      7. 엔트리 생성nameyy로 수행하고, 이를 entry list추가합니다.

      8. 계속합니다.

    3. field양식 관련 커스텀 요소인 경우, fieldentry list를 사용하여 엔트리 구성 알고리즘을 수행한 다음, 계속합니다.

    4. field 요소에 name 속성이 지정되지 않았거나, 해당 name 속성의 값이 빈 문자열인 경우, 계속합니다.

    5. namefield 요소의 name 속성의 값으로 설정합니다.

    6. field 요소가 select 요소인 경우, field옵션 목록에 있는 각 option 요소에 대해, 해당 선택됨이 true이고 비활성화되지 않은 경우, nameoption 요소의 으로 엔트리를 생성하고, 이를 entry list추가합니다.

    7. 그 외의 경우, field 요소가 input 요소이며, 해당 type 속성이 체크박스 상태 또는 라디오 버튼 상태인 경우, 다음을 수행합니다:

      1. field 요소에 value 속성이 지정된 경우, value를 해당 속성의 값으로 설정합니다. 그렇지 않으면, value를 문자열 "on"으로 설정합니다.

      2. namevalue엔트리를 생성하고, 이를 entry list추가합니다.

    8. 그 외의 경우, field 요소가 input 요소이며 해당 type 속성이 파일 업로드 상태인 경우, 다음을 수행합니다:

      1. 선택된 파일이 없으면, name과 빈 이름을 가진 새로운 파일 객체로 엔트리를 생성하고, application/octet-stream 유형으로 설정하며, 빈 본문으로 설정하고, 이를 entry list추가합니다.

      2. 그 외의 경우, 선택된 파일의 각 파일에 대해 name과 해당 파일을 나타내는 파일 객체로 엔트리를 생성하고, 이를 entry list추가합니다.

    9. 그 외의 경우, field 요소가 input 요소이며 해당 type 속성이 숨김 상태이고 name이 "_charset_"와 ASCII 대소문자 구분 없이 일치하는 경우, 다음을 수행합니다:

      1. charsetencoding이름으로 설정합니다.

      2. namecharset으로 엔트리를 생성하고, 이를 entry list추가합니다.

    10. 그 외의 경우, namefield 요소의 으로 엔트리를 생성하고, 이를 entry list추가합니다.

    11. 요소에 dirname 속성이 있고 해당 속성의 값이 빈 문자열이 아니며 요소가 자동 방향성 양식 관련 요소인 경우, 다음을 수행합니다:

      1. dirname을 요소의 dirname 속성 값으로 설정합니다.

      2. dir을 요소의 방향성이 'ltr'인 경우 문자열 "ltr"로 설정하고, 그렇지 않으면(즉, 요소의 방향성이 'rtl'인 경우) "rtl"로 설정합니다.

      3. dirnamedir으로 엔트리를 생성하고, 이를 entry list추가합니다.

  6. form dataentry list와 연결된 새로운 FormData 객체로 설정합니다.

  7. 이벤트를 발생시킵니다. 이벤트 이름은 formdata이고, form에서 FormDataEvent를 사용하여 발생시킵니다. 이때 formData 속성은 form data로 초기화되고, bubbles 속성은 true로 초기화됩니다.

  8. form엔트리 목록 구성 중을 false로 설정합니다.

  9. entry list복제본을 반환합니다.

4.10.21.5 양식 제출 인코딩 선택

사용자 에이전트가 양식에 대한 인코딩을 선택해야 하는 경우, 다음 단계를 실행해야 합니다:

  1. encoding문서의 문자 인코딩으로 설정합니다.

  2. 만약 form 요소에 accept-charset 속성이 있으면, encoding을 다음 하위 단계들을 실행하여 설정합니다:

    1. inputform 요소의 accept-charset 속성 값으로 설정합니다.

    2. candidate encoding labelsASCII 공백을 기준으로 input을 분할한 결과로 설정합니다.

    3. candidate encodings을 빈 문자 인코딩 목록으로 설정합니다.

    4. candidate encoding labels의 각 토큰에 대해 차례대로 인코딩을 가져오고, 실패하지 않으면 candidate encodings에 그 인코딩을 추가합니다.

    5. 만약 candidate encodings이 비어 있으면, UTF-8을 반환합니다.

    6. candidate encodings에서 첫 번째 인코딩을 반환합니다.

  3. 출력 인코딩을 가져오는 결과를 encoding에서 반환합니다.

4.10.21.6 엔트리 목록을 이름-값 쌍 목록으로 변환

application/x-www-form-urlencodedtext/plain 인코딩 알고리즘은 값이 엔트리 목록이 아닌 문자열이어야 하는 이름-값 쌍 목록을 사용합니다. 이 알고리즘은 변환을 수행합니다.

엔트리 목록 entry list를 이름-값 쌍 목록으로 변환하기 위해, 다음 단계를 실행합니다:

  1. list를 빈 이름-값 쌍 목록으로 설정합니다.

  2. entry에 대해 entry list를 다음과 같이 순회합니다:

    1. nameentry이름으로 설정하고, U+000D(CR) 뒤에 U+000A(LF)가 없는 모든 경우와 U+000A(LF) 앞에 U+000D(CR)가 없는 모든 경우를 U+000D(CR)과 U+000A(LF)로 구성된 문자열로 대체합니다.

    2. 만약 entry파일 객체인 경우, valueentry이름으로 설정합니다. 그렇지 않으면 valueentry으로 설정합니다.

    3. value에서 U+000D(CR) 뒤에 U+000A(LF)가 없는 모든 경우와 U+000A(LF) 앞에 U+000D(CR)가 없는 모든 경우를 U+000D(CR)과 U+000A(LF)로 구성된 문자열로 대체합니다.

    4. list 이름이 name이고 값이 value인 새 이름-값 쌍을 추가합니다.

  3. list를 반환합니다.

4.10.21.7 URL-인코딩된 폼 데이터

application/x-www-form-urlencoded에 대한 자세한 내용은 URL을 참조하십시오. [URL]

4.10.21.8 멀티파트 폼 데이터

multipart/form-data 인코딩 알고리즘엔트리 목록 entry list인코딩 encoding을 사용하여 다음과 같이 작동합니다:

  1. entry에 대해 entry list를 순회합니다:

    1. entry이름에서 U+000D(CR) 뒤에 U+000A(LF)가 없는 모든 경우와 U+000A(LF) 앞에 U+000D(CR)가 없는 모든 경우를 U+000D(CR)과 U+000A(LF)로 구성된 문자열로 대체합니다.

    2. 만약 entry파일 객체가 아닌 경우, entry에서 U+000D(CR) 뒤에 U+000A(LF)가 없는 모든 경우와 U+000A(LF) 앞에 U+000D(CR)가 없는 모든 경우를 U+000D(CR)과 U+000A(LF)로 구성된 문자열로 대체합니다.

  2. RFC 7578, Returning Values from Forms: multipart/form-data에 설명된 규칙을 사용하여 entry list를 인코딩하여 생성된 바이트 시퀀스를 반환합니다. 다음 조건을 고려하십시오: [RFC7578]

multipart/form-data 페이로드를 해석하는 방법에 대한 자세한 내용은 RFC 7578을 참조하십시오. [RFC7578]

4.10.21.9 일반 텍스트 양식 데이터

text/plain 인코딩 알고리즘은 이름-값 쌍 목록 pairs를 사용하여 다음과 같이 작동합니다:

  1. result를 빈 문자열로 설정합니다.

  2. pairs의 각 pair에 대해:

    1. pair의 이름을 result에 추가합니다.

    2. U+003D 등호 문자(=) 하나를 result에 추가합니다.

    3. pair의 값을 result에 추가합니다.

    4. U+000D 캐리지 리턴(CR)과 U+000A 라인 피드(LF) 문자 쌍을 result에 추가합니다.

  3. result를 반환합니다.

text/plain 형식을 사용하는 페이로드는 사람이 읽을 수 있도록 설계되었습니다. 그러나 이 형식은 컴퓨터에서 신뢰할 수 있게 해석할 수 없으며, 형식이 모호합니다(예: 값의 끝에 있는 줄 바꿈과 값 내의 실제 줄 바꿈을 구분할 방법이 없습니다).

4.10.21.10 SubmitEvent 인터페이스

SubmitEvent

모든 현재 엔진에서 지원됩니다.

Firefox75+Safari15+Chrome81+
Opera?Edge81+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

SubmitEvent/SubmitEvent

모든 현재 엔진에서 지원됩니다.

Firefox75+Safari15+Chrome81+
Opera?Edge81+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=Window]
interface SubmitEvent : Event {
  constructor(DOMString type, optional SubmitEventInit eventInitDict = {});

  readonly attribute HTMLElement? submitter;
};

dictionary SubmitEventInit : EventInit {
  HTMLElement? submitter = null;
};
event.submitter

제출 버튼을 나타내는 요소를 반환하며, 버튼이 폼 제출을 트리거하지 않은 경우 null을 반환합니다.

submitter 속성은 초기화된 값을 반환해야 합니다.

4.10.21.11 FormDataEvent 인터페이스

FormDataEvent/FormDataEvent

모든 현재 엔진에서 지원됩니다.

Firefox72+Safari15+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

FormDataEvent

모든 현재 엔진에서 지원됩니다.

Firefox72+Safari15+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=Window]
interface FormDataEvent : Event {
  constructor(DOMString type, FormDataEventInit eventInitDict);

  readonly attribute FormData formData;
};

dictionary FormDataEventInit : EventInit {
  required FormData formData;
};
event.formData

FormData 객체를 반환하며, 이는 대상 에 연결된 요소의 이름과 값을 나타냅니다. FormData 객체에서 수행되는 작업은 제출될 폼 데이터에 영향을 미칩니다.

formData 속성은 초기화된 값을 반환해야 합니다. 이 속성은 항목 목록에 연결된 FormData 객체를 나타내며, 이는 이 제출될 때 구성된 항목 목록과 연결됩니다.

4.10.22 폼 재설정

form 요소 form재설정될 때, 다음 단계를 실행합니다:

  1. reset을(를) 이벤트 발행의 결과로 합니다. 이 이벤트의 이름은 reset 이며, form에서 bubblescancelable 속성이 true로 초기화된 상태로 발행됩니다.

  2. reset이 true이면, 리셋 알고리즘을 각 재설정 가능한 요소에 대해 호출합니다. 이 요소들의 폼 소유자form입니다.

재설정 가능한 요소는 자체의 리셋 알고리즘을 정의합니다. 이러한 알고리즘의 일부로 폼 컨트롤에 가해진 변경 사항은 사용자가 직접 한 변경 사항으로 간주되지 않습니다 (예: input 이벤트가 발생하지 않음).

4.11 대화형 요소

4.11.1 details 요소

Element/details

모든 현재 엔진에서 지원됩니다.

Firefox49+Safari6+Chrome12+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android49+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLDetailsElement

모든 현재 엔진에서 지원됩니다.

Firefox49+Safari6+Chrome10+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
대화형 콘텐츠.
감지 가능한 콘텐츠.
이 요소를 사용할 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
하나의 summary 요소와 그 뒤에 오는 플로우 콘텐츠.
text/html에서의 태그 생략:
태그를 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
name — 상호 배타적인 details 요소 그룹의 이름
open — 세부 정보가 표시되는지 여부
접근성 고려 사항:
작성자를 위한 안내.
구현자를 위한 안내.
DOM 인터페이스:
[Exposed=Window]
interface HTMLDetailsElement : HTMLElement {
[HTMLConstructor] constructor();

[CEReactions] attribute DOMString name;
[CEReactions] attribute boolean open;
};

details 요소는 사용자가 추가 정보를 얻거나 제어할 수 있는 공개 위젯을 나타냅니다.

모든 HTML 요소와 마찬가지로, details 요소를 다른 유형의 제어를 나타내기 위해 사용하는 것은 적합하지 않습니다. 예를 들어, 탭 위젯과 메뉴 위젯은 공개 위젯이 아니므로 이러한 패턴을 구현하기 위해 details 요소를 남용하는 것은 잘못된 것입니다.

details 요소는 각주에 적합하지 않습니다. 각주를 마크업하는 방법에 대한 자세한 내용은 각주 섹션을 참조하십시오.

요소의 첫 번째 summary 자식 요소가 있다면, 이 요소는 세부 사항의 요약 또는 전설을 나타냅니다. 만약 자식 summary 요소가 없을 경우, 사용자 에이전트는 자체적으로 전설을 제공해야 합니다 (예: "세부 사항").

요소의 나머지 콘텐츠는 추가 정보나 제어를 나타냅니다.

name 콘텐츠 속성은 요소가 속한 관련 details 요소 그룹의 이름을 지정합니다. 이 그룹의 한 구성원을 열면 그룹의 다른 구성원이 닫히게 됩니다. 이 속성이 지정된 경우 값은 빈 문자열이 되어서는 안 됩니다.

이 기능을 사용하기 전에 작성자는 관련 details 요소를 독점적인 아코디언으로 그룹화하는 것이 사용자에게 도움이 되는지 또는 해가 되는지 고려해야 합니다. 독점적인 아코디언을 사용하면 콘텐츠 집합이 차지할 수 있는 최대 공간을 줄일 수 있지만, 원하는 항목을 찾기 위해 많은 항목을 열어야 하는 사용자나 여러 항목의 콘텐츠를 동시에 보고자 하는 사용자를 좌절시킬 수 있습니다.

문서는 동일한 details 이름 그룹에 속한 details 요소 중 open 속성이 있는 요소를 두 개 이상 포함해서는 안 됩니다. 작성자는 스크립트를 사용하여 문서에 details 요소를 추가할 때, details 이름 그룹details 요소를 두 개 이상 포함시키지 않도록 해야 합니다.

공통 name 속성으로 생성된 요소 그룹은 독점적이며, 이는 최대 하나의 details 요소만 동시에 열릴 수 있음을 의미합니다. 이러한 독점성은 사용자 에이전트에 의해 강제되지만, 그 결과로 즉시 마크업의 open 속성이 변경됩니다. 작성자에게 적용되는 이 요구 사항은 잘못된 마크업을 금지합니다.

문서에는 동일한 details 이름 그룹에 속한 다른 details 요소의 자손인 details 요소가 포함되어서는 안 됩니다.

name 속성을 사용하여 여러 관련된 details 요소를 그룹화하는 문서는 해당 관련 요소를 포함하는 요소(예: section 요소 또는 article 요소) 내에 함께 보관해야 합니다. 그룹에 제목이 도입되는 것이 합리적일 경우, 작성자는 그 제목을 포함 요소의 시작 부분에 heading 요소로 추가해야 합니다.

관련 요소를 시각적으로 및 프로그래밍 방식으로 함께 그룹화하는 것은 접근 가능한 사용자 경험에 중요할 수 있습니다. 이는 사용자가 이러한 요소 간의 관계를 이해하는 데 도움이 될 수 있습니다. 관련 요소가 웹 페이지의 서로 다른 섹션에 있으면 이러한 요소 간의 관계가 덜 발견되거나 이해될 수 있습니다.

open 콘텐츠 속성은 불리언 속성입니다. 속성이 존재하면 요약 및 추가 정보가 사용자에게 표시됨을 나타냅니다. 속성이 없으면 요약만 표시됩니다.

요소가 생성될 때 속성이 없으면 추가 정보가 숨겨져야 하며, 속성이 있으면 해당 정보가 표시되어야 합니다. 이후 속성이 제거되면 정보가 숨겨져야 하며, 속성이 추가되면 정보가 표시되어야 합니다.

사용자 에이전트는 사용자가 추가 정보를 표시하거나 숨길 수 있도록 해야 합니다. 세부 정보를 표시하라는 요청을 충족하려면 사용자 에이전트는 해당 요소에 open 속성을 빈 문자열로 설정해야 합니다. 정보를 숨기라는 요청을 충족하려면 사용자 에이전트는 요소에서 open 속성을 제거해야 합니다.

추가 정보를 표시하거나 숨기라는 요청은 적절한 summary 요소의 활성화 동작일 수 있습니다. 그러나 그러한 요소가 존재하지 않는 경우에도 사용자 에이전트는 다른 사용자 인터페이스를 통해 이러한 기능을 제공할 수 있습니다.

details 이름 그룹에는 details 요소 a와 모든 다른 details 요소 b가 포함됩니다. 이러한 조건을 충족하는 경우:

모든 details 요소에는 세부 정보 전환 작업 추적기가 있으며, 이는 전환 작업 추적기 또는 null이며, 초기에는 null입니다.

다음 속성 변경 단계element, localName, oldValue, value, 및 namespace에 대해 모든 details 요소에 사용됩니다:

  1. namespace가 null이 아닌 경우, return합니다.

  2. localNamename인 경우, element에 대해 필요한 경우 주어진 요소를 닫아 세부 사항 독점성을 보장합니다.

  3. localNameopen인 경우:

    1. oldValue 또는 value 중 하나가 null이고 다른 하나가 null이 아닌 경우, 이 details 요소에 대해 세부 정보 알림 작업 단계로 알려진 다음 단계를 실행합니다:

      open 속성이 연속적으로 여러 번 전환될 때, 결과 작업은 기본적으로 병합되어 단 하나의 이벤트만 발행됩니다.

      1. oldValue가 null인 경우, 이 details 요소, "closed", 및 "open"을 주어진 세부 정보 전환 이벤트 작업을 대기열에 추가합니다.

      2. 그렇지 않은 경우, 이 details 요소, "open", 및 "closed"을 주어진 세부 정보 전환 이벤트 작업을 대기열에 추가합니다.

    2. oldValue가 null이고 value가 null이 아닌 경우, element에 대해 필요한 경우 다른 요소를 닫아 세부 사항 독점성을 보장합니다.

details 요소에 대한 HTML 요소 삽입 단계insertedNode에 대해 다음과 같습니다:

  1. insertedNode에 대해 필요한 경우 주어진 요소를 닫아 세부 사항 독점성을 보장합니다. 세부 사항 독점성을 보장합니다.

이 속성 변경 및 삽입 단계는 파서를 통해 속성이나 요소가 삽입될 때도 실행됩니다.

details 요소 element, 문자열 oldState 및 문자열 newState에 대해 세부 정보 전환 이벤트 작업을 대기열에 추가합니다:

  1. element세부 정보 전환 작업 추적기가 null이 아닌 경우:

    1. oldStateelement세부 정보 전환 작업 추적기old state로 설정합니다.

    2. element세부 정보 전환 작업 추적기작업작업 대기열에서 제거합니다.

    3. element세부 정보 전환 작업 추적기를 null로 설정합니다.

  2. 요소 작업을 대기열에 추가합니다 DOM 조작 작업 소스element를 주어진 다음 단계를 실행합니다:

    1. 이벤트를 발행합니다 이름은 toggle이고, element에서 ToggleEvent를 사용하며, oldState 속성은 oldState로 초기화되고 newState 속성은 newState로 초기화됩니다.

    2. element세부 정보 전환 작업 추적기를 null로 설정합니다.

  3. element세부 정보 전환 작업 추적기를 방금 대기열에 추가된 작업으로 설정하고, old stateoldState로 설정합니다.

필요한 경우 다른 요소를 닫아 세부 사항 독점성을 보장합니다 주어진 details 요소 element:

  1. 단언: elementopen 속성이 있는지 확인합니다.

  2. elementname 속성이 없거나, 해당 name 속성이 빈 문자열인 경우, return합니다.

  3. documentelement노드 문서로 설정합니다.

  4. oldFlagdocument변이 이벤트 플래그 발화의 값으로 설정합니다.

  5. document변이 이벤트 플래그 발화를 false로 설정합니다.

  6. groupMemberselementdetails 이름 그룹 내에서 element를 제외한 모든 요소를 포함하는 목록으로 설정합니다. 이 목록은 트리 순서로 정렬됩니다.

  7. groupMembersotherElement에 대해:

    1. otherElementopen 속성이 설정되어 있는 경우:

      1. 단언: otherElementgroupMembers 내에서 open 속성이 설정된 유일한 요소임을 확인합니다.

      2. 제거 otherElementopen 속성을 제거합니다.

      3. 중단.

  8. document변이 이벤트 플래그 발화oldFlag로 설정합니다.

details 요소 element가 주어진 경우, 필요한 경우 해당 요소를 닫아 세부 사항 독점성을 보장하기 위해:

  1. elementopen 속성이 없는 경우, return합니다.

  2. elementname 속성이 없거나 해당 name 속성이 빈 문자열인 경우, return합니다.

  3. documentelement노드 문서로 설정합니다.

  4. oldFlagdocument변이 이벤트 플래그 발화의 값으로 설정합니다.

  5. document변이 이벤트 플래그 발화를 false로 설정합니다.

  6. groupMemberselementdetails 이름 그룹 내에서 element를 제외한 모든 요소를 포함하는 목록으로 설정합니다. 이 목록은 트리 순서로 정렬됩니다.

  7. groupMembersotherElement에 대해:

    1. otherElementopen 속성이 설정되어 있는 경우:

      1. 제거 elementopen 속성을 제거합니다.

      2. 중단.

  8. document변이 이벤트 플래그 발화oldFlag로 설정합니다.

HTMLDetailsElement/open

모든 현재 엔진에서 지원됩니다.

Firefox49+Safari6+Chrome10+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?

nameopen IDL 속성은 동일한 이름의 해당 콘텐츠 속성을 반영해야 합니다.

상위 세부 정보 표시 알고리즘currentNode에 대해 다음 단계를 실행합니다:

  1. currentNode평탄 트리 내에서 상위 노드를 가지고 있는 동안:

    1. currentNodedetails 요소의 두 번째 슬롯에 삽입된 경우:

      1. currentNodecurrentNode가 삽입된 details 요소로 설정합니다.

      2. 만약 currentNodeopen 속성이 설정되어 있지 않다면, currentNodeopen 속성을 빈 문자열로 설정합니다.

    2. 그렇지 않다면, currentNode평탄 트리 내에서 currentNode의 상위 노드로 설정합니다.

다음 예제는 details 요소를 사용하여 진행 보고서에서 기술 세부 정보를 숨기는 방법을 보여줍니다.

<section class="progress window">
 <h1>"Really Achieving Your Childhood Dreams" 복사 중</h1>
 <details>
  <summary>복사 중... <progress max="375505392" value="97543282"></progress> 25%</summary>
  <dl>
   <dt>전송 속도:</dt> <dd>452KB/s</dd>
   <dt>로컬 파일 이름:</dt> <dd>/home/rpausch/raycd.m4v</dd>
   <dt>원격 파일 이름:</dt> <dd>/var/www/lectures/raycd.m4v</dd>
   <dt>소요 시간:</dt> <dd>01:16:27</dd>
   <dt>색상 프로파일:</dt> <dd>SD (6-1-6)</dd>
   <dt>크기:</dt> <dd>320×240</dd>
  </dl>
 </details>
</section>

다음은 기본적으로 일부 제어를 숨기기 위해 details 요소를 사용하는 방법을 보여줍니다:

<details>
 <summary><label for=fn>이름 및 확장자:</label></summary>
 <p><input type=text id=fn name=fn value="Pillar Magazine.pdf">
 </p><label><input type=checkbox name=ext checked> 확장자 숨기기</label>
</details>

이것은 목록의 다른 details 요소와 함께 사용되어 사용자가 필드 세트를 작은 제목 세트로 축소하고 각 제목을 열 수 있도록 할 수 있습니다.

이 예제에서는 요약이 실제 값이 아닌 제어할 수 있는 내용을 요약하고 있어 이상적이지 않습니다.

다음 예제는 name 속성을 사용하여 독점적인 아코디언을 생성하는 방법을 보여줍니다. 사용자가 하나의 details 요소를 열면 다른 열린 details 요소가 닫히게 됩니다.

<section class="characteristics">
 <details name="frame-characteristics">
  <summary>재질</summary>
  사진 액자는 단단한 참나무로 만들어졌습니다.
 </details>
 <details name="frame-characteristics"> 
  <summary>크기</summary>
  사진 액자는 40cm 높이와 30cm 너비의 사진에 맞습니다.
  액자 크기는 45cm 높이, 35cm 너비, 두께 2cm입니다.
 </details>
 <details name="frame-characteristics">
  <summary>색상</summary>
  사진 액자는 자연 목재 색상 또는 검정 얼룩 색상으로 제공됩니다.
 </details>
</section>

다음 예제는 open 속성이 독점적인 아코디언을 생성하기 위해 name 속성을 사용하는 요소 집합의 일부인 details 요소에 설정되었을 때 일어나는 일을 보여줍니다.

초기 마크업은 다음과 같습니다:

<section class="characteristics">
 <details name="frame-characteristics" id="d1" open>...</details> 
 <details name="frame-characteristics" id="d2">...</details> 
 <details name="frame-characteristics" id="d3">...</details> 
</section>

그리고 스크립트:

document.getElementById("d2").setAttribute("open", "");

스크립트가 실행된 후 결과 트리는 다음과 같이 마크업과 동일하게 됩니다:

<section class="characteristics">
 <details name="frame-characteristics" id="d1">...</details> 
 <details name="frame-characteristics" id="d2" open>...</details> 
 <details name="frame-characteristics" id="d3">...</details> 
</section>

이 경우 d2open 속성을 설정하면 d1open 속성이 제거됩니다.

사용자가 d2 내부의 summary 요소를 활성화할 때도 동일한 일이 발생합니다.

사용자가 제어와 상호작용할 때 open 속성이 자동으로 추가되고 제거되기 때문에, 이를 사용하여 요소의 상태에 따라 요소를 다르게 스타일링할 수 있습니다. 여기서는 스타일 시트를 사용하여 요소가 열리거나 닫힐 때 요약의 색상을 애니메이션하는 예시를 보여줍니다:

<style>
 details > summary { transition: color 1s; color: black; }
 details[open] > summary { color: red; }
</style>
<details> 
 <summary>자동 상태: 작동 중</summary> 
 <p>속도: 12m/s</p> 
 </p>방향: 북쪽</p> 
</details>

4.11.2 summary 요소

Element/summary

모든 현재 엔진에서 지원됩니다.

Firefox49+Safari6+Chrome12+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android?
카테고리:
없음.
이 요소를 사용할 수 있는 맥락:
details 요소의 첫 번째 자식으로 사용됩니다.
내용 모델:
구문 내용과 선택적으로 제목 내용이 혼합될 수 있습니다.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
내용 속성:
글로벌 속성
접근성 고려사항:
작성자용.
구현자용.
DOM 인터페이스:
HTMLElement를 사용합니다.

summary 요소는 details 요소의 나머지 내용에 대한 요약, 캡션 또는 전설을 나타냅니다.

다음 알고리즘이 true를 반환하는 경우 summary 요소는 상위 details의 요약입니다:

  1. summary 요소에 상위 요소가 없으면 false를 반환합니다.

  2. parent를 이 summary 요소의 상위 요소로 설정합니다.

  3. parentdetails 요소가 아니면 false를 반환합니다.

  4. parent의 첫 번째 summary 자식 요소가 이 summary 요소가 아니면 false를 반환합니다.

  5. true를 반환합니다.

summary 요소의 활성화 동작은 다음 단계를 실행합니다:

  1. summary 요소가 상위 details의 요약이 아닌 경우 return합니다.

  2. parent를 이 summary 요소의 상위 요소로 설정합니다.

  3. parentopen 속성이 존재하면 이를 제거합니다. 그렇지 않으면 설정하여 parentopen 속성을 빈 문자열로 만듭니다.

    이 작업은 세부 정보 알림 작업 단계를 실행하게 됩니다.

4.11.3 명령

4.11.3.1 측면

명령은 메뉴 항목, 버튼 및 링크 뒤에 있는 추상화입니다. 명령이 정의되면 인터페이스의 다른 부분에서 동일한 명령을 참조할 수 있으며, 이를 통해 비활성화 상태와 같은 측면을 여러 액세스 포인트가 공유할 수 있습니다.

명령은 다음과 같은 측면을 가지도록 정의됩니다:

레이블
사용자가 보는 명령의 이름.
액세스 키
명령을 트리거하는 사용자 에이전트가 선택한 키 조합. 명령에는 액세스 키가 없을 수 있습니다.
숨김 상태
명령이 숨겨져 있는지 여부(기본적으로 메뉴에 표시할지 여부).
비활성화 상태
명령이 관련 있고 트리거될 수 있는지 여부.
동작
명령을 트리거했을 때 발생하는 실제 효과. 이 동작은 스크립트 이벤트 핸들러, URL로의 이동 또는 양식 제출일 수 있습니다.

사용자 에이전트는 다음 기준에 맞는 명령을 노출할 수 있습니다:

사용자 에이전트는 이러한 명령이 액세스 키를 가지고 있는 경우, 해당 키를 사용자에게 알리는 방법으로 이를 노출하는 것이 좋습니다.

예를 들어, 이러한 명령은 사용자 에이전트의 메뉴 바에 나열될 수 있습니다.

4.11.3.2 a 요소를 사용하여 명령 정의

a 요소에 href 속성이 있으면 명령을 정의합니다.

명령의 레이블은 요소의 하위 텍스트 콘텐츠입니다.

명령의 액세스 키는 요소의 지정된 액세스 키입니다(있는 경우).

명령의 숨김 상태는 요소에 숨김 속성이 있는 경우 true(숨김)이고, 그렇지 않은 경우 false입니다.

명령의 비활성화 상태 측면은 요소나 그 조상 중 하나가 비활성화된 상태일 경우 true이며, 그렇지 않은 경우 false입니다.

명령의 동작은 요소에서 클릭 이벤트를 발생시키는 것입니다.

4.11.3.3 button 요소를 사용하여 명령 정의

button 요소는 항상 명령을 정의합니다.

명령의 레이블, 액세스 키, 숨김 상태동작 측면은 이전 섹션에서 설명한 대로 a 요소와 동일하게 결정됩니다.

명령의 비활성화 상태는 요소나 그 조상 중 하나가 비활성화 상태이거나 요소의 비활성화된 상태가 설정된 경우 true이며, 그렇지 않은 경우 false입니다.

4.11.3.4 input 요소를 사용하여 명령 정의

input 요소의 type 속성이 제출 버튼, 재설정 버튼, 이미지 버튼, 버튼, 라디오 버튼 또는 체크박스 상태 중 하나에 있으면 명령을 정의합니다.

명령의 레이블은 다음과 같이 결정됩니다:

비록 value 속성이 이미지 버튼 상태의 input 요소에서 비호환적이더라도, 속성이 존재하고 이미지 버튼의 alt 속성이 없을 때, 여전히 레이블 결정에 기여할 수 있습니다.

명령의 액세스 키는 요소의 지정된 액세스 키입니다(있는 경우).

명령의 숨김 상태는 요소에 숨김 속성이 있는 경우 true(숨김)이고, 그렇지 않은 경우 false입니다.

명령의 비활성화 상태는 요소나 그 조상 중 하나가 비활성화 상태이거나 요소의 비활성화 상태가 설정된 경우 true이며, 그렇지 않은 경우 false입니다.

명령의 동작은 요소에서 클릭 이벤트를 발생시키는 것입니다.

4.11.3.5 option 요소를 사용하여 명령 정의

option 요소가 조상 select 요소를 가지고 있으며, value 속성이 없거나 value 속성이 비어 있지 않은 경우 명령을 정의합니다.

명령의 레이블option 요소의 label 속성 값이 있으면 그것이 레이블이 되고, 그렇지 않으면 option 요소의 하위 텍스트 콘텐츠가 레이블이 됩니다. 이때 ASCII 공백이 제거되고 축약된 상태로 사용됩니다.

명령의 액세스 키는 요소의 지정된 액세스 키입니다(있는 경우).

명령의 숨김 상태는 요소에 숨김 속성이 있는 경우 true(숨김)이고, 그렇지 않은 경우 false입니다.

명령의 비활성화 상태는 요소가 비활성화된 상태이거나, 요소의 가장 가까운 조상 select 요소가 비활성화된 상태이거나, 요소 또는 그 조상 중 하나가 비활성화된 상태인 경우 true이며, 그렇지 않은 경우 false입니다.

option의 가장 가까운 조상 select 요소에 multiple 속성이 있는 경우, 명령의 동작option 요소를 토글하는 것이고, 그렇지 않은 경우 명령의 동작option 요소를 선택하는 것입니다.

4.11.3.6 legend 요소에서 accesskey 속성을 사용하여 명령 정의

legend 요소는 다음 조건이 모두 참일 때 명령을 정의합니다.

명령의 레이블은 요소의 하위 텍스트 콘텐츠입니다.

명령의 액세스 키는 요소의 지정된 액세스 키입니다.

명령의 숨김 상태, 비활성화 상태동작 속성은 해당 legend 요소의 accesskey 대리자의 해당 속성과 동일합니다.

이 예제에서 legend 요소는 accesskey를 지정하며, 활성화되면 input 요소에 위임됩니다.

<fieldset>
<legend accesskey=p>
 <label>I want <input name=pizza type=number step=1 value=1 min=0> pizza(s) with these toppings </label>
</legend>
<label><input name=pizza-cheese type=checkbox checked> Cheese </label>
<label><input name=pizza-ham type=checkbox checked> Ham </label>
<label><input name=pizza-pineapple type=checkbox> Pineapple </label>
</fieldset>
4.11.3.7 accesskey 속성을 사용하여 다른 요소에서 명령 정의

지정된 액세스 키가 있는 요소는 명령을 정의합니다.

이전 섹션 중 하나가 이 요소에 대해 명령을 정의한다고 정의한 경우, 해당 섹션이 이 요소에 적용되며, 이 섹션은 적용되지 않습니다. 그렇지 않으면 이 섹션이 해당 요소에 적용됩니다.

명령의 레이블은 요소에 따라 다릅니다. 요소가 라벨이 있는 컨트롤인 경우, 하위 텍스트 콘텐츠가 트리 순서로 첫 번째 라벨 요소인 경우, 해당 텍스트 콘텐츠가 명령의 레이블입니다. (JavaScript 용어로는 element.labels[0].textContent에 해당합니다.) 그렇지 않으면 명령의 레이블은 요소의 하위 텍스트 콘텐츠입니다.

명령의 액세스 키는 요소의 지정된 액세스 키입니다.

명령의 숨김 상태는 요소에 숨김 속성이 있는 경우 참(숨김)이고, 그렇지 않으면 거짓입니다.

명령의 비활성화 상태는 요소나 그 조상 중 하나가 비활성 상태인 경우 참이고, 그렇지 않으면 거짓입니다.

명령의 동작은 다음 단계를 실행하는 것입니다:

  1. 요소에 대해 포커싱 단계를 실행합니다.
  2. 요소에서 클릭 이벤트를 발생시킵니다.

4.11.4 dialog 요소

Element/dialog

모든 현재 엔진에서 지원됩니다.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (레거시)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLDialogElement

모든 현재 엔진에서 지원됩니다.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (레거시)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
이 요소를 사용할 수 있는 맥락:
플로우 콘텐츠가 예상되는 곳.
콘텐츠 모델:
플로우 콘텐츠.
텍스트/HTML에서 태그 생략:
두 태그 모두 생략할 수 없습니다.
콘텐츠 속성:
전역 속성
open — 다이얼로그 상자가 표시되는지 여부
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLDialogElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean open;
  attribute DOMString returnValue;
  [CEReactions] undefined show();
  [CEReactions] undefined showModal();
  [CEReactions] undefined close(optional DOMString returnValue);
};

dialog 요소는 사용자가 작업을 수행하거나 정보를 수집하기 위해 상호 작용하는 작은 창(“대화 상자”)의 형태로 애플리케이션의 일시적인 부분을 나타냅니다. 사용자가 작업을 완료하면 다이얼로그가 애플리케이션에 의해 자동으로 닫히거나 사용자가 수동으로 닫을 수 있습니다.

모든 종류의 애플리케이션에서 친숙한 패턴인 모달 대화 상자의 경우, 저자는 웹 애플리케이션의 대화 상자가 비웹 애플리케이션 사용자에게 친숙한 방식으로 동작하도록 해야 합니다.

모든 HTML 요소와 마찬가지로, 다른 유형의 제어를 나타내려고 할 때 dialog 요소를 사용하는 것은 적합하지 않습니다. 예를 들어, 컨텍스트 메뉴, 도구 설명 및 팝업 목록 상자는 대화 상자가 아니므로 이러한 패턴을 구현하기 위해 dialog 요소를 남용하는 것은 잘못된 것입니다.

사용자 대면 대화 상자 동작의 중요한 부분은 초기 포커스 배치입니다. 대화 상자 포커싱 단계는 대화 상자가 표시될 때 초기 포커스의 좋은 후보를 선택하려고 하지만, 특정 대화 상자에 대한 사용자 기대에 맞는 올바른 선택을 신중하게 생각하는 저자를 대체할 수는 없습니다. 따라서 저자는 대화 상자가 열리면 사용자가 즉시 상호 작용해야 하는 대화 상자의 하위 요소에 autofocus 속성을 사용해야 합니다. 그런 요소가 없는 경우 저자는 autofocus 속성을 dialog 요소 자체에 사용해야 합니다.

다음 예제에서는 인벤토리 관리 웹 애플리케이션에서 제품의 세부 정보를 편집하기 위해 대화 상자가 사용됩니다.

<dialog>
  <label>제품 번호 <input type="text" readonly></label>
  <label>제품 이름 <input type="text" autofocus></label>
</dialog>

만약 autofocus 속성이 없었다면, 대화 상자 포커싱 단계에 의해 제품 번호 필드에 포커스가 맞춰졌을 것입니다. 이는 합리적인 동작이지만, 저자는 제품 번호 필드가 읽기 전용이고 사용자 입력을 기대하지 않기 때문에 더 관련성 높은 제품 이름 필드에 포커스를 맞추는 것이 더 적절하다고 판단하여, 기본 설정을 재정의하기 위해 autofocus를 사용했습니다.

심지어 저자가 기본적으로 제품 번호 필드에 포커스를 맞추고 싶다면, 해당 input 요소에 autofocus를 사용하여 이를 명시적으로 지정하는 것이 좋습니다. 이렇게 하면 코드의 의도가 후속 독자에게 명확해지고, 향후 업데이트에 대한 견고성을 보장할 수 있습니다. (예를 들어, 다른 개발자가 닫기 버튼을 추가하고 이를 제품 번호 필드 앞에 노드 트리에 배치할 경우).

사용자 동작의 또 다른 중요한 측면은 대화 상자가 스크롤 가능한지 여부입니다. 일부 경우에는 사용자의 높은 텍스트 확대 설정으로 인해 오버플로우(및 따라서 스크롤 가능성)가 피할 수 없게 되지만, 일반적으로 사용자는 스크롤 가능한 대화 상자를 기대하지 않습니다. 대화 상자 요소에 큰 텍스트 노드를 직접 추가하는 것은 특히 나쁜데, 이는 대화 상자 요소 자체가 오버플로우되기 쉽기 때문입니다. 저자는 이를 피하는 것이 좋습니다.

다음 서비스 약관 대화 상자는 위의 권장 사항을 준수합니다.

<dialog style="height: 80vh;">
  <div style="overflow: auto; height: 60vh;" autofocus>
    <p>이 웹사이트를 통해 2010년 4월 1일에 주문을 제출함으로써, 귀하는 우리의 비양도 옵션을 부여하는 데 동의하며, 이 옵션은 현재 및 영원히 귀하의 불멸의 영혼을 청구할 수 있는 옵션입니다.</p>
    <p>우리가 이 옵션을 행사하기로 결정할 경우, 귀하는 이 사이트 또는 그 정당한 권한을 부여받은 하인의 서면 통지를 받은 후 5(오) 근무일 이내에 귀하의 불멸의 영혼과 그에 대한 모든 권리를 양도하는 데 동의합니다.</p>
    <!-- ... 등, 더 많은 <p> 요소가 포함된 ... -->
  </div>
  <form method="dialog">
    <button type="submit" value="agree">동의</button>
    <button type="submit" value="disagree">동의 안 함</button>
  </form>
</dialog>

대화 상자 포커싱 단계가 기본적으로 스크롤 가능한 div 요소를 선택했겠지만, 이전 예와 마찬가지로 autofocusdiv에 지정하여 더 명확하고 미래의 변경에도 견고하도록 했습니다.

대조적으로, 서비스 약관을 설명하는 p 요소가 이러한 래퍼 div 요소를 포함하지 않았다면, dialog 자체가 스크롤 가능하게 되어 위의 권장 사항을 위반했을 것입니다. 또한, autofocus 속성이 없는 경우, 이러한 마크업 패턴은 위의 권장 사항을 위반하고 대화 상자 포커싱 단계의 기본 동작을 방해하여, 동의 버튼으로 포커스가 이동하게 되어 사용자 경험이 나빠집니다.

open 속성은 불리언 속성입니다. 이 속성이 지정되면 dialog 요소가 활성화되어 사용자가 상호 작용할 수 있음을 나타냅니다.

dialog 요소에 open 속성이 지정되지 않은 경우 사용자가 표시하지 않아야 합니다. 이 요구 사항은 스타일 계층을 통해 간접적으로 구현될 수 있습니다. 예를 들어, 권장 기본 렌더링을 지원하는 사용자 에이전트는 렌더링 섹션에 설명된 CSS 규칙을 사용하여 이 요구 사항을 구현합니다.

open 속성을 제거하면 일반적으로 대화 상자가 숨겨집니다. 그러나 그렇게 하면 몇 가지 이상한 추가 결과가 발생합니다:

이러한 이유로 open 속성을 수동으로 제거하지 않는 것이 좋습니다. 대신, close() 메서드를 사용하여 대화 상자를 닫거나 hidden 속성을 사용하여 숨기는 것이 좋습니다.

tabindex 속성은 dialog 요소에 지정되어서는 안 됩니다.

dialog.show()

HTMLDialogElement/show

모든 현재 엔진에서 지원됩니다.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

dialog 요소를 표시합니다.

dialog.showModal()

HTMLDialogElement/showModal

모든 현재 엔진에서 지원됩니다.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

dialog 요소를 표시하고, 이를 최상위 모달 대화 상자로 만듭니다.

이 메서드는 autofocus 속성을 따릅니다.

dialog.close([ result ])

HTMLDialogElement/close

모든 현재 엔진에서 지원됩니다.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

dialog 요소를 닫습니다.

인수가 제공된 경우, 이를 반환값으로 설정합니다.

dialog.returnValue [ = result ]

HTMLDialogElement/returnValue

모든 현재 엔진에서 지원됩니다.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

dialog의 반환값을 반환합니다.

설정할 수 있으며, 반환값을 업데이트합니다.

show() 메서드 단계는 다음과 같습니다:

  1. thisopen 속성이 있고, is modal 플래그가 this에서 false로 설정되어 있다면, 이 메서드는 아무것도 하지 않고 종료합니다.

  2. thisopen 속성이 있는 경우, "InvalidStateError" DOMException 예외를 던집니다.

  3. this에 빈 문자열 값을 가지는 open 속성을 추가합니다.

  4. thispreviously focused element를 현재 focused 요소로 설정합니다.

  5. hideUntil 변수를 this에 대해 topmost popover ancestor를 실행한 결과로 설정합니다. 이때, null과 false를 인자로 사용합니다.

  6. hideUntil이 null이라면, thisnode document로 설정합니다.

  7. hideUntil을 인자로 하여 false와 true로 설정된 상태에서 hide all popovers until을 실행합니다.

  8. dialog focusing stepsthis에 대해 실행합니다.

showModal() 메서드 단계는 다음과 같습니다:

  1. thisopen 속성이 있고, is modal 플래그가 true로 설정되어 있다면, 이 메서드는 아무것도 하지 않고 종료합니다.

  2. thisopen 속성이 있는 경우, "InvalidStateError" DOMException 예외를 던집니다.

  3. thisconnected 상태가 아니라면, "InvalidStateError" DOMException 예외를 던집니다.

  4. thispopover showing state 상태에 있다면, "InvalidStateError" DOMException 예외를 던집니다.

  5. this에 빈 문자열 값을 가지는 open 속성을 추가합니다.

  6. is modal 플래그를 this에 대해 true로 설정합니다.

  7. thisnode documentblocked by the modal dialog 상태로 만듭니다.

    이로 인해 문서의 focused areainert 상태가 됩니다. 단, 현재 포커스된 영역이 subjectshadow-including descendant가 아닌 경우에만 해당됩니다. 이러한 경우, 문서의 focused area는 곧 reset되어 viewport로 변경됩니다. 몇 단계 후에 더 나은 포커스 대상을 찾기 위한 시도를 할 것입니다.

  8. 만약 thisnode 문서최상위 레이어가 이미 포함하지 않는다면 this최상위 레이어에 추가합니다 this.

  9. thisclose watcherclose watcher 설정의 결과로 설정합니다 this관련된 전역 객체와 함께:

  10. this이전에 포커스된 요소포커스된 요소로 설정합니다.

  11. hideUntil최상위 팝오버 조상 실행의 결과로 설정합니다 this, null, 그리고 false를 사용하여.

  12. 만약 hideUntil이 null이라면, hideUntilthisnode 문서로 설정합니다.

  13. 모든 팝오버를 숨깁니다, hideUntil, false, 그리고 true를 사용하여 실행합니다.

  14. 대화 상자 포커스 단계this를 사용하여 실행합니다.

dialog focusing stepsdialog 요소 subject를 대상으로 다음과 같이 실행됩니다:

  1. control 변수를 null로 설정합니다.

  2. subjectautofocus 속성이 있으면, controlsubject로 설정합니다.

  3. control이 null이라면, controlsubjectfocus delegate로 설정합니다.

  4. control이 여전히 null이라면, controlsubject로 설정합니다.

  5. control에 대해 focusing steps를 실행합니다.

    controlfocusable하지 않으면, 이 작업은 아무것도 하지 않습니다. 이는 subject가 focus delegate를 가지고 있지 않고, 사용자 에이전트가 dialog 요소가 일반적으로 focusable하지 않다고 판단한 경우에만 발생합니다. 이 경우, 이전에 문서의 focused area에 대한 수정 사항이 적용됩니다.

  6. topDocument 변수를 controlnode navigabletop-level traversableactive document로 설정합니다.

  7. controlnode documentorigintopDocumentorigin과 동일하지 않다면, 이 작업은 아무것도 하지 않고 종료합니다.

  8. topDocumentautofocus candidates를 비웁니다.

  9. topDocumentautofocus processed flag를 true로 설정합니다.

dialog HTML element removing steps는, removedNodeoldParent를 대상으로 다음과 같이 실행됩니다:

  1. removedNodeclose watcher가 null이 아니라면, 다음 단계를 실행합니다:

    1. Destroy removedNodeclose watcher.

    2. removedNodeclose watcher를 null로 설정합니다.

  2. removedNodenode documenttop layerremovedNode를 포함하고 있다면, remove an element from the top layer immediately 작업을 실행합니다.

  3. removedNodeis modal 플래그를 false로 설정합니다.

close(returnValue) 메서드 단계는 다음과 같습니다:

  1. returnValue가 주어지지 않았다면, 이를 null로 설정합니다.

  2. Close the dialog 작업을 thisreturnValue를 사용하여 실행합니다.

dialog 요소 subject닫는 경우, null 또는 문자열 result를 사용하여 다음 단계를 실행합니다:

  1. subjectopen 속성이 없으면, 이 작업은 아무것도 하지 않고 종료합니다.

  2. subjectopen 속성을 제거합니다.

  3. subjectis modal 플래그가 true라면, 요소를 top layer에서 제거하도록 요청 작업을 subject에 대해 실행합니다.

  4. wasModal 변수를 subjectis modal 플래그 값으로 설정합니다.

  5. subjectis modal 플래그를 false로 설정합니다.

  6. result가 null이 아닌 경우, returnValue 속성을 result로 설정합니다.

  7. subjectpreviously focused element가 null이 아닌 경우, 다음 단계를 실행합니다:

    1. element 변수를 subjectpreviously focused element로 설정합니다.

    2. subjectpreviously focused element를 null로 설정합니다.

    3. subjectnode documentfocused areaDOM anchorelementshadow-including inclusive descendant이거나, wasModal이 true라면, focusing steps 작업을 element에 대해 실행합니다. 이 단계를 실행할 때는 뷰포트가 스크롤되지 않아야 합니다.

  8. 요소 작업을 대기열에 추가 작업을 subject 요소에 대해 실행하여, fire an event 작업을 close 이름으로 subject에서 실행합니다.

  9. subjectclose watcher가 null이 아닌 경우, 다음 단계를 실행합니다:

    1. Destroy subjectclose watcher.

    2. subjectclose watcher를 null로 설정합니다.

returnValue IDL 속성은, 해당 값이 설정된 마지막 값을 반환해야 하며, 새로운 값으로 설정할 때는 새 값으로 설정해야 합니다. 요소가 생성될 때는 빈 문자열로 설정되어야 합니다.

우리는 dialog 요소에 대해 show/close를 동사로 사용합니다. 더 일반적으로 생각되는 반의어 쌍인 show/hide 또는 open/close 대신 다음과 같은 제약이 있기 때문입니다:

게다가, 조사에 따르면, dialog 요소의 원래 설계 당시 다른 많은 UI 프레임워크에서 show/close 동사 쌍이 적당히 일반적이었습니다.

결론적으로, 특정 동사의 함축과 기술 맥락에서의 사용 방식으로 인해, 대화 상자를 보여주고 닫는 동작이 항상 반의어로 표현될 수는 없다는 것이 밝혀졌습니다.


dialog 요소에는 닫기 감시자(close watcher)가 있으며, 이는 닫기 감시자 또는 null로 초기값은 null입니다.

dialog 요소에는 모달(modal) 여부 플래그가 있습니다. dialog 요소가 생성될 때, 이 플래그는 false로 설정되어야 합니다.

HTML 요소에는 이전에 포커스를 받은 요소가 있으며, 이는 null 또는 요소이며, 초기값은 null입니다. showModal()show()가 호출될 때, 이 요소는 대화 상자 포커스 단계(dialog focusing steps)를 실행하기 전에 현재 포커스된 요소로 설정됩니다. popover 속성을 가진 요소는 popover 표시 알고리즘(show popover algorithm) 중에 현재 포커스된 요소를 이 요소로 설정합니다.


HTMLDialogElement/open

모든 최신 엔진에서 지원됩니다.

Firefox98+ Safari15.4+ Chrome37+
Opera? Edge79+
Edge (Legacy)? Internet ExplorerNo
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

open IDL 속성은 반영해야 합니다. open 콘텐츠 속성에.

이 대화 상자에는 작은 글씨가 있습니다. strong 요소는 사용자의 주의를 더 중요한 부분으로 끌기 위해 사용됩니다.

<dialog>
 <h1>Add to Wallet</h1>
 <p><strong><label for=amt>How many gold coins do you want to add to your wallet?</label></strong></p>
 <p><input id=amt name=amt type=number min=0 step=0.01 value=100></p>
 <p><small>You add coins at your own risk.</small></p>
 <p><label><input name=round type=checkbox> Only add perfectly round coins</label></p>
 <p><input type=button onclick="submit()" value="Add Coins"></p>
</dialog>

4.12 스크립트

스크립트를 사용하면 작성자가 문서에 상호작용성을 추가할 수 있습니다.

가능한 경우 스크립트 대신 선언적 대안을 사용하는 것이 권장됩니다. 선언적 메커니즘은 종종 유지 관리가 더 쉬우며 많은 사용자가 스크립트를 비활성화합니다.

예를 들어, 더 많은 세부 정보를 표시하기 위해 섹션을 표시하거나 숨기기 위해 스크립트를 사용하는 대신, details 요소를 사용할 수 있습니다.

작성자는 또한 스크립트 지원이 없는 경우에도 애플리케이션이 정상적으로 작동하도록 하는 것이 권장됩니다.

예를 들어, 작성자가 테이블 헤더에 동적으로 테이블을 정렬하는 링크를 제공하는 경우, 스크립트 없이도 작동하도록 링크를 만들어 서버에서 정렬된 테이블을 요청할 수 있습니다.

4.12.1 script 요소

요소/script

모든 현재 엔진에서 지원됩니다.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer
Firefox Android4+ Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

HTMLScriptElement

모든 현재 엔진에서 지원됩니다.

Firefox1+ Safari3+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android37+ Samsung Internet? Opera Android12.1+
카테고리:
메타데이터 콘텐츠.
플로우 콘텐츠.
구문 콘텐츠.
스크립트 지원 요소.
이 요소가 사용될 수 있는 컨텍스트:
메타데이터 콘텐츠가 예상되는 곳.
구문 콘텐츠가 예상되는 곳.
스크립트 지원 요소가 예상되는 곳.
콘텐츠 모델:
src 속성이 없으면, type 속성의 값에 따라 달라지지만, 스크립트 콘텐츠 제한 사항과 일치해야 합니다.
src 속성이 있는 경우, 요소는 비어 있거나, 스크립트 설명서만 포함해야 하며, 스크립트 콘텐츠 제한 사항과 일치해야 합니다.
text/html에서 태그 생략:
태그는 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
src — 리소스 주소
type — 스크립트 유형
nomodule모듈 스크립트를 지원하는 사용자 에이전트에서 실행 방지
async — 가져오는 동안 차단하지 않고, 스크립트가 사용 가능해질 때 실행
defer — 스크립트 실행을 지연시킴
crossorigin — 요소가 교차 출처 요청을 처리하는 방법
integrity서브리소스 무결성 검사에 사용되는 무결성 메타데이터 [SRI]
referrerpolicy — 요소가 시작한 가져오기에 대한 참조 정책
blocking — 요소가 렌더링을 차단할 가능성이 있는지 여부
fetchpriority — 요소가 시작한 가져오기우선순위 설정
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLScriptElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute boolean noModule;
  [CEReactions] attribute boolean async;
  [CEReactions] attribute boolean defer;
  [CEReactions] attribute DOMString? crossOrigin;
  [CEReactions] attribute DOMString text;
  [CEReactions] attribute DOMString integrity;
  [CEReactions] attribute DOMString referrerPolicy;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList blocking;
  [CEReactions] attribute DOMString fetchPriority;

  static boolean supports(DOMString type);

  // 도 사용되지 않는 멤버가 있습니다
};

script 요소는 저자가 문서에 동적 스크립트와 데이터 블록을 포함할 수 있도록 합니다. 이 요소는 사용자에게 표시되는 콘텐츠를 표현하지 않습니다.

요소/script#attr-type

모든 현재 엔진에서 지원됩니다.

Firefox1+ Safari≤4+ Chrome1+
Opera? Edge79+
Edge (Legacy)12+ Internet Explorer
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

type 속성은 표현되는 스크립트의 유형을 사용자 정의할 수 있도록 합니다:

데이터 블록유효한 MIME 유형 문자열을 사용하여 나타내야 한다는 요구 사항은 잠재적인 미래의 충돌을 피하기 위한 것입니다. 이 명세서가 추가적인 스크립트 유형을 추가할 경우, type 속성을 MIME 유형이 아닌 값으로 설정하여 트리거됩니다. 예를 들어, "module" 값이 모듈 스크립트를 나타내는 것과 같습니다. 지금 유효한 MIME 유형 문자열을 사용함으로써, 미래의 사용자 에이전트에서도 데이터 블록이 다른 스크립트 유형으로 다시 해석되지 않도록 보장할 수 있습니다.

고전적인 스크립트JavaScript 모듈 스크립트는 인라인으로 포함하거나, src 속성을 사용하여 외부 파일에서 가져올 수 있습니다. 이 속성이 지정된 경우, 사용할 외부 스크립트 리소스의 URL을 제공합니다. src가 지정된 경우, 이는 유효한 비어 있지 않은 URL(주변에 공백이 있을 수 있음)이어야 합니다.

인라인 script 요소의 내용 또는 외부 스크립트 리소스는 고전적인 스크립트JavaScript 모듈 스크립트에 대해 각각 JavaScript 명세의 스크립트 또는 모듈 생산 요구 사항을 준수해야 합니다. [JAVASCRIPT]

CSS 모듈 스크립트에 대한 외부 스크립트 리소스의 내용은 CSS 명세의 요구 사항을 준수해야 합니다. [CSS]

JSON 모듈 스크립트에 대한 외부 스크립트 리소스의 내용은 JSON 명세의 요구 사항을 준수해야 합니다. [JSON]

import map에 대한 인라인 script 요소의 내용은 import map 작성 요구 사항을 준수해야 합니다.

import map script 요소의 경우, src, async, nomodule, defer, crossorigin, integrityreferrerpolicy 속성은 지정되어서는 안 됩니다.

문서에는 import map script 요소가 하나만 있어야 합니다.

데이터 블록을 포함하기 위해 사용되는 경우, 데이터는 인라인으로 포함되어야 하며, 데이터의 형식은 type 속성을 사용하여 제공되어야 하며, script 요소의 내용은 사용된 형식에 대해 정의된 요구 사항을 준수해야 합니다. src, async, nomodule, defer, crossorigin, integrity, referrerpolicyfetchpriority 속성은 지정되어서는 안 됩니다.

nomodule 속성은 불리언 속성으로, 모듈 스크립트를 지원하는 사용자 에이전트에서 스크립트가 실행되지 않도록 합니다. 이를 통해 최신 사용자 에이전트에서 모듈 스크립트와 이전 사용자 에이전트에서 고전적인 스크립트를 선택적으로 실행할 수 있습니다. nomodule 속성은 모듈 스크립트에 지정되어서는 안 됩니다(지정된 경우 무시됩니다).

요소/script#attr-async

모든 현재 엔진에서 지원됩니다.

Firefox1+ Safari≤4+ Chrome1+
Opera? Edge79+
Edge (Legacy)12+ Internet Explorer
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

요소/script#attr-defer

모든 현재 엔진에서 지원됩니다.

Firefox3.5+ Safari3+ Chrome1+
Opera? Edge79+
Edge (Legacy)12+ Internet Explorer10+
Firefox Android4+ Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

asyncdefer 속성은 스크립트를 어떻게 평가할지를 나타내는 불리언 속성입니다. 고전적인 스크립트defer 또는 async를 지정할 수 있지만, src 속성이 존재하지 않으면 이 둘 중 하나를 지정해서는 안 됩니다. 모듈 스크립트async 속성을 지정할 수 있지만, defer 속성은 지정해서는 안 됩니다.

이 속성을 사용하여 선택할 수 있는 여러 모드가 있으며, 이는 스크립트의 유형에 따라 달라집니다.

고전적인 스크립트의 경우, async 속성이 있으면 고전적인 스크립트는 구문 분석과 병렬로 가져오며, 이용 가능해지는 대로 평가됩니다(구문 분석이 완료되기 전에 평가될 수 있음). async 속성이 없고 defer 속성이 있으면, 고전적인 스크립트는 구문 분석과 병렬로 가져오고 페이지의 구문 분석이 완료된 후 평가됩니다. 두 속성 모두 없는 경우, 스크립트는 즉시 가져와 평가되며, 이 과정에서 구문 분석이 완료될 때까지 차단됩니다.

모듈 스크립트의 경우, async 속성이 있으면 모듈 스크립트 및 해당 종속성이 구문 분석과 병렬로 가져와지며, 모듈 스크립트는 이용 가능해지는 대로 평가됩니다(구문 분석이 완료되기 전에 평가될 수 있음). 그렇지 않으면 모듈 스크립트와 그 종속성은 구문 분석과 병렬로 가져와지고 페이지의 구문 분석이 완료된 후 평가됩니다. (defer 속성은 모듈 스크립트에 영향을 미치지 않습니다.)

이는 다음의 도식도에서 요약됩니다:

스크립트를 사용할 경우, 구문 분석이 가져오기 및 실행에 의해 중단됩니다. defer 속성을 사용할 경우, 가져오기와 구문 분석이 병렬로 이루어지고, 구문 분석이 완료된 후 실행이 이루어집니다. async 속성을 사용할 경우, 가져오기가 구문 분석과 병렬로 이루어지지만, 완료되면 구문 분석이 중단되고 스크립트가 실행됩니다. 모듈 스크립트의 경우, 일반적인 스크립트의 defer 속성과 유사하지만, 종속성도 함께 가져옵니다. async 속성을 사용할 경우, 종속성을 포함한 모듈 스크립트의 처리도 일반적인 스크립트의 async 속성과 유사합니다.

이 속성들에 대한 정확한 처리 세부 사항은 주로 역사적인 이유로 다소 복잡하며, HTML의 여러 측면을 포함합니다. 따라서 구현 요구 사항은 명세 전체에 흩어져 있을 수밖에 없습니다. 아래의 알고리즘(이 섹션에서)은 이 처리의 핵심을 설명하지만, 이 알고리즘은 script 시작종료 태그, 외부 콘텐츠에서, XML에서, document.write() 메서드, 스크립팅 처리 등과 관련된 구문 분석 규칙을 참조하고 있습니다.

document.write() 메서드를 사용하여 삽입된 script 요소는 일반적으로 실행되며(보통 추가 스크립트 실행이나 HTML 구문 분석을 차단), innerHTMLouterHTML 속성을 사용하여 삽입된 경우에는 전혀 실행되지 않습니다.

defer 속성은 async 속성이 지정된 경우에도 지정할 수 있으며, async를 지원하지 않는( defer만 지원하는) 레거시 웹 브라우저에서 defer 동작으로 대체되도록 합니다.

crossorigin 속성은 CORS 설정 속성입니다. 고전적인 스크립트의 경우, 스크립트가 다른 출처에서 가져온 경우 오류 정보가 노출될지 여부를 제어합니다. 모듈 스크립트의 경우, 교차 출처 요청에 사용되는 자격 증명 모드를 제어합니다.

고전적인 스크립트와 달리, 모듈 스크립트는 교차 출처 가져오기에 CORS 프로토콜을 사용해야 합니다.

integrity 속성은 이 요소가 책임지는 요청에 대한 무결성 메타데이터를 나타냅니다. 값은 텍스트입니다. integrity 속성은 src 속성이 지정되지 않은 경우 지정되어서는 안 됩니다. [SRI]

referrerpolicy 속성은 참조 정책 속성입니다. 이 속성의 목적은 스크립트와 해당 스크립트에서 가져오는 모든 스크립트를 가져올 때 사용되는 참조 정책을 설정하는 것입니다. [REFERRERPOLICY]

script 요소의 referrer 정책이 가져온 스크립트에는 적용되지만 다른 하위 리소스에는 적용되지 않는 예:

<script referrerpolicy="origin">
  fetch('/api/data');    // <script>의 referrer 정책으로 가져오지 않음
  import('./utils.mjs'); // <script>의 referrer 정책("origin"으로 설정)이 적용됨
</script>

blocking 속성은 차단 속성입니다.

fetchpriority 속성은 가져오기 우선순위 속성입니다. 이 속성의 목적은 스크립트를 가져올 때 사용되는 우선순위를 설정하는 것입니다.

src, type, nomodule, async, defer, crossorigin, integrity, referrerpolicy, 그리고 fetchpriority 속성을 동적으로 변경하는 것은 직접적인 영향을 미치지 않습니다. 이 속성들은 아래에 설명된 특정 시점에만 사용됩니다.

src, type, defer, integrity, 그리고 blocking IDL 속성은 각각 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

HTMLScriptElement/referrerPolicy

모든 현재 엔진에서 지원됩니다.

Firefox65+ Safari14+ Chrome70+
Opera? Edge79+
Edge (Legacy)? Internet Explorer아니요
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

referrerPolicy IDL 속성은 referrerpolicy 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

fetchPriority IDL 속성은 fetchpriority 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

crossOrigin IDL 속성은 crossorigin 콘텐츠 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

noModule IDL 속성은 nomodule 콘텐츠 속성을 반영해야 합니다.

async 속성의 getter 단계는 다음과 같습니다:

  1. thisforce async가 true이면, true를 반환합니다.

  2. thisasync 콘텐츠 속성이 존재하면, true를 반환합니다.

  3. false를 반환합니다.

async 속성의 setter 단계는 다음과 같습니다:

  1. thisforce async를 false로 설정합니다.

  2. 주어진 값이 true인 경우, thisasync 콘텐츠 속성을 빈 문자열로 설정합니다.

  3. 그렇지 않으면, thisasync 콘텐츠 속성을 제거합니다.

script.text [ = value ]

요소의 자식 텍스트 콘텐츠를 반환합니다.

값을 설정하면 요소의 자식이 해당 값으로 대체됩니다.

HTMLScriptElement.supports(type)

주어진 type이 사용자 에이전트에서 지원되는 스크립트 유형인 경우 true를 반환합니다. 이 명세서에서 가능한 스크립트 유형은 "classic", "module", "importmap"이며, 향후 다른 유형이 추가될 수 있습니다.

text 속성의 getter는 이 script 요소의 자식 텍스트 콘텐츠를 반환해야 합니다.

text 속성의 setter는 이 script 요소 내의 값을 주어진 값으로 문자열 전체를 대체해야 합니다.

HTMLScriptElement/supports_static

모든 현재 엔진에서 지원됩니다.

Firefox94+ Safari16+ Chrome96+
Opera? Edge96+
Edge (Legacy)? Internet Explorer아니요
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

supports(type) 메서드의 단계는 다음과 같습니다:

  1. type이 "classic"이면 true를 반환합니다.

  2. type이 "module"이면 true를 반환합니다.

  3. type이 "importmap"이면 true를 반환합니다.

  4. false를 반환합니다.

type 인수는 이러한 값과 정확히 일치해야 합니다. ASCII 대소문자 구분 없이 일치하는 방식은 수행되지 않습니다. 이는 type 콘텐츠 속성 값이 처리되는 방식, DOMTokenListsupports() 메서드가 작동하는 방식과 다르지만, WorkerType 열거형이 Worker() 생성자에서 사용되는 방식과 일치합니다.

이 예에서는 두 개의 script 요소가 사용됩니다. 하나는 외부 고전적인 스크립트를 포함하고, 다른 하나는 데이터 블록으로 데이터를 포함합니다.

<script src="game-engine.js"></script>
<script type="text/x-game-map">
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>

이 데이터는 스크립트에서 비디오 게임의 지도를 생성하는 데 사용할 수 있습니다. 그러나 이 데이터가 반드시 그렇게 사용되어야 하는 것은 아닙니다. 예를 들어, 지도 데이터가 페이지의 다른 마크업에 포함되어 있을 수 있으며, 여기의 데이터 블록은 사이트의 검색 엔진이 사용자가 게임 지도에서 특정 기능을 찾도록 돕기 위해 사용될 수 있습니다.

다음 예제는 script 요소가 고전적인 스크립트의 일부로 문서의 다른 부분에서 사용되는 함수를 정의하는 데 어떻게 사용될 수 있는지 보여줍니다. 또한 script 요소가 문서를 구문 분석하는 동안 스크립트를 호출하여, 이 경우 양식의 출력을 초기화하는 방법을 보여줍니다.

<script>
 function calculate(form) {
   var price = 52000;
   if (form.elements.brakes.checked)
     price += 1000;
   if (form.elements.radio.checked)
     price += 2500;
   if (form.elements.turbo.checked)
     price += 5000;
   if (form.elements.sticker.checked)
     price += 250;
   form.elements.result.value = price;
 }
</script>
<form name="pricecalc" onsubmit="return false" onchange="calculate(this)">
 <fieldset>
  <legend>당신의 자동차 가격 계산</legend>
  <p>기본 가격: £52000.</p>
  <p>추가 옵션 선택:</p>
  <ul>
   <li><label><input type=checkbox name=brakes> 세라믹 브레이크 (£1000)</label></li>
   <li><label><input type=checkbox name=radio> 위성 라디오 (£2500)</label></li>
   <li><label><input type=checkbox name=turbo> 터보 차저 (£5000)</label></li>
   <li><label><input type=checkbox name=sticker> "XZ" 스티커 (£250)</label></li>
  </ul>
  <p>총액: £<output name=result></output></p>
 </fieldset>
 <script>
  calculate(document.forms.pricecalc);
 </script>
</form>

다음 예제는 script 요소가 외부 JavaScript 모듈 스크립트를 포함하는 방법을 보여줍니다.

<script type="module" src="app.mjs"></script>

이 모듈과 JavaScript import 구문을 통해 소스 파일에서 표현된 모든 종속성이 가져옵니다. 생성된 모듈 그래프가 모두 가져오고 문서의 구문 분석이 완료되면 app.mjs의 내용이 평가됩니다.

또한 동일한 Window에서 다른 script 요소에서 app.mjs 모듈을 가져오는 코드가 있다면(예: import "./app.mjs";를 통해), 이전 script 요소에 의해 생성된 동일한 JavaScript 모듈 스크립트가 가져옵니다.

이 예제는 최신 사용자 에이전트에서 JavaScript 모듈 스크립트를 포함하고, 오래된 사용자 에이전트에서는 고전적인 스크립트를 포함하는 방법을 보여줍니다:

<script type="module" src="app.mjs"></script>
<script nomodule defer src="classic-app-bundle.js"></script>

최신 사용자 에이전트에서는 script 요소가 nomodule 속성을 가진 경우 무시되며, script 요소에 type이 "module"인 경우 가져와서 평가됩니다(이는 JavaScript 모듈 스크립트로 평가됨). 반대로, 오래된 사용자 에이전트는 "module" 유형의 script 요소를 무시하며, 이는 그들에게 알려지지 않은 스크립트 유형이기 때문입니다. 그러나 이들은 nomodule 속성을 구현하지 않기 때문에 다른 script 요소를 가져와서 고전적인 스크립트로 평가하는 데 문제가 없습니다.

다음 예제는 script 요소를 사용하여 문서의 텍스트에 여러 가지 치환 작업을 수행하는 인라인 JavaScript 모듈 스크립트를 작성하는 방법을 보여줍니다. 이를 통해 보다 흥미로운 독서 경험을 제공할 수 있습니다(예: 뉴스 사이트에서): [XKCD1288]

<script type="module">
 import { walkAllTextNodeDescendants } from "./dom-utils.mjs";

 const substitutions = new Map([
   ["witnesses", "these dudes I know"]
   ["allegedly", "kinda probably"]
   ["new study", "Tumblr post"]
   ["rebuild", "avenge"]
   ["space", "spaaace"]
   ["Google glass", "Virtual Boy"]
   ["smartphone", "Pokédex"]
   ["electric", "atomic"]
   ["Senator", "Elf-Lord"]
   ["car", "cat"]
   ["election", "eating contest"]
   ["Congressional leaders", "river spirits"]
   ["homeland security", "Homestar Runner"]
   ["could not be reached for comment", "is guilty and everyone knows it"]
 ]);

 function substitute(textNode) {
   for (const [before, after] of substitutions.entries()) {
     textNode.data = textNode.data.replace(new RegExp(`\\b${before}\\b`, "ig"), after);
   }
 }

 walkAllTextNodeDescendants(document.body, substitute);
</script>

JavaScript 모듈 스크립트를 사용하여 얻을 수 있는 몇 가지 주요 기능으로는 다른 JavaScript 모듈에서 기능을 가져올 수 있는 기능, 기본적으로 엄격 모드, 최상위 선언이 전역 객체에 새로운 속성을 도입하지 않는다는 점 등이 있습니다. 또한 이 script 요소가 문서의 어디에 나타나든 상관없이 문서 구문 분석이 완료되고 종속성(dom-utils.mjs)이 가져와서 평가될 때까지 평가되지 않는다는 점도 주목해야 합니다.

다음 예제는 JSON 모듈 스크립트JavaScript 모듈 스크립트 내부에서 어떻게 가져올 수 있는지 보여줍니다:

<script type="module">
 import peopleInSpace from "http://api.open-notify.org/astros.json" with { type: "json" };

 const list = document.querySelector("#people-in-space");
 for (const { craft, name } of peopleInSpace.people) {
   const li = document.createElement("li");
   li.textContent = `${name} / ${craft}`;
   list.append(li);
 }
</script>

모듈 스크립트의 MIME 유형 검사 기준은 엄격합니다. JSON 모듈 스크립트의 가져오기가 성공하려면 HTTP 응답에 JSON MIME 유형이 있어야 합니다. 예를 들어 Content-Type: text/json과 같습니다. 반면에 with { type: "json" } 문장의 일부가 생략된 경우, JavaScript 모듈 스크립트를 가져오려는 의도인 것으로 가정하며, HTTP 응답에 JavaScript MIME 유형이 없는 경우 가져오기가 실패합니다.

4.12.1.1 처리 모델

script 요소는 여러 관련된 상태를 가지고 있습니다.

script 요소는 파서 문서를 가지고 있으며, 이는 null이거나 document입니다. 초기값은 null입니다. 이 값은 HTML 파서XML 파서에 의해 script 요소에 설정되며, 해당 요소의 처리에 영향을 미칩니다. null이 아닌 파서 문서를 가진 script 요소는 파서 삽입됨으로 알려져 있습니다.

script 요소는 준비 시간 문서를 가지고 있으며, 이는 null이거나 document입니다. 초기값은 null입니다. 이 값은 스크립트가 준비 중에 문서 간에 이동할 때 실행되지 않도록 방지하는 데 사용됩니다.

script 요소는 초기값이 true인 강제 비동기 불리언 값을 가지고 있습니다. 이 값은 HTML 파서XML 파서에 의해 script 요소에 설정되며, 요소에 async 콘텐츠 속성이 추가될 때 false로 설정됩니다.

script 요소는 초기값이 false인 외부 파일에서 가져옴 불리언 값을 가지고 있습니다. 이 값은 스크립트가 준비될 때, 그 시점의 요소의 src 속성에 따라 결정됩니다.

script 요소는 초기값이 false인 파서 실행 준비 완료 불리언 값을 가지고 있습니다. 이 값은 파서 삽입된 요소에만 사용되며, 파서가 스크립트를 실행할 시점을 알려줍니다.

script 요소는 초기값이 false인 이미 시작됨 불리언 값을 가지고 있습니다.

script 요소는 초기값이 false인 로드 이벤트 지연 불리언 값을 가지고 있습니다.

script 요소는 초기값이 null인 타입을 가지고 있으며, 이는 null, "classic", "module", 또는 "importmap" 중 하나입니다. 이 값은 준비 시점에서 요소의 type 속성에 따라 결정됩니다.

script 요소는 "초기화되지 않음", null(오류를 나타냄), 스크립트 또는 import map 파서 결과 중 하나인 결과를 가지고 있습니다. 초기값은 "초기화되지 않음"입니다.

script 요소는 일련의 단계 또는 null인 결과가 준비되었을 때 실행할 단계를 가지고 있으며, 초기값은 null입니다. 준비 완료로 표시를 하기 위해 script 요소 el스크립트, import map 파서 결과 또는 null result를 받았을 때 다음과 같이 진행합니다:

  1. el결과result로 설정합니다.

  2. 만약 el결과가 준비되었을 때 실행할 단계가 null이 아니라면, 그 단계를 실행합니다.

  3. el결과가 준비되었을 때 실행할 단계를 null로 설정합니다.

  4. el로드 이벤트 지연을 false로 설정합니다.


script 요소 el암묵적으로 잠재적으로 렌더링 차단 상태가 됩니다. 만약 el타입이 "classic"이고, el파서 삽입됨 상태이며, elasync 또는 defer 속성이 없으면 el은 렌더링 차단 상태가 됩니다.

복제 단계script 요소 el을 복제하여 복사본 copy를 생성할 때, copy이미 시작됨 값을 el이미 시작됨으로 설정합니다.

async 속성이 script 요소 el에 추가되면, 사용자 에이전트는 el강제 비동기 값을 false로 설정해야 합니다.

script 요소 el로드 이벤트 지연이 true인 경우, 사용자 에이전트는 로드 이벤트를 지연시켜야 합니다. el준비 시간 문서의 이벤트가 지연됩니다.


script 요소 el이 파서 삽입되지 않았을 때 다음 목록에 나열된 이벤트 중 하나를 경험하면, 사용자 에이전트는 스크립트 요소를 즉시 준비해야 합니다:

스크립트 요소를 준비하려면 script 요소 el을 사용하세요:

  1. 만약 el이미 시작됨이 true라면, 반환하세요.

  2. parser documentelparser document로 설정하세요.

  3. elparser document를 null로 설정하세요.

    이 작업은 파서에 의해 삽입된 script 요소들이 실행되지 않는 경우, 예를 들어 빈 상태이거나 지원되지 않는 스크립팅 언어를 지정한 경우에 다른 스크립트가 나중에 이를 변경하여 다시 실행할 수 있도록 하기 위해 수행됩니다.

  4. parser document가 null이 아니고 elasync 속성이 없는 경우, el강제 비동기를 true로 설정하세요.

    이 작업은 파서에 의해 삽입된 script 요소가 실행되지 않았을 때, 스크립트가 이를 동적으로 업데이트한 후 실행되더라도 async 속성이 설정되지 않았더라도 비동기 방식으로 실행되도록 하기 위해 수행됩니다.

  5. source textel자식 텍스트 내용으로 설정하세요.

  6. elsrc 속성이 없고, source text가 빈 문자열인 경우, 반환하세요.

  7. el연결된 상태가 아닌 경우, 반환하세요.

  8. 다음 중 하나라도 true인 경우:

    이 경우, 이 script 요소에 대한 스크립트 블록의 타입 문자열을 "text/javascript"로 설정하세요.

    그렇지 않다면, eltype 속성이 있으면, 스크립트 블록의 타입 문자열을 그 속성의 값에 앞뒤의 ASCII 공백을 제거한 값으로 설정하세요.

    그 외의 경우, el에 비어 있지 않은 language 속성이 있으면, 스크립트 블록의 타입 문자열을 "text/"와 ellanguage 속성 값의 연결로 설정하세요.

    language 속성은 절대 적합하지 않으며, type 속성이 있으면 항상 무시됩니다.

  9. 스크립트 블록의 타입 문자열JavaScript MIME 타입 에센스와 일치하는 경우, eltype을 "classic"으로 설정하세요.

  10. 그렇지 않으면, 스크립트 블록의 타입 문자열이 "module" 문자열과 ASCII 대소문자 구분 없이 일치하는 경우, eltype을 "module"로 설정하세요.

  11. 그렇지 않으면, 스크립트 블록의 타입 문자열이 "importmap" 문자열과 ASCII 대소문자 구분 없이 일치하는 경우, eltype을 "importmap"으로 설정하세요.

  12. 그 외의 경우, 반환하세요. (스크립트는 실행되지 않으며, eltype은 null로 남습니다.)

  13. parser document가 null이 아닌 경우, elparser document를 다시 parser document로 설정하고, el강제 비동기를 false로 설정하세요.

  14. el이미 시작됨을 true로 설정하세요.

  15. el준비 시간 문서노드 문서로 설정하세요.

  16. 만약 parser document가 null이 아니고, parser documentel준비 시간 문서와 다르다면, 반환하세요.

  17. 만약 el에 대해 스크립팅이 비활성화된 경우, 반환하세요.

    스크립팅이 비활성화됨의 정의는 다음 스크립트가 실행되지 않음을 의미합니다: XMLHttpRequestresponseXML 문서 내의 스크립트, DOMParser에 의해 생성된 문서 내의 스크립트, XSLTProcessortransformToDocument 기능에 의해 생성된 문서 내의 스크립트, 그리고 스크립트에 의해 Document 내에 처음 삽입된 스크립트.

  18. 만약 elnomodule 콘텐츠 속성이 있고, eltype이 "classic"인 경우, 반환하세요.

    이것은 모듈 스크립트nomodule을 지정하는 것이 아무런 효과가 없음을 의미합니다. 알고리즘은 계속 진행됩니다.

  19. 만약 elsrc 콘텐츠 속성이 없고, Content Security Policy에 의해 요소의 인라인 동작이 차단되어야 하는가? 알고리즘이 el, "script", 및 source text를 제공받았을 때 "Blocked"를 반환하는 경우, 반환하세요. [CSP]

  20. 만약 elevent 속성과 for 속성이 있으며, eltype이 "classic"인 경우:

    1. forelfor 속성 값으로 설정하세요.

    2. eventelevent 속성 값으로 설정하세요.

    3. 앞뒤의 ASCII 공백을 제거하여 eventfor에서 제거하세요.

    4. for가 문자열 "window"와 ASCII 대소문자 구분 없이 일치하지 않는 경우, 반환하세요.

    5. event가 "onload" 또는 "onload()" 문자열과 ASCII 대소문자 구분 없이 일치하지 않는 경우, 반환하세요.

  21. 만약 elcharset 속성이 있는 경우, 인코딩을 얻는 결과를 elcharset 속성 값으로 설정하세요.

    elcharset 속성이 없거나, 인코딩을 얻는 것이 실패한 경우, encodingel노드 문서문서의 인코딩으로 설정하세요.

    만약 eltype이 "module"인 경우, 이 인코딩은 무시됩니다.

  22. classic script CORS settingelcrossorigin 콘텐츠 속성의 현재 상태로 설정하세요.

  23. module script credentials modeelcrossorigin 콘텐츠 속성의 CORS 설정 속성 자격 증명 모드로 설정하세요.

  24. cryptographic nonceel[[CryptographicNonce]] 내부 슬롯의 값으로 설정하세요.

  25. 만약 elintegrity 속성이 있는 경우, integrity metadata를 그 속성의 값으로 설정하세요.

    그렇지 않으면, integrity metadata를 빈 문자열로 설정하세요.

  26. referrer policyelreferrerpolicy 콘텐츠 속성의 현재 상태로 설정하세요.

  27. fetch priorityelfetchpriority 콘텐츠 속성의 현재 상태로 설정하세요.

  28. parser metadatael파서에 의해 삽입된 경우 "parser-inserted"로, 그렇지 않은 경우 "not-parser-inserted"로 설정하세요.

  29. options스크립트 가져오기 옵션으로 설정하고, 암호화 논스cryptographic nonce, 무결성 메타데이터integrity metadata, 파서 메타데이터parser metadata, 자격 증명 모드module script credentials mode, referrer policyreferrer policy, fetch priorityfetch priority로 설정하세요.

  30. settings objectel노드 문서관련 설정 객체로 설정하세요.

  31. 만약 elsrc 콘텐츠 속성이 있는 경우, 다음을 수행하세요:

    1. 만약 eltype이 "importmap"이라면, 요소 작업을 큐에 추가하고, DOM 조작 작업 소스에서 el을 주어진 상태로 하여 이벤트를 발생시키며 errorel에 전달하고, 반환하세요.

      외부 import map 스크립트는 현재 지원되지 않습니다. 지원 추가에 대한 논의는 WICG/import-maps issue #235를 참조하세요.

    2. srcelsrc 속성 값으로 설정하세요.

    3. 만약 src가 빈 문자열인 경우, 요소 작업을 큐에 추가하고, DOM 조작 작업 소스에서 el을 주어진 상태로 하여 이벤트를 발생시키며 errorel에 전달하고, 반환하세요.

    4. el외부 파일로부터 true로 설정하세요.

    5. urlURL 인코딩-파싱의 결과로 설정하세요. srcel노드 문서의 상대 경로로 설정하세요.

    6. 만약 url이 실패한 경우, 요소 작업을 큐에 추가하고, DOM 조작 작업 소스에서 el을 주어진 상태로 하여 이벤트를 발생시키며 errorel에 전달하고, 반환하세요.

    7. el잠재적으로 렌더링을 차단하고 있는 경우, 렌더링 차단el에서 수행하세요.

    8. el로드 이벤트 지연을 true로 설정하세요.

    9. el이 현재 렌더링 차단 중인 경우, options렌더링 차단을 true로 설정하세요.

    10. result를 주어진 onComplete에 다음 단계로 설정하세요:

      1. 준비 완료로 표시 el을 주어진 result로 설정하세요.

    11. eltype을 사용하여 전환하세요:

      "classic"

      클래식 스크립트를 가져오기를 주어진 url, settings object, options, classic script CORS setting, encodingonComplete와 함께 수행하세요.

      "module"

      elintegrity 속성이 없는 경우, options무결성 메타데이터를 주어진 urlsettings object와 함께 사용하여 모듈 무결성 메타데이터를 해결하세요.

      외부 모듈 스크립트 그래프를 가져오기를 주어진 url, settings object, options, 및 onComplete와 함께 수행하세요.

      성능 향상을 위해, 사용자 에이전트는 src 속성이 설정되자마자 (위에서 설명한 대로) el이 연결될 것이라는 희망에서, 클래식 스크립트 또는 모듈 그래프를 가져오기 시작할 수 있습니다 (그리고 이 사이에 crossorigin 속성이 변경되지 않기를 기대합니다). 어쨌든, el연결됨 상태가 되면, 로드는 이 단계에서 설명된 대로 시작되어야 합니다. 만약 UA가 이러한 사전 가져오기를 수행하지만 el이 연결되지 않거나, src 속성이 동적으로 변경되거나, crossorigin 속성이 동적으로 변경된 경우, UA는 그렇게 얻은 스크립트를 실행하지 않으며, 가져오기 과정은 사실상 낭비됩니다.

  32. 만약 elsrc 콘텐츠 속성이 없는 경우:

    1. base URLel노드 문서문서 기본 URL로 설정하세요.

    2. eltype을 사용하여 전환하세요:

      "classic"
      1. 클래식 스크립트 생성의 결과를 source text, settings object, base URL, 및 options을 사용하여 script로 설정하세요.

      2. 준비 완료로 표시 el을 주어진 script로 설정하세요.

      "module"
      1. el로드 이벤트 지연을 true로 설정하세요.

      2. el잠재적으로 렌더링을 차단하는 경우:

        1. 렌더링 차단el에서 수행하세요.

        2. options렌더링 차단을 true로 설정하세요.

      3. 인라인 모듈 스크립트 그래프를 가져오기source text, base URL, settings object, options, 및 주어진 result로 수행하세요:

        1. 요소 작업을 큐에 추가하여 네트워킹 작업 소스에서 el을 주어진 상태로 수행하고, 다음 단계를 수행하세요:

          1. 준비 완료로 표시 el을 주어진 result로 설정하세요.

          이곳에서 작업을 큐에 추가하는 것은, 인라인 모듈 스크립트에 의존성이 없거나 구문 오류가 즉시 발생하더라도, 스크립트 요소를 실행 단계가 동기적으로 진행되지 않음을 의미합니다.

      "importmap"
      1. 만약 el관련 전역 객체import maps 허용됨이 false인 경우, 요소 작업을 큐에 추가하고, DOM 조작 작업 소스에서 el을 주어진 상태로 하여 이벤트를 발생시키며 errorel에 전달하고, 반환하세요.

      2. el관련 전역 객체import maps 허용됨을 false로 설정하세요.

      3. resultsource textbase URL로 주어진 import map 구문 분석 결과 생성의 결과로 설정하세요.

      4. 준비 완료로 표시 el을 주어진 result로 설정하세요.

  33. 만약 eltype이 "classic"이고 elsrc 속성이 있거나, eltype이 "module"인 경우:

    1. 확인: elresult가 "uninitialized"인 상태입니다.

    2. 만약 elasync 속성이 있거나 el강제 비동기가 true인 경우:

      1. scriptsel준비 시간 문서가능한 한 빨리 실행될 스크립트 세트로 설정하세요.

      2. 추가하세요 elscripts로.

      3. el결과가 준비되었을 때 실행할 단계들을 다음으로 설정하세요:

        1. 스크립트 요소를 실행하세요 el을.

        2. 제거하세요 elscripts에서.

    3. 그렇지 않고, el파서에 의해 삽입되지 않은 경우:

      1. scriptsel준비 시간 문서가능한 한 빨리 순서대로 실행될 스크립트 목록으로 설정하세요.

      2. 추가하세요 elscripts로.

      3. el결과가 준비되었을 때 실행할 단계들을 다음으로 설정하세요:

        1. 만약 scripts[0]이 el이 아닌 경우, 이 단계를 중단하세요.

        2. scripts가 비어 있지 않고, scripts[0]의 result가 "uninitialized"이 아닌 동안:

          1. 스크립트 요소를 실행하세요 scripts[0].

          2. 제거하세요 scripts[0]을.

    4. 그렇지 않고, eldefer 속성이 있거나 eltype이 "module"인 경우:

      1. 추가하세요 elelparser document문서가 파싱을 완료하면 실행될 스크립트 목록에.

      2. el결과가 준비되었을 때 실행할 단계들을 다음으로 설정하세요: el파서가 실행할 준비 완료를 true로 설정하세요. (파서는 스크립트를 실행하는 작업을 처리합니다.)

    5. 그 외의 경우:

      1. elparser document파싱 차단 스크립트 대기 중el로 설정하세요.

      2. 렌더링 차단el에서 수행하세요.

      3. el결과가 준비되었을 때 실행할 단계들을 다음으로 설정하세요: el파서가 실행할 준비 완료를 true로 설정하세요. (파서는 스크립트를 실행하는 작업을 처리합니다.)

  34. 그 외의 경우:

    1. 확인: elresult가 "uninitialized"가 아님을.

    2. 다음 모두가 true인 경우:

      다음 작업을 수행하세요:

      1. elparser document파싱 차단 스크립트 대기 중el로 설정하세요.

      2. el파서가 실행할 준비 완료를 true로 설정하세요. (파서는 스크립트를 실행하는 작업을 처리합니다.)

    3. 그 외의 경우, 즉시 스크립트 요소를 실행하세요 el을, 다른 스크립트들이 이미 실행 중이더라도.

Document에는 파싱 차단 스크립트가 있으며, 이는 script 요소이거나 null이며, 초기값은 null입니다.

Document에는 가능한 빨리 실행될 스크립트 집합이 있으며, 이는 집합으로, script 요소들로 구성되며, 초기값은 비어 있습니다.

Document에는 가능한 빨리 순서대로 실행될 스크립트 목록이 있으며, 이는 목록으로, script 요소들로 구성되며, 초기값은 비어 있습니다.

Document에는 문서 파싱이 완료되면 실행될 스크립트 목록이 있으며, 이는 목록으로, script 요소들로 구성되며, 초기값은 비어 있습니다.

파서를 차단하는 script 요소가 다른 Document로 이동되기 전에 해당 파서를 차단하는 경우, 해당 요소는 더 이상 파서를 차단하는 조건이 적용되지 않을 때까지 해당 파서를 차단합니다. (예: 원래 Document스크립트를 차단하는 스타일 시트가 있는 경우, 스크립트가 차단하는 스타일 시트가 모두 로드될 때까지 스크립트는 계속 파서를 차단합니다.)

스크립트 요소를 실행하려면 script 요소 el을 수행합니다:

  1. documentel노드 문서로 설정합니다.

  2. el준비 시간 문서document와 같지 않으면 반환합니다.

  3. el에서 렌더링을 해제합니다.

  4. 만약 el결과가 null이면, el에서 이벤트를 발생시킵니다 그 이름은 error이며, 반환합니다.

  5. el외부 파일에서 왔거나, el유형이 "module"이면, document파괴적 쓰기를 무시하는 카운터를 증가시킵니다.

  6. el유형에 따라 다음을 수행합니다:

    "classic"
    1. documentcurrentScript 객체에 가장 최근에 설정된 값을 oldCurrentScript로 설정합니다.

    2. el루트섀도우 루트가 아니라면, documentcurrentScript 속성을 el로 설정합니다. 그렇지 않으면, null로 설정합니다.

      이는 문서 트리 내에서 체크되지 않으며, el이 실행 전에 문서에서 제거되었을 수 있으므로, 이 경우에도 currentScript 여전히 그것을 가리킬 필요가 있습니다.

    3. 클래식 스크립트를 실행합니다. el결과를 사용합니다.

    4. documentcurrentScript 속성을 oldCurrentScript로 설정합니다.

    "module"
    1. 확인: documentcurrentScript 속성이 null입니다.

    2. 모듈 스크립트를 실행합니다. el결과를 사용합니다.

    "importmap"
    1. 임포트 맵을 등록합니다. el관련 전역 객체el결과를 사용합니다.

  7. 이전 단계에서 증가한 경우 document파괴적 쓰기를 무시하는 카운터를 감소시킵니다.

  8. el외부 파일에서 왔다면, el에서 이벤트를 발생시킵니다 그 이름은 load입니다.

4.12.1.2 스크립팅 언어

사용자 에이전트는 JavaScript를 지원할 필요가 없습니다. JavaScript 이외의 언어가 등장하여 웹 브라우저에서 유사한 광범위한 채택을 받게 되면 이 표준을 업데이트해야 합니다. 그러한 시점까지는 script 요소에 대해 정의된 처리 모델을 고려할 때, 다른 언어를 구현하는 것은 이 표준과 충돌하게 됩니다.

서버는 JavaScript 리소스에 대해 Updates to ECMAScript Media Types에 따라 text/javascript를 사용해야 합니다. 서버는 JavaScript 리소스에 대해 다른 JavaScript MIME 유형을 사용해서는 안 되며, 비-JavaScript MIME 유형을 사용해서는 안 됩니다. [RFC9239]

외부 JavaScript 리소스의 경우, `Content-Type` 헤더의 MIME 유형 매개변수는 일반적으로 무시됩니다. (일부 경우 `charset` 매개변수가 영향을 미칠 수 있습니다.) 그러나 script 요소의 type 속성에 대해서는 중요하며, 이는 JavaScript MIME 유형 본질 매치 개념을 사용합니다.

예를 들어, type 속성이 "text/javascript; charset=utf-8"로 설정된 스크립트는 구문 분석 시 유효한 JavaScript MIME 유형임에도 불구하고 평가되지 않습니다.

또한, 외부 JavaScript 리소스의 경우, `Content-Type` 헤더 처리에 대해 스크립트 요소 준비 알고리즘과 Fetch에 설명된 특별한 고려사항이 적용됩니다. [FETCH]

4.12.1.3 script 요소의 내용에 대한 제한

이 섹션에서 설명된 다소 이상한 제한을 피하는 가장 쉽고 안전한 방법은 스크립트 내 리터럴(예: 문자열, 정규 표현식 또는 주석)에 "<!--", "<script", "</script"와 같은 ASCII 대소문자 무시 일치 항목이 나타날 때 이를 "\x3C!--", "\x3Cscript", "\x3C/script"로 항상 이스케이프 처리하는 것이며, 이러한 구문을 표현식에서 사용하는 코드를 작성하지 않는 것입니다. 이렇게 하면 이 섹션에서 언급된 제한에 의해 발생할 수 있는 함정을 완전히 피할 수 있습니다. 즉, 역사적 이유로 HTML에서 script 블록을 파싱하는 것이 다소 이상하고 직관적이지 않게 동작할 수 있습니다.

script 요소의 하위 텍스트 내용은 다음 ABNF에서 정의된 script 생산 규칙과 일치해야 하며, 이 규칙의 문자 집합은 유니코드입니다. [ABNF]

script        = outer *( comment-open inner comment-close outer )

outer         = < any string that doesn't contain a substring that matches not-in-outer >
not-in-outer  = comment-open
inner         = < any string that doesn't contain a substring that matches not-in-inner >
not-in-inner  = comment-close / script-open

comment-open  = "<!--"
comment-close = "-->"
script-open   = "<" s c r i p t tag-end

s             =  %x0053 ; U+0053 라틴 대문자 S
s             =/ %x0073 ; U+0073 라틴 소문자 s
c             =  %x0043 ; U+0043 라틴 대문자 C
c             =/ %x0063 ; U+0063 라틴 소문자 c
r             =  %x0052 ; U+0052 라틴 대문자 R
r             =/ %x0072 ; U+0072 라틴 소문자 r
i             =  %x0049 ; U+0049 라틴 대문자 I
i             =/ %x0069 ; U+0069 라틴 소문자 i
p             =  %x0050 ; U+0050 라틴 대문자 P
p             =/ %x0070 ; U+0070 라틴 소문자 p
t             =  %x0054 ; U+0054 라틴 대문자 T
t             =/ %x0074 ; U+0074 라틴 소문자 t

tag-end       =  %x0009 ; U+0009 문자 탭(tab)
tag-end       =/ %x000A ; U+000A 줄 바꿈(LF)
tag-end       =/ %x000C ; U+000C 양식 피드(FF)
tag-end       =/ %x0020 ; U+0020 스페이스
tag-end       =/ %x002F ; U+002F 슬래시(/)
tag-end       =/ %x003E ; U+003E 큰따옴표(>)

script 요소가 스크립트 설명을 포함하는 경우, 아래 섹션에서 설명된 대로 요소 내용에 대한 추가 제한이 있습니다.

다음 스크립트는 이 문제를 설명합니다. 예를 들어 다음과 같이 문자열을 포함하는 스크립트를 가정해 보겠습니다:

const example = '이 문자열을 고려하십시오: <!-- <script>';
console.log(example);

이 문자열을 script 블록에 직접 넣으면 위의 제한 사항을 위반하게 됩니다:

<script>
  const example = '이 문자열을 고려하십시오: <!-- <script>';
  console.log(example);
</script>

더 큰 문제는 실제로 스크립트가 이상하게 파싱된다는 것입니다: 위의 스크립트 블록은 종료되지 않습니다. 즉, 이 코드 조각의 "</script>" 종료 태그처럼 보이는 부분은 실제로 여전히 script 블록의 일부입니다. 스크립트는 종료되지 않았기 때문에 실행되지 않으며, 마크업이 다음과 같이 생긴 경우처럼 어떻게든 실행되더라도 이 스크립트(여기 강조 표시된)는 유효한 JavaScript가 아니므로 실패할 것입니다:

<script>
  const example = '이 문자열을 고려하십시오: <!-- <script>';
  console.log(example);
</script>
<!-- 보기에 반하여, 이것은 여전히 스크립트의 일부입니다! -->
<script> 
 ... // 여전히 동일한 스크립트 블록입니다...
</script>

여기에서 무슨 일이 일어나고 있냐면, 역사적 이유로 script 요소의 "<!--" 및 "<script" 문자열은 HTML에서 균형이 맞춰져야 파서가 블록을 닫는 것으로 간주합니다.

이 섹션의 맨 위에서 언급된 대로 문제의 문자열을 이스케이프 처리하면 이 문제를 완전히 피할 수 있습니다:

<script>
  // 참고: `\x3C`는 `<`에 대한 이스케이프 시퀀스입니다.
  const example = '이 문자열을 고려하십시오: \x3C!-- \x3Cscript>';
  console.log(example);
</script> 
<!-- 이것은 단순히 스크립트 블록 사이의 주석입니다 -->
<script>
 ... // 이것은 새로운 스크립트 블록입니다
</script>

이러한 시퀀스는 다음 예제와 같이 스크립트 표현식에서 자연스럽게 발생할 수 있습니다:

if (x<!--y) { ... } 
if ( player<script ) { ... }

이러한 경우 문자들을 이스케이프 처리할 수는 없지만, 시퀀스가 발생하지 않도록 표현식을 다시 작성할 수 있습니다:

if (x < !--y) { ... } 
if (!--y > x) { ... } 
if (!(--y) > x) { ... } 
if (player < script) { ... } 
if (script > player) { ... }

이렇게 하면 또 다른 문제를 피할 수 있습니다: 관련된 역사적 이유로 클래식 스크립트에서 "<!--" 문자열이 실제로는 줄 주석 시작으로 처리됩니다, 마치 "//"처럼.

4.12.1.4 외부 스크립트에 대한 인라인 문서

script 요소의 src 속성이 지정된 경우, script 요소의 내용이 있는 경우, 해당 요소의 내용에서 파생된 text IDL 속성의 값이 다음 ABNF에서 정의된 documentation 생성 규칙과 일치해야 하며, 이 규칙의 문자 집합은 유니코드입니다. [ABNF]

documentation = *( *( space / tab / comment ) [ line-comment ] newline )
comment       = slash star *( not-star / star not-slash ) 1*star slash
line-comment  = slash slash *not-newline

; characters
tab           = %x0009 ; U+0009 문자 탭(tab)
newline       = %x000A ; U+000A 줄 바꿈(LF)
space         = %x0020 ; U+0020 스페이스
star          = %x002A ; U+002A 별표(*)
slash         = %x002F ; U+002F 슬래시(/)
not-newline   = %x0000-0009 / %x000B-10FFFF
                ; a 스칼라 값 other than U+000A LINE FEED (LF)
not-star      = %x0000-0029 / %x002B-10FFFF
                ; a 스칼라 값 other than U+002A ASTERISK (*)
not-slash     = %x0000-002E / %x0030-10FFFF
                ; a 스칼라 값 other than U+002F SOLIDUS (/)

이 내용은 요소의 내용을 JavaScript 주석에 넣는 것과 같습니다.

이 요구 사항은 script 요소 내용의 구문에 대한 앞서 언급된 제한 사항에 추가로 적용됩니다.

이 기능을 통해 작성자는 외부 스크립트 파일을 참조하면서도 라이선스 정보 또는 API 정보와 같은 문서를 문서 내에 포함할 수 있습니다. 구문이 제한되어 있으므로 작성자가 유효한 스크립트처럼 보이는 것을 포함하면서도 src 속성을 제공하지 않도록 방지합니다.

<script src="cool-effects.js">
 // 인스턴스를 생성하려면:
 //    var e = new Effect();
 // .play로 효과를 시작하고, .stop으로 중지합니다:
 //    e.play();
 //    e.stop();
</script>
4.12.1.5 script 요소와 XSLT의 상호작용

이 섹션은 비규범적입니다.

이 명세는 script 요소와 XSLT의 상호작용을 정의하지 않습니다. 그러나 실제로 이를 정의하는 다른 명세가 없는 경우, 기존 구현을 기반으로 한 구현자들을 위한 몇 가지 지침을 제공합니다:

첫 번째 두 경우와 마지막 경우의 주요 차이점은 첫 번째 두 경우는 Document에서 작업하고 마지막 경우는 조각에서 작업한다는 것입니다.

4.12.2 noscript 요소

Element/noscript

현재 모든 엔진에서 지원됨.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
메타데이터 콘텐츠.
플로우 콘텐츠.
프레이징 콘텐츠.
이 요소가 사용될 수 있는 문맥:
head 요소 안에, 상위 noscript 요소가 없을 때.
프레이징 콘텐츠가 예상되는 HTML 문서에서, 상위 noscript 요소가 없을 때.
콘텐츠 모델:
스크립팅이 비활성화된 경우, head 요소 내에서: 0개 이상의 link 요소, 0개 이상의 style 요소, 0개 이상의 meta 요소를 임의의 순서로 포함할 수 있습니다.
스크립팅이 비활성화된 경우, head 요소 외부에서: 투명한 콘텐츠 모델을 따르지만, noscript 요소의 하위 요소가 없어야 합니다.
그 외의 경우: 서술된 요구 사항에 맞는 텍스트.
text/html에서의 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
HTMLElement을 사용합니다.

noscript 요소는 스크립팅이 활성화된 경우 아무것도 나타내지 않으며, 스크립팅이 비활성화된 경우 자식 요소를 나타냅니다. 이 요소는 스크립팅을 지원하는 사용자 에이전트와 지원하지 않는 사용자 에이전트에 대해 서로 다른 마크업을 표시하는 데 사용됩니다.

HTML 문서에서 사용될 때, 허용되는 콘텐츠 모델은 다음과 같습니다:

head 요소에서, 스크립트가 비활성화noscript 요소의 경우

noscript 요소는 link, stylemeta 요소만 포함해야 합니다.

head 요소에서, 스크립트가 활성화noscript 요소의 경우

noscript 요소는 텍스트만 포함해야 하며, noscript 요소를 context 요소로 하고 그 텍스트 내용을 input으로 하여 HTML 조각 파싱 알고리즘을 실행한 결과가 link, style, meta 요소로만 구성된 노드 목록이 되며, 이 목록이 noscript 요소의 자식 요소로서 적합한지 확인되어야 하며, 파싱 오류가 발생하지 않아야 합니다.

head 요소 외부에서, 스크립트가 비활성화noscript 요소의 경우

noscript 요소의 내용 모델은 투명이며, 추가로 noscript 요소는 조상 요소로 noscript 요소를 가질 수 없습니다 (즉, noscript 요소는 중첩될 수 없습니다).

head 요소 외부에서, 스크립트가 활성화noscript 요소의 경우

noscript 요소는 텍스트만 포함해야 하며, 그 텍스트는 아래 알고리즘을 실행하여 noscript 요소와 script 요소가 없는 적합한 문서가 되고, 알고리즘의 어느 단계에서도 예외가 발생하지 않으며 HTML 파서파싱 오류를 표시하지 않도록 하는 텍스트여야 합니다:

  1. 문서에서 모든 script 요소를 제거합니다.
  2. 문서에서 모든 noscript 요소의 목록을 만듭니다. 이 목록에 있는 모든 noscript 요소에 대해 다음 단계를 수행합니다:
    1. snoscript 요소의 자식 텍스트 내용으로 설정합니다.
    2. outerHTML 속성을 s의 값으로 설정합니다. (이로 인해 noscript 요소가 문서에서 제거됩니다.)

이 모든 복잡한 작업은 역사적인 이유로 인해 noscript 요소가 HTML 구문 분석기에 의해 스크립팅이 활성화되었는지 여부에 따라 다르게 처리되기 때문에 필요합니다.

noscript 요소는 XML 문서에서 사용되어서는 안 됩니다.

noscript 요소는 HTML 문법에서만 효과가 있으며, XML 문법에서는 효과가 없습니다. 이는 스크립트가 활성화되었을 때 파서가 꺼져 요소의 내용을 순수 텍스트로 처리하고 실제 요소로 처리하지 않기 때문입니다. XML은 이를 수행할 수 있는 메커니즘을 정의하지 않습니다.

noscript 요소는 다른 요구 사항이 없습니다. 특히 noscript 요소의 자식 요소는 스크립팅이 활성화된 경우에도 양식 제출, 스크립팅 등에 대한 예외가 적용되지 않습니다.

다음 예제에서는 noscript 요소를 사용하여 스크립트의 대체 수단을 제공합니다.

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p><script> 
 var x = document.getElementById('x'); 
 var output = document.createElement('p'); 
 output.textContent = 'Type a number; it will be squared right then!'; 
 x.form.appendChild(output); 
 x.form.onsubmit = function () { return false; } 
 x.oninput = function () { 
 var v = x.valueAsNumber; 
 output.textContent = v + ' squared is ' + v * v; 
 }; 
 </script><noscript> 
 <input type=submit value="Calculate Square"> 
 </noscript></form>

스크립트가 비활성화된 경우, 계산을 서버 측에서 수행하는 버튼이 나타납니다. 스크립트가 활성화된 경우, 값은 실시간으로 계산됩니다.

noscript 요소는 다소 강제적인 방법입니다. 때로는 스크립트가 활성화되어 있지만 페이지의 스크립트가 실패할 수 있습니다. 이러한 이유로 noscript 요소를 사용하는 것보다, 스크립트가 페이지를 스크립트 없는 상태에서 스크립트가 있는 상태로 동적으로 변경하도록 설계하는 것이 더 좋습니다. 다음 예제와 같이:

<form action="calcSquare.php">
 <p> 
 <label for=x>Number</label>: 
 <input id="x" name="x" type="number"> 
 </p> <input id="submit" type=submit value="Calculate Square">
 <script> 
 var x = document.getElementById('x'); 
 var output = document.createElement('p'); 
 output.textContent = 'Type a number; it will be squared right then!'; 
 x.form.appendChild(output); 
 x.form.onsubmit = function () { return false; } 
 x.oninput = function () { 
 var v = x.valueAsNumber; 
 output.textContent = v + ' squared is ' + v * v; 
 };  var submit = document.getElementById('submit'); 
 submit.parentNode.removeChild(submit);
 </script></form>

위 기술은 XML 문서에서도 유용합니다. noscript 요소는 여기에서 허용되지 않기 때문입니다.

4.12.3 template 요소

Element/template

현재 모든 엔진에서 지원됨.

Firefox22+Safari8+Chrome26+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView AndroidSamsung Internet?Opera Android?

HTMLTemplateElement

현재 모든 엔진에서 지원됨.

Firefox22+Safari8+Chrome26+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
메타데이터 콘텐츠.
플로우 콘텐츠.
프레이징 콘텐츠.
스크립트 지원 요소.
이 요소가 사용될 수 있는 문맥:
메타데이터 콘텐츠가 예상되는 곳.
프레이징 콘텐츠가 예상되는 곳.
스크립트 지원 요소가 예상되는 곳.
colgroup 요소의 하위 요소로, span 속성이 없는 경우.
콘텐츠 모델:
없음 (자세한 내용은 예제 참조).
text/html에서의 태그 생략:
어떤 태그도 생략할 수 없습니다.
콘텐츠 속성:
글로벌 속성
shadowrootmode — 선언적 shadow root 스트리밍을 활성화합니다.
shadowrootdelegatesfocus — 선언적 shadow root에 포커스 위임을 설정합니다.
shadowrootclonable — 선언적 shadow root에 복제 가능을 설정합니다.
shadowrootserializable — 선언적 shadow root에 직렬화 가능을 설정합니다.
접근성 고려 사항:
저자용.
구현자용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLTemplateElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute DocumentFragment content;
  [CEReactions] attribute DOMString shadowRootMode;
  [CEReactions] attribute boolean shadowRootDelegatesFocus;
  [CEReactions] attribute boolean shadowRootClonable;
  [CEReactions] attribute boolean shadowRootSerializable;
};

template 요소는 스크립트를 통해 문서에 복제하여 삽입할 수 있는 HTML 조각을 선언하는 데 사용됩니다.

렌더링 시 template 요소는 아무것도 나타내지 않습니다.

shadowrootmode 콘텐츠 속성은 다음 키워드와 상태를 가진 열거된 속성입니다:

키워드 상태 간단한 설명
open open template 요소는 열린 선언적 shadow root를 나타냅니다.
closed closed template 요소는 닫힌 선언적 shadow root를 나타냅니다.

shadowrootmode 속성의 유효하지 않은 값 기본값누락된 값 기본값은 모두 none 상태입니다.

shadowrootdelegatesfocus 콘텐츠 속성은 부울 속성입니다.

shadowrootclonable 콘텐츠 속성은 부울 속성입니다.

shadowrootserializable 콘텐츠 속성은 부울 속성입니다.

template 요소의 template 콘텐츠요소 자체의 자식이 아닙니다.

DOM 조작의 결과로 template 요소에 텍스트 노드 및 요소 노드가 포함될 수 있지만, 이는 template 요소의 콘텐츠 모델이 없음으로 정의되어 있기 때문에 콘텐츠 모델 위반입니다.

예를 들어, 다음 문서를 고려해 보십시오:

<!doctype html>
<html lang="en">
 <head>
  <title>Homework</title>
 <body>
  <template id="template"><p>Smile!</p></template>
  <script>
   let num = 3; 
   const fragment = document.getElementById('template').content.cloneNode(true); 
   while (num-- > 1) { 
     fragment.firstChild.before(fragment.firstChild.cloneNode(true)); 
     fragment.firstChild.textContent += fragment.lastChild.textContent; 
   } 
   document.body.appendChild(fragment); 
  </script>
</html>

p 요소는 template의 자식이 아니며, DOM의 DocumentFragment의 자식입니다.

스크립트가 appendChild()를 호출하면 template 요소에 자식이 추가됩니다. 그러나 이는 template 요소의 콘텐츠 모델 위반입니다.

template.content

HTMLTemplateElement/content

현재 모든 엔진에서 지원됨.

Firefox22+Safari8+Chrome26+
Opera?Edge79+
Edge (Legacy)13+Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

template 콘텐츠를 반환합니다 (DocumentFragment).

template 요소는 DocumentFragment 객체와 연결된 template 콘텐츠를 가집니다. template 콘텐츠적합성 요구 사항이 없습니다. template 요소가 생성될 때, 사용자 에이전트는 template 콘텐츠를 설정하기 위해 다음 단계를 실행해야 합니다:

  1. doctemplate 요소의 노드 문서적합한 템플릿 콘텐츠 소유 문서로 설정합니다.

  2. docDocumentFragment 객체로 설정합니다. 이 객체의 노드 문서doc이고 호스트template 요소입니다.

  3. 새로 생성된 DocumentFragment 객체를 template 콘텐츠로 설정합니다.

document doc적합한 템플릿 콘텐츠 소유 문서는 다음 알고리즘에 의해 반환된 document입니다:

  1. doc이 이 알고리즘에 의해 생성되지 않은 document라면:

    1. doc연결된 비활성 템플릿 문서가 아직 없다면:

      1. new docdocument로 설정합니다. (이 문서의 브라우징 컨텍스트는 null입니다). 이는 위 단계에서 사용되는 "이 알고리즘에 의해 생성된 document"입니다.

      2. docHTML 문서인 경우, new docHTML 문서로도 표시합니다.

      3. doc연결된 비활성 템플릿 문서new doc으로 설정합니다.

    2. docdoc연결된 비활성 템플릿 문서로 설정합니다.

    이 알고리즘에 의해 생성되지 않은 각 documenttemplate 콘텐츠를 소유하는 프록시로 작동할 단일 document를 얻습니다. 따라서 브라우징 컨텍스트에 없으므로 비활성 상태를 유지합니다 (예: 스크립트가 실행되지 않음). 한편, 이 알고리즘에 의해 생성된 document 객체 내부의 template 요소는 콘텐츠에 대해 동일한 소유자를 재사용합니다.

  2. doc을 반환합니다.

template 요소의 채택 단계(node이전 문서를 매개변수로 사용)에서 실행해야 하는 단계는 다음과 같습니다:

  1. docnode노드 문서적합한 템플릿 콘텐츠 소유 문서로 설정합니다.

    node노드 문서node가 방금 채택된 document 객체입니다.

  2. nodetemplate 콘텐츠(DocumentFragment 객체)를 doc에 채택합니다.

content getter 단계는 template 콘텐츠ShadowRoot 노드가 아닌 경우 templatetemplate 콘텐츠를 반환하는 것입니다. 그렇지 않으면 null을 반환합니다.

shadowRootMode IDL 속성은 shadowrootmode 콘텐츠 속성을 알려진 값으로만 제한하여 반영해야 합니다.

shadowRootDelegatesFocus IDL 속성은 shadowrootdelegatesfocus 콘텐츠 속성을 반영해야 합니다.

shadowRootClonable IDL 속성은 shadowrootclonable 콘텐츠 속성을 반영해야 합니다.

shadowRootSerializable IDL 속성은 shadowrootserializable 콘텐츠 속성을 반영해야 합니다.


template 요소 node의 복사본 copy를 복제할 때 실행되는 복제 단계는 다음과 같습니다:

  1. 호출 중인 복제 알고리즘에서 자식 복제 플래그가 설정되지 않은 경우, 반환합니다.

  2. 복사된 콘텐츠nodetemplate 콘텐츠의 모든 자식을 복제한 결과입니다. 이때 document복사본template 콘텐츠노드 문서로 설정되며, 자식 복제 플래그가 설정됩니다.

  3. 복사된 콘텐츠복사본template 콘텐츠에 추가합니다.

이 예제에서는 스크립트를 사용하여 데이터 구조에서 데이터를 가져와 <template> 요소를 사용하여 테이블의 4열을 채웁니다. 이 방법은 구조를 수동으로 생성하는 대신에 마크업에서 구조를 제공합니다.

<!DOCTYPE html>
<html lang='en'>
<title>Cat data</title>
<script>
 // Data is hard-coded here, but could come from the server
 var data = [
   { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 },
   { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 },
 ];
</script>
<table>
 <thead>
  <tr>
   <th>Name <th>Color <th>Sex <th>Legs
 </thead>
  <tbody>
  <template id="row">
   <tr><td><td><td><td>
  </template>
</table>
<script>
 var template = document.querySelector('#row'); 
 for (var i = 0; i < data.length; i += 1) { 
   var cat = data[i]; 
   var clone = template.content.cloneNode(true); 
   var cells = clone.querySelectorAll('td'); 
   cells[0].textContent = cat.name; 
   cells[1].textContent = cat.color; 
   cells[2].textContent = cat.sex; 
   cells[3].textContent = cat.legs; 
   template.parentNode.appendChild(clone); 
 } 
</script>

이 예제에서는 cloneNode()를 사용하여 template의 콘텐츠를 복제합니다. 이와 동등하게 document.importNode()를 사용할 수 있습니다. 이 두 API의 유일한 차이점은 노드 문서가 업데이트되는 시점입니다: cloneNode()를 사용하면 노드가 appendChild()로 추가될 때 업데이트됩니다. document.importNode()를 사용하면 노드가 복제될 때 업데이트됩니다.

4.12.3.1 template 요소와 XSLT 및 XPath의 상호 작용

이 섹션은 비규범적입니다.

이 명세서는 XSLT 및 XPath가 template 요소와 어떻게 상호작용하는지 정의하지 않습니다. 그러나 이를 실제로 정의하는 다른 명세가 없는 경우, 구현자를 위한 몇 가지 지침이 있으며, 이는 이 명세서에 설명된 다른 처리 방식과 일관되도록 의도되었습니다:

4.12.4 slot 요소

Element/slot

모든 현재 엔진에서 지원됨.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLSlotElement

모든 현재 엔진에서 지원됨.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
이 요소를 사용할 수 있는 컨텍스트:
구문 콘텐츠가 예상되는 곳.
콘텐츠 모델:
투명
text/html에서 태그 생략:
태그는 생략할 수 없음.
콘텐츠 속성:
글로벌 속성
name — 쉐도우 트리 슬롯의 이름
접근성 고려 사항:
작성자를 위한 내용.
구현자를 위한 내용.
DOM 인터페이스:
[Exposed=Window]
interface HTMLSlotElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  sequence<Node> assignedNodes(optional AssignedNodesOptions options = {});
  sequence<Element> assignedElements(optional AssignedNodesOptions options = {});
  undefined assign((Element or Text)... nodes);
};

dictionary AssignedNodesOptions {
  boolean flatten = false;
};

slot 요소는 슬롯을 정의합니다. 주로 쉐도우 트리에서 사용됩니다. slot 요소는 할당된 노드가 있다면 해당 노드를 나타내고, 그렇지 않으면 콘텐츠를 나타냅니다.

name 콘텐츠 속성은 문자열 값을 포함할 수 있습니다. 이는 슬롯이름을 나타냅니다.

name 속성은 다른 요소에 슬롯을 할당하는 데 사용됩니다. slot 요소에 name 속성이 있으면 이름이 지정된 슬롯이 생성되며, 해당 요소가 slot 속성을 가지고 그 값이 name 속성의 값과 일치하는 경우, 해당 요소는 쉐도우 트리의 자식이 되고, 그 루트호스트는 해당 slot 속성값을 가집니다.

slot.name

HTMLSlotElement/name

모든 현재 엔진에서 지원됨.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
slot이름을 가져오거나 설정할 수 있습니다.
slot.assignedNodes()

HTMLSlotElement/assignedNodes

모든 현재 엔진에서 지원됨.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
slot할당된 노드를 반환합니다.
slot.assignedNodes({ flatten: true })
slot할당된 노드를 반환하고, 없다면 slot의 자식을 반환합니다. 또한, 재귀적으로 만나는 모든 slot 요소에 대해서도 동일하게 수행하며, 더 이상 slot 요소가 남아 있지 않을 때까지 계속됩니다.
slot.assignedElements()

HTMLSlotElement/assignedElements

모든 현재 엔진에서 지원됨.

Firefox66+Safari12.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
slot할당된 노드를 반환하며, 요소로만 제한합니다.
slot.assignedElements({ flatten: true })
assignedNodes({ flatten: true })와 동일하며, 요소로만 제한합니다.
slot.assign(...nodes)

slot수동 할당된 노드를 주어진 nodes로 설정합니다.

name IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

slot 요소에는 수동으로 할당된 노드가 있으며, 이는 assign()으로 설정된 정렬된 세트로, 이 세트는 처음에 비어 있습니다.

수동으로 할당된 노드 세트는 슬롯 가능 항목에 대한 약한 참조를 사용하여 구현할 수 있습니다. 이 세트는 스크립트에서 직접 접근할 수 없기 때문입니다.

assignedNodes(options) 메서드 단계는 다음과 같습니다:

  1. 만약 options["flatten"] 값이 false이면, this할당된 노드를 반환합니다.

  2. this를 사용하여 평평해진 슬롯 가능 항목 찾기의 결과를 반환합니다.

assignedElements(options) 메서드 단계는 다음과 같습니다:

  1. 만약 options["flatten"] 값이 false이면, this할당된 노드를 반환하되, 요소 노드로만 제한합니다.

  2. this를 사용하여 평평해진 슬롯 가능 항목 찾기의 결과를 반환하되, 요소 노드로만 제한합니다.

HTMLSlotElement/assign

모든 현재 엔진에서 지원됨.

Firefox92+Safari16.4+Chrome86+
Opera?Edge86+
Edge (Legacy)?지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

assign(...nodes) 메서드 단계는 다음과 같습니다:

  1. node에 대해 this수동 할당된 노드node수동 슬롯 할당을 null로 설정합니다.

  2. nodesSet을 새로운 정렬된 세트로 설정합니다.

  3. nodenodes에 대해:

    1. 만약 node수동 슬롯 할당슬롯을 참조하고 있다면, node를 해당 슬롯수동으로 할당된 노드에서 제거합니다.

    2. node수동 슬롯 할당this로 설정합니다.

    3. Append nodenodesSet에 추가합니다.

  4. this수동 할당된 노드nodesSet으로 설정합니다.

  5. 트리용 슬롯 가능 항목 할당this루트에 대해 실행합니다.

4.12.5 canvas 요소

Element/canvas

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

HTMLCanvasElement

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
카테고리:
플로우 콘텐츠.
구문 콘텐츠.
내장 콘텐츠.
유의미한 콘텐츠.
사용할 수 있는 문맥:
내장 콘텐츠가 예상되는 곳.
콘텐츠 모델:
투명, 그러나 인터랙티브 콘텐츠 자손은 없음, 단 a 요소, img 요소와 usemap 속성, button 요소, input 요소 중 type 속성이 체크박스 또는 라디오 버튼 상태인 경우와 input 요소의 버튼, 및 select 요소의 다중 선택 속성 또는 표시 크기가 1보다 큰 경우는 예외입니다.
태그 생략 규칙:
두 태그 모두 생략 불가.
콘텐츠 속성:
전역 속성
width — 수평 크기
height — 수직 크기
접근성 고려사항:
저자용.
구현자용.
DOM 인터페이스:
typedef (CanvasRenderingContext2D or ImageBitmapRenderingContext or WebGLRenderingContext or WebGL2RenderingContext or GPUCanvasContext) RenderingContext;

[Exposed=Window]
interface HTMLCanvasElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long width;
  [CEReactions] attribute unsigned long height;

  RenderingContext? getContext(DOMString contextId, optional any options = null);

  USVString toDataURL(optional DOMString type = "image/png", optional any quality);
  undefined toBlob(BlobCallback _callback, optional DOMString type = "image/png", optional any quality);
  OffscreenCanvas transferControlToOffscreen();
};

callback BlobCallback = undefined (Blob? blob);

canvas 요소는 스크립트에 해상도 종속 비트맵 캔버스를 제공하며, 이를 사용하여 그래프, 게임 그래픽, 예술 또는 기타 시각적 이미지를 즉석에서 렌더링할 수 있습니다.

작성자는 보다 적합한 요소가 있을 때 canvas 요소를 문서에서 사용하지 않아야 합니다. 예를 들어, 페이지 제목을 렌더링하는 데 canvas 요소를 사용하는 것은 부적절합니다: 원하는 제목의 표현이 그래픽적으로 강렬한 경우, 적절한 요소로 마크업하고(일반적으로 h1) 그런 다음 CSS와 shadow trees와 같은 지원 기술을 사용하여 스타일을 지정해야 합니다.

작성자가 canvas 요소를 사용할 때, canvas 비트맵과 본질적으로 동일한 기능이나 목적을 사용자에게 전달하는 콘텐츠도 제공해야 합니다. 이 콘텐츠는 canvas 요소의 내용으로 배치될 수 있습니다. canvas 요소의 내용(있는 경우)은 요소의 대체 콘텐츠입니다.


인터랙티브한 시각 매체에서 canvas 요소에 대해 스크립팅이 활성화되어 있고, canvas 요소 지원이 활성화된 경우, canvas 요소는 요소의 비트맵인 동적으로 생성된 이미지로 구성된 내장 콘텐츠나타냅니다.

비인터랙티브, 정적 시각 매체에서 canvas 요소가 이전에 렌더링 컨텍스트와 연관된 경우(예: 페이지가 인터랙티브한 시각 매체에서 열리고 현재 인쇄 중이거나 페이지 레이아웃 과정에서 실행된 스크립트가 요소에 그림을 그린 경우), canvas 요소는 요소의 현재 비트맵과 크기를 가진 내장 콘텐츠나타냅니다. 그렇지 않으면, 요소는 대신 대체 콘텐츠를 나타냅니다.

비시각 매체에서는 물론, canvas 요소에 대해 스크립팅이 비활성화되었거나 canvas 요소 지원이 비활성화된 경우에는, canvas 요소는 대신 대체 콘텐츠나타냅니다.

canvas 요소가 내장 콘텐츠나타낼 때, 사용자는 여전히 canvas 요소의 자손(대체 콘텐츠 내)을 포커스할 수 있습니다. 요소가 포커스된 경우, 해당 요소는 키보드 상호작용 이벤트의 대상이 됩니다(비록 요소 자체가 보이지 않더라도). 이를 통해 작성자는 인터랙티브한 캔버스를 키보드로 접근 가능하게 만들 수 있습니다: 작성자는 인터랙티브한 영역과 대체 콘텐츠포커스 가능한 영역 간에 일대일 매핑을 만들어야 합니다. (포커스는 마우스 상호작용 이벤트에는 영향을 미치지 않습니다.) [UIEVENTS]

가장 가까운 조상 canvas 요소가 렌더링 중이며 내장 콘텐츠나타내는 요소는 관련 캔버스 대체 콘텐츠로 사용되고 있는 요소입니다.


canvas 요소에는 요소의 비트맵 크기를 제어하는 두 가지 속성인 widthheight가 있습니다. 이러한 속성은 지정될 경우 유효한 비음수 정수 값을 가져야 합니다. 비음수 정수를 구문 분석하는 규칙숫자 값을 얻는 데 사용되어야 합니다. 속성이 없거나 값을 구문 분석하는 중 오류가 발생하면 기본값이 대신 사용됩니다. width 속성의 기본값은 300이고, height 속성의 기본값은 150입니다.

width 또는 height 속성의 값을 설정할 때, canvas 요소의 컨텍스트 모드플레이스홀더로 설정되어 있는 경우, 사용자 에이전트는 "InvalidStateError" DOMException을 발생시키고 속성의 값을 변경하지 않아야 합니다.

canvas 요소가 내장 콘텐츠나타내는 경우, 요소의 자연스러운 크기는 요소의 비트맵 크기와 동일합니다.

사용자 에이전트는 canvas 및 그 렌더링 컨텍스트의 비트맵에 대해 좌표 공간 단위당 이미지 데이터 한 픽셀로 구성된 정사각형 픽셀 밀도를 사용해야 합니다.

canvas 요소는 스타일 시트에 의해 임의로 크기를 조정할 수 있으며, 이때 비트맵은 'object-fit' CSS 속성에 따릅니다.


캔버스 요소의 비트맵, ImageBitmap 객체의 비트맵 및 CanvasRenderingContext2DImageBitmapRenderingContext 객체와 같은 일부 렌더링 컨텍스트의 비트맵은 원본-클린(origin-clean) 플래그를 가지며, 이 플래그는 true 또는 false로 설정될 수 있습니다. 캔버스 요소 또는 ImageBitmap 객체가 생성될 때, 해당 비트맵의 원본-클린 플래그는 true로 설정되어야 합니다.

캔버스 요소는 렌더링 컨텍스트를 바인딩할 수 있습니다. 처음에는 바인딩된 렌더링 컨텍스트가 없습니다. 렌더링 컨텍스트가 있는지 여부와 어떤 종류의 렌더링 컨텍스트인지 추적하기 위해, 캔버스 요소는 캔버스 컨텍스트 모드도 가지며, 이는 처음에는 없음(none)이지만, 이 사양에 정의된 알고리즘에 의해 플레이스홀더(placeholder), 2d, bitmaprenderer, webgl, webgl2 또는 webgpu로 변경될 수 있습니다.

캔버스 컨텍스트 모드가 없음(none)일 때, 캔버스 요소에는 렌더링 컨텍스트가 없으며, 비트맵은 투명한 검정색이어야 하며 자연 너비는 요소의 width 속성의 숫자 값과 같아야 하고, 자연 높이는 요소의 height 속성의 숫자 값과 같아야 하며, 이 값들은 CSS 픽셀로 해석되며, 속성이 설정, 변경 또는 제거될 때 업데이트됩니다.

캔버스 컨텍스트 모드가 플레이스홀더(placeholder)일 때, 캔버스 요소에는 렌더링 컨텍스트가 없습니다. 이 요소는 OffscreenCanvas 객체의 플레이스홀더 역할을 하며, OffscreenCanvas 객체의 렌더링 컨텍스트에 의해 캔버스 요소의 내용이 업데이트됩니다.

캔버스 요소가 내장 콘텐츠를 나타낼 때, 이 요소는 요소의 자연 너비, 자연 높이 및 요소의 비트맵으로 구성된 페인트 소스를 제공합니다.

widthheight 콘텐츠 속성이 설정, 제거, 변경되거나 이미 가지고 있는 값으로 중복 설정될 때마다, 사용자 에이전트는 캔버스 요소의 컨텍스트 모드에 해당하는 다음 표의 작업을 수행해야 합니다.

컨텍스트 모드

작업

2d

비트맵 크기 설정 단계를 따라 widthheight 콘텐츠 속성의 숫자 값으로 설정합니다.

webgl 또는 webgl2

WebGL 사양에서 정의된 동작을 따릅니다. [WEBGL]

webgpu

WebGPU에서 정의된 동작을 따릅니다. [WEBGPU]

bitmaprenderer

컨텍스트의 비트맵 모드빈(blank)으로 설정되어 있는 경우, 캔버스 요소의 렌더링 컨텍스트를 전달하여 ImageBitmapRenderingContext의 출력 비트맵 설정 단계를 실행합니다.

플레이스홀더

아무 것도 하지 않습니다.

없음(none)

아무 것도 하지 않습니다.

HTMLCanvasElement/height

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

HTMLCanvasElement/width

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

widthheight IDL 속성은 동일한 이름을 가진 각각의 콘텐츠 속성을 반영해야 하며, 기본값도 동일합니다.


context = canvas.getContext(contextId [, options ])

HTMLCanvasElement/getContext

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

캔버스에서 그리기 API를 노출하는 객체를 반환합니다. contextId는 원하는 API를 지정합니다: "2d", "bitmaprenderer", "webgl", "webgl2", 또는 "webgpu". options는 해당 API에 의해 처리됩니다.

이 사양에서는 "2d" 및 "bitmaprenderer" 컨텍스트를 정의합니다. WebGL 사양은 "webgl" 및 "webgl2" 컨텍스트를 정의합니다. WebGPU는 "webgpu" 컨텍스트를 정의합니다. [WEBGL] [WEBGPU]

contextId가 지원되지 않거나, 캔버스가 이미 다른 컨텍스트 유형으로 초기화된 경우(예: "webgl" 컨텍스트를 가져온 후에 "2d" 컨텍스트를 가져오려고 할 때) null을 반환합니다.

canvas 요소의 getContext(contextId, options) 메서드를 호출할 때, 다음 단계를 실행해야 합니다:

  1. options객체가 아닌 경우, options를 null로 설정합니다.

  2. options를 JavaScript 값으로 변환한 결과로 설정합니다.

  3. canvas 요소의 캔버스 컨텍스트 모드contextId에 해당하는 표의 셀에 있는 단계를 실행합니다:

    none 2d bitmaprenderer webgl 또는 webgl2 webgpu placeholder
    "2d"
    1. context2D 컨텍스트 생성 알고리즘을 실행한 결과로 설정합니다. 여기서 thisoptions를 사용합니다.

    2. this컨텍스트 모드2d로 설정합니다.

    3. context를 반환합니다.

    이 메서드가 동일한 첫 번째 인수로 마지막으로 호출되었을 때 반환된 동일한 객체를 반환합니다. null을 반환합니다. null을 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 발생시킵니다.
    "bitmaprenderer"
    1. contextImageBitmapRenderingContext 생성 알고리즘을 실행한 결과로 설정합니다. 여기서 thisoptions를 사용합니다.

    2. this컨텍스트 모드bitmaprenderer로 설정합니다.

    3. context를 반환합니다.

    null을 반환합니다. 이 메서드가 동일한 첫 번째 인수로 마지막으로 호출되었을 때 반환된 동일한 객체를 반환합니다. null을 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 발생시킵니다.
    "webgl" 또는 "webgl2", 현재 구성에서 사용자가 WebGL 기능을 지원하는 경우
    1. context를 WebGL 사양의 컨텍스트 생성 섹션에서 제시한 지침을 따른 결과로 설정합니다. [WEBGL]

    2. context가 null인 경우 null을 반환합니다. 그렇지 않으면 this컨텍스트 모드webgl 또는 webgl2로 설정합니다.

    3. context를 반환합니다.

    null을 반환합니다. null을 반환합니다. 이 메서드가 동일한 첫 번째 인수로 마지막으로 호출되었을 때 반환된 동일한 객체를 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 발생시킵니다.
    "webgpu", 현재 구성에서 사용자가 WebGPU 기능을 지원하는 경우
    1. contextWebGPU캔버스 렌더링 섹션에서 제시한 지침을 따른 결과로 설정합니다. [WEBGPU]

    2. context가 null인 경우 null을 반환합니다. 그렇지 않으면 this컨텍스트 모드webgpu로 설정합니다.

    3. context를 반환합니다.

    null을 반환합니다. null을 반환합니다. null을 반환합니다. 이 메서드가 동일한 첫 번째 인수로 마지막으로 호출되었을 때 반환된 동일한 객체를 반환합니다. "InvalidStateError" DOMException을 발생시킵니다.
    지원되지 않는 값* null을 반환합니다. null을 반환합니다. null을 반환합니다. null을 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 발생시킵니다.

    * 예를 들어, 그래픽 하드웨어의 능력이 소진되고 소프트웨어 대체 구현이 없는 경우의 "webgl" 또는 "webgl2" 값.


url = canvas.toDataURL([ type [, quality ] ])

HTMLCanvasElement/toDataURL

모든 현재 엔진에서 지원됩니다.

Firefox2+Safari4+Chrome2+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

캔버스의 이미지를 위한 data: URL을 반환합니다.

첫 번째 인수는 제공된 경우 반환될 이미지의 형식을 제어합니다(예: PNG 또는 JPEG). 기본값은 "image/png"이며, 주어진 형식이 지원되지 않는 경우에도 해당 형식이 사용됩니다. 두 번째 인수는 가변 품질을 지원하는 이미지 형식(예: "image/jpeg")인 경우 적용되며, 0.0에서 1.0까지의 범위 내의 숫자로 결과 이미지에 대한 원하는 품질 수준을 나타냅니다.

"image/png"이 아닌 형식을 사용하려는 경우, 반환된 문자열이 "data:image/png," 또는 "data:image/png;" 중 하나로 시작하는지 확인하여 이미지가 요청된 형식으로 실제로 반환되었는지 확인할 수 있습니다. 그렇다면, 이미지는 PNG이며, 요청된 형식이 지원되지 않았음을 의미합니다. (예외는 캔버스에 높이 또는 너비가 없는 경우로, 이 경우 결과는 단순히 "data:,"일 수 있습니다.)

canvas.toBlob(callback [, type [, quality ] ])

HTMLCanvasElement/toBlob

모든 현재 엔진에서 지원됩니다.

Firefox18+Safari11+Chrome50+
Opera?Edge79+
Edge (Legacy)No🔰 10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

캔버스에 포함된 이미지를 나타내는 파일을 나타내는 Blob 객체를 생성하고 해당 객체에 대한 핸들을 사용하여 콜백을 호출합니다.

두 번째 인수는 제공된 경우 반환될 이미지의 형식을 제어합니다(예: PNG 또는 JPEG). 기본값은 "image/png"이며, 주어진 형식이 지원되지 않는 경우에도 해당 형식이 사용됩니다. 세 번째 인수는 가변 품질을 지원하는 이미지 형식(예: "image/jpeg")인 경우 적용되며, 0.0에서 1.0까지의 범위 내의 숫자로 결과 이미지에 대한 원하는 품질 수준을 나타냅니다.

canvas.transferControlToOffscreen()

HTMLCanvasElement/transferControlToOffscreen

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

OffscreenCanvas 객체를 새로 생성하여 반환합니다. 이 객체는 canvas 요소를 플레이스홀더로 사용합니다. 일단 canvas 요소가 OffscreenCanvas 객체의 플레이스홀더가 되면, 자연 크기를 더 이상 변경할 수 없으며 렌더링 컨텍스트를 가질 수 없습니다. 플레이스홀더 캔버스의 내용은 OffscreenCanvas 객체의 관련 에이전트이벤트 루프렌더링 업데이트 단계에서 업데이트됩니다.

toDataURL(type, quality) 메서드는 호출되면 다음 단계들을 실행해야 합니다:

  1. canvas 요소의 비트맵의 origin-clean 플래그가 false로 설정되어 있으면, "SecurityError" DOMException을 발생시킵니다.

  2. canvas 요소의 비트맵에 픽셀이 없으면(즉, 가로 또는 세로 크기가 0인 경우) 문자열 "data:,"을 반환합니다. (이는 최단 data: URL이며, text/plain 리소스에서 빈 문자열을 나타냅니다.)

  3. file을 이 canvas 요소의 비트맵을 파일로 직렬화한 결과로 설정하고, typequality가 주어진 경우 이를 전달합니다.

  4. file이 null이면 "data:,"을 반환합니다.

  5. file을 나타내는 data: URL을 반환합니다. [RFC2397]

toBlob(callback, type, quality) 메서드는 호출되면 다음 단계들을 실행해야 합니다:

  1. canvas 요소의 비트맵의 origin-clean 플래그가 false로 설정되어 있으면, "SecurityError" DOMException을 발생시킵니다.

  2. result를 null로 설정합니다.

  3. canvas 요소의 비트맵에 픽셀이 있으면(즉, 가로 또는 세로 크기가 0이 아닌 경우), result를 이 canvas 요소의 비트맵의 복사본으로 설정합니다.

  4. 다음 단계를 병렬로 실행합니다:

    1. result가 null이 아닌 경우 resulttypequality가 주어진 경우 이를 사용하여 result를 파일로 직렬화합니다.

    2. 캔버스 blob 직렬화 작업 소스에서 요소 작업을 큐에 넣고canvas 요소에 대해 다음 단계를 실행합니다:

      1. result가 null이 아닌 경우, result를 이 canvas 요소의 관련 영역에서 새로 생성된 Blob 객체로 설정하고, result를 나타냅니다. [FILEAPI]

      2. 콜백 함수를 호출합니다 « result »와 "보고서"를 사용하여.

transferControlToOffscreen() 메서드는 호출되면 다음 단계들을 실행해야 합니다:

  1. canvas 요소의 컨텍스트 모드없음으로 설정되어 있지 않으면 "InvalidStateError" DOMException을 발생시킵니다.

  2. offscreenCanvas를 이 canvas 요소의 widthheight 콘텐츠 속성 값과 동일한 크기로 새로 생성된 OffscreenCanvas 객체로 설정합니다.

  3. offscreenCanvas플레이스홀더 canvas 요소를 이 canvas 요소에 대한 약한 참조로 설정합니다.

  4. canvas 요소의 컨텍스트 모드플레이스홀더로 설정합니다.

  5. offscreenCanvas를 반환합니다.

4.12.5.1 2D 렌더링 컨텍스트

CanvasRenderingContext2D

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

CanvasImageSource

CanvasGradient

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

CanvasPattern

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+

TextMetrics

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari4+Chrome2+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android31+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

ImageData

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
typedef (HTMLImageElement or
         SVGImageElement) HTMLOrSVGImageElement;

typedef (HTMLOrSVGImageElement or
         HTMLVideoElement or
         HTMLCanvasElement or
         ImageBitmap or
         OffscreenCanvas or
         VideoFrame) CanvasImageSource;

enum PredefinedColorSpace { "srgb", "display-p3" };

enum CanvasFillRule { "nonzero", "evenodd" };

dictionary CanvasRenderingContext2DSettings {
  boolean alpha = true;
  boolean desynchronized = false;
  PredefinedColorSpace colorSpace = "srgb";
  boolean willReadFrequently = false;
};

enum ImageSmoothingQuality { "low", "medium", "high" };

[Exposed=Window]
interface CanvasRenderingContext2D {
  // back-reference to the canvas
  readonly attribute HTMLCanvasElement canvas;

  CanvasRenderingContext2DSettings getContextAttributes();
};
CanvasRenderingContext2D includes CanvasState;
CanvasRenderingContext2D includes CanvasTransform;
CanvasRenderingContext2D includes CanvasCompositing;
CanvasRenderingContext2D includes CanvasImageSmoothing;
CanvasRenderingContext2D includes CanvasFillStrokeStyles;
CanvasRenderingContext2D includes CanvasShadowStyles;
CanvasRenderingContext2D includes CanvasFilters;
CanvasRenderingContext2D includes CanvasRect;
CanvasRenderingContext2D includes CanvasDrawPath;
CanvasRenderingContext2D includes CanvasUserInterface;
CanvasRenderingContext2D includes CanvasText;
CanvasRenderingContext2D includes CanvasDrawImage;
CanvasRenderingContext2D includes CanvasImageData;
CanvasRenderingContext2D includes CanvasPathDrawingStyles;
CanvasRenderingContext2D includes CanvasTextDrawingStyles;
CanvasRenderingContext2D includes CanvasPath;

interface mixin CanvasState {
  // state
  undefined save(); // push state on state stack
  undefined restore(); // pop state stack and restore state
  undefined reset(); // reset the rendering context to its default state
  boolean isContextLost(); // return whether context is lost
};

interface mixin CanvasTransform {
  // transformations (default transform is the identity matrix)
  undefined scale(unrestricted double x, unrestricted double y);
  undefined rotate(unrestricted double angle);
  undefined translate(unrestricted double x, unrestricted double y);
  undefined transform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);

  [NewObject] DOMMatrix getTransform();
  undefined setTransform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);
  undefined setTransform(optional DOMMatrix2DInit transform = {});
  undefined resetTransform();

};

interface mixin CanvasCompositing {
  // compositing
  attribute unrestricted double globalAlpha; // (default 1.0)
  attribute DOMString globalCompositeOperation; // (default "source-over")
};

interface mixin CanvasImageSmoothing {
  // image smoothing
  attribute boolean imageSmoothingEnabled; // (default true)
  attribute ImageSmoothingQuality imageSmoothingQuality; // (default low)

};

interface mixin CanvasFillStrokeStyles {
  // colors and styles (see also the CanvasPathDrawingStyles and CanvasTextDrawingStyles interfaces)
  attribute (DOMString or CanvasGradient or CanvasPattern) strokeStyle; // (default black)
  attribute (DOMString or CanvasGradient or CanvasPattern) fillStyle; // (default black)
  CanvasGradient createLinearGradient(double x0, double y0, double x1, double y1);
  CanvasGradient createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1);
  CanvasGradient createConicGradient(double startAngle, double x, double y);
  CanvasPattern? createPattern(CanvasImageSource image, [LegacyNullToEmptyString] DOMString repetition);

};

interface mixin CanvasShadowStyles {
  // shadows
  attribute unrestricted double shadowOffsetX; // (default 0)
  attribute unrestricted double shadowOffsetY; // (default 0)
  attribute unrestricted double shadowBlur; // (default 0)
  attribute DOMString shadowColor; // (default transparent black)
};

interface mixin CanvasFilters {
  // filters
  attribute DOMString filter; // (default "none")
};

interface mixin CanvasRect {
  // rects
  undefined clearRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
  undefined fillRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
  undefined strokeRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
};

interface mixin CanvasDrawPath {
  // path API (see also CanvasPath)
  undefined beginPath();
  undefined fill(optional CanvasFillRule fillRule = "nonzero");
  undefined fill(Path2D path, optional CanvasFillRule fillRule = "nonzero");
  undefined stroke();
  undefined stroke(Path2D path);
  undefined clip(optional CanvasFillRule fillRule = "nonzero");
  undefined clip(Path2D path, optional CanvasFillRule fillRule = "nonzero");
  boolean isPointInPath(unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
  boolean isPointInPath(Path2D path, unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
  boolean isPointInStroke(unrestricted double x, unrestricted double y);
  boolean isPointInStroke(Path2D path, unrestricted double x, unrestricted double y);
};

interface mixin CanvasUserInterface {
  undefined drawFocusIfNeeded(Element element);
  undefined drawFocusIfNeeded(Path2D path, Element element);
};

interface mixin CanvasText {
  // text (see also the CanvasPathDrawingStyles and CanvasTextDrawingStyles interfaces)
  undefined fillText(DOMString text, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth);
  undefined strokeText(DOMString text, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth);
  TextMetrics measureText(DOMString text);
};

interface mixin CanvasDrawImage {
  // drawing images
  undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy);
  undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
  undefined drawImage(CanvasImageSource image, unrestricted double sx, unrestricted double sy, unrestricted double sw, unrestricted double sh, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
};

interface mixin CanvasImageData {
  // pixel manipulation
  ImageData createImageData([EnforceRange] long sw, [EnforceRange] long sh, optional ImageDataSettings settings = {});
  ImageData createImageData(ImageData imagedata);
  ImageData getImageData([EnforceRange] long sx, [EnforceRange] long sy, [EnforceRange] long sw, [EnforceRange] long sh, optional ImageDataSettings settings = {});
  undefined putImageData(ImageData imagedata, [EnforceRange] long dx, [EnforceRange] long dy);
  undefined putImageData(ImageData imagedata, [EnforceRange] long dx, [EnforceRange] long dy, [EnforceRange] long dirtyX, [EnforceRange] long dirtyY, [EnforceRange] long dirtyWidth, [EnforceRange] long dirtyHeight);
};

enum CanvasLineCap { "butt", "round", "square" };
enum CanvasLineJoin { "round", "bevel", "miter" };
enum CanvasTextAlign { "start", "end", "left", "right", "center" };
enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" };
enum CanvasDirection { "ltr", "rtl", "inherit" };
enum CanvasFontKerning { "auto", "normal", "none" };
enum CanvasFontStretch { "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" };
enum CanvasFontVariantCaps { "normal", "small-caps", "all-small-caps", "petite-caps", "all-petite-caps", "unicase", "titling-caps" };
enum CanvasTextRendering { "auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision" };

interface mixin CanvasPathDrawingStyles {
  // line caps/joins
  attribute unrestricted double lineWidth; // (default 1)
  attribute CanvasLineCap lineCap; // (default "butt")
  attribute CanvasLineJoin lineJoin; // (default "miter")
  attribute unrestricted double miterLimit; // (default 10)

  // dashed lines
  undefined setLineDash(sequence<unrestricted double> segments); // default empty
  sequence<unrestricted double> getLineDash();
  attribute unrestricted double lineDashOffset;
};

interface mixin CanvasTextDrawingStyles {
  // text
  attribute DOMString font; // (default 10px sans-serif)
  attribute CanvasTextAlign textAlign; // (default: "start")
  attribute CanvasTextBaseline textBaseline; // (default: "alphabetic")
  attribute CanvasDirection direction; // (default: "inherit")
  attribute DOMString letterSpacing; // (default: "0px")
  attribute CanvasFontKerning fontKerning; // (default: "auto")
  attribute CanvasFontStretch fontStretch; // (default: "normal")
  attribute CanvasFontVariantCaps fontVariantCaps; // (default: "normal")
  attribute CanvasTextRendering textRendering; // (default: "auto")
  attribute DOMString wordSpacing; // (default: "0px")
};

interface mixin CanvasPath {
  // shared path API methods
  undefined closePath();
  undefined moveTo(unrestricted double x, unrestricted double y);
  undefined lineTo(unrestricted double x, unrestricted double y);
  undefined quadraticCurveTo(unrestricted double cpx, unrestricted double cpy, unrestricted double x, unrestricted double y);
  undefined bezierCurveTo(unrestricted double cp1x, unrestricted double cp1y, unrestricted double cp2x, unrestricted double cp2y, unrestricted double x, unrestricted double y);
  undefined arcTo(unrestricted double x1, unrestricted double y1, unrestricted double x2, unrestricted double y2, unrestricted double radius); 
  undefined rect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
  undefined roundRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h, optional (unrestricted double or DOMPointInit or sequence<(unrestricted double or DOMPointInit)>) radii = 0);
  undefined arc(unrestricted double x, unrestricted double y, unrestricted double radius, unrestricted double startAngle, unrestricted double endAngle, optional boolean counterclockwise = false); 
  undefined ellipse(unrestricted double x, unrestricted double y, unrestricted double radiusX, unrestricted double radiusY, unrestricted double rotation, unrestricted double startAngle, unrestricted double endAngle, optional boolean counterclockwise = false); 
};

[Exposed=(Window,Worker)]
interface CanvasGradient {
  // opaque object
  undefined addColorStop(double offset, DOMString color);
};

[Exposed=(Window,Worker)]
interface CanvasPattern {
  // opaque object
  undefined setTransform(optional DOMMatrix2DInit transform = {});
};

[Exposed=(Window,Worker)]
interface TextMetrics {
  // x-direction
  readonly attribute double width; // advance width
  readonly attribute double actualBoundingBoxLeft;
  readonly attribute double actualBoundingBoxRight;

  // y-direction
  readonly attribute double fontBoundingBoxAscent;
  readonly attribute double fontBoundingBoxDescent;
  readonly attribute double actualBoundingBoxAscent;
  readonly attribute double actualBoundingBoxDescent;
  readonly attribute double emHeightAscent;
  readonly attribute double emHeightDescent;
  readonly attribute double hangingBaseline;
  readonly attribute double alphabeticBaseline;
  readonly attribute double ideographicBaseline;
};

dictionary ImageDataSettings {
  PredefinedColorSpace colorSpace;
};

[Exposed=(Window,Worker),
 Serializable]
interface ImageData {
  constructor(unsigned long sw, unsigned long sh, optional ImageDataSettings settings = {});
  constructor(Uint8ClampedArray data, unsigned long sw, optional unsigned long sh, optional ImageDataSettings settings = {});

  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  readonly attribute Uint8ClampedArray data;
  readonly attribute PredefinedColorSpace colorSpace;
};

[Exposed=(Window,Worker)]
interface Path2D {
  constructor(optional (Path2D or DOMString) path);

  undefined addPath(Path2D path, optional DOMMatrix2DInit transform = {});
};
Path2D includes CanvasPath;

기존 웹 콘텐츠와의 호환성을 유지하기 위해 사용자 에이전트는 CanvasUserInterface에 정의된 메서드를 stroke() 메서드 바로 뒤에 CanvasRenderingContext2D 객체에서 나열해야 합니다.

context = canvas.getContext('2d' [, { [ alpha: true ] [, desynchronized: false ] [, colorSpace: 'srgb'] [, willReadFrequently: false ]} ])

반환되는 객체는 CanvasRenderingContext2D 로, 특정 캔버스 요소에 영구적으로 바인딩됩니다.

만약 alpha 멤버가 false로 설정되면, 컨텍스트는 항상 불투명하게 설정됩니다.

만약 desynchronized 멤버가 true로 설정되면, 컨텍스트는 비동기화될 수 있습니다.

colorSpace 멤버는 렌더링 컨텍스트의 색상 공간을 지정합니다.

willReadFrequently 멤버가 true로 설정되면, 컨텍스트는 읽기 최적화를 위해 표시됩니다.

context.canvas

CanvasRenderingContext2D/canvas

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

해당 캔버스 요소를 반환합니다.

attributes = context.getContextAttributes()

반환되는 객체의 멤버는 다음과 같습니다:

A CanvasRenderingContext2D 객체는 생성 시 초기화되는 출력 비트맵을 가지고 있습니다.

출력 비트맵에는 원본-클린 플래그가 있으며, true 또는 false로 설정할 수 있습니다. 이 비트맵이 생성될 때, 원본-클린 플래그는 초기값으로 true로 설정되어야 합니다.

CanvasRenderingContext2D 객체는 또한 알파 불리언 값을 가지고 있습니다. 만약 CanvasRenderingContext2D 객체의 알파 값이 false일 경우, 알파 채널은 모든 픽셀에 대해 1.0(완전히 불투명)으로 고정되어야 하며, 어떤 픽셀의 알파 구성 요소를 변경하려는 시도는 조용히 무시되어야 합니다.

따라서, 이러한 컨텍스트의 비트맵은 불투명한 검정색으로 시작합니다. 투명한 검정색 대신에, clearRect()는 항상 불투명한 검정색 픽셀을 생성하며, getImageData()의 네 번째 바이트는 항상 255가 됩니다. putImageData() 메서드는 입력의 네 번째 바이트를 무시하게 됩니다. 그러나 캔버스에 그려진 스타일과 이미지의 알파 구성 요소는 여전히 출력 비트맵의 알파 채널에 영향을 미칠 때까지는 존중됩니다. 예를 들어, 새로 생성된 출력 비트맵알파가 false로 설정된 상태에서 50% 투명한 흰색 사각형을 그리면 완전히 불투명한 회색 사각형이 나타납니다.

CanvasRenderingContext2D 객체는 또한 비동기화 불리언 값을 가지고 있습니다. 만약 CanvasRenderingContext2D 객체의 비동기화 값이 true일 경우, 사용자 에이전트는 캔버스의 렌더링을 최적화하여 입력 이벤트에서 래스터화까지의 지연 시간을 줄이기 위해 캔버스 페인트 사이클을 이벤트 루프와 비동기화하거나, 일반적인 사용자 에이전트 렌더링 알고리즘을 우회할 수 있습니다. 이 모드는 일반적인 페인트 메커니즘이나 래스터화를 우회하기 때문에, 눈에 띄는 화면 찢김 현상이 발생할 수 있습니다.

사용자 에이전트는 일반적으로 표시되지 않는 버퍼에 렌더링을 수행하고, 빠르게 이를 표시 중인 버퍼와 교체하여 프레젠테이션을 수행합니다. 이전 버퍼는 백 버퍼라고 하고, 후자는 프론트 버퍼라고 합니다. 지연 시간을 줄이기 위한 인기 있는 기술 중 하나는 싱글 버퍼 렌더링으로도 알려진 프론트 버퍼 렌더링입니다. 이 기술은 스캔 과정과 병행하여 레이싱 방식으로 렌더링이 진행됩니다. 이 기술은 지연 시간을 줄이는 대신 화면 찢김 현상이 발생할 수 있으며, 비동기화 불리언 값을 구현하는 데 사용할 수 있습니다. [MULTIPLEBUFFERING]

비동기화 불리언 값은 드로잉 애플리케이션과 같이 입력과 래스터화 간의 지연 시간이 중요한 특정 유형의 애플리케이션을 구현할 때 유용할 수 있습니다.

CanvasRenderingContext2D 객체는 또한 자주 읽힐 것이라는 불리언 값을 가지고 있습니다. 만약 CanvasRenderingContext2D 객체의 자주 읽힐 것 값이 true일 경우, 사용자 에이전트는 캔버스의 읽기 작업을 최적화할 수 있습니다.

대부분의 장치에서 사용자 에이전트는 캔버스의 출력 비트맵을 GPU에 저장할지(이는 "하드웨어 가속"이라고도 합니다), CPU에 저장할지("소프트웨어"라고도 합니다)를 결정해야 합니다. 대부분의 렌더링 작업은 가속된 캔버스에서 더 성능이 우수하지만, getImageData(), toDataURL(), 또는 toBlob()과 같은 읽기 작업은 예외입니다. CanvasRenderingContext2D 객체가 자주 읽힐 것이 true로 설정되면, 사용자 에이전트는 웹페이지가 많은 읽기 작업을 수행할 가능성이 높다고 판단하고 소프트웨어 캔버스를 사용하는 것이 유리하다고 알립니다.

CanvasRenderingContext2D 객체는 또한 색상 공간 설정을 가지고 있으며, 이는 PredefinedColorSpace 유형입니다. CanvasRenderingContext2D 객체의 색상 공간출력 비트맵의 색상 공간을 나타냅니다.

getContextAttributes() 메서드는 다음과 같은 단계를 통해 값을 반환합니다: «[ "alpha" → thisalpha, "desynchronized" → thisdesynchronized, "colorSpace" → thiscolor space, "willReadFrequently" → thiswill read frequently ]».


CanvasRenderingContext2D 2D 렌더링 컨텍스트는 원점(0,0)이 왼쪽 상단 모서리에 위치한 평면 직선 데카르트 표면을 나타내며, 좌표 공간에서 x 값은 오른쪽으로 갈수록 증가하고, y 값은 아래로 갈수록 증가합니다. 오른쪽 가장자리의 x 좌표는 렌더링 컨텍스트의 출력 비트맵의 너비와 동일하며, 마찬가지로 아래쪽 가장자리의 y 좌표는 렌더링 컨텍스트의 출력 비트맵의 높이와 동일합니다.

좌표 공간의 크기가 사용자 에이전트가 내부적으로 또는 렌더링 중에 사용할 실제 비트맵의 크기를 반드시 나타내는 것은 아닙니다. 예를 들어, 고해상도 디스플레이에서는 사용자 에이전트가 좌표 공간의 단위당 네 개의 장치 픽셀을 사용하는 비트맵을 내부적으로 사용할 수 있어, 렌더링이 전반적으로 높은 품질을 유지할 수 있습니다. 유사하게, 안티앨리어싱은 최종 이미지의 해상도보다 높은 해상도의 비트맵을 오버샘플링하여 구현할 수 있습니다.

CSS 픽셀을 사용하여 렌더링 컨텍스트의 출력 비트맵의 크기를 설명한다고 해서, 렌더링될 때 캔버스가 동일한 영역을 CSS 픽셀로 덮는 것은 아닙니다. CSS 픽셀은 텍스트 레이아웃과 같은 CSS 기능과의 통합을 용이하게 하기 위해 재사용됩니다.

다시 말해서, 아래의 캔버스 요소의 렌더링 컨텍스트는 200x200 출력 비트맵을 가지고 있으며, 내부적으로는 CSS 픽셀을 단위로 사용하여 CSS와의 통합을 용이하게 하고, 100x100 CSS 픽셀로 렌더링됩니다:

<canvas width=200 height=200 style=width:100px;height:100px>

2D 컨텍스트 생성 알고리즘target(canvas 요소)과 options을 전달받아 다음 단계들을 실행합니다:

  1. settingsoptions을 사전형 타입 CanvasRenderingContext2DSettings으로 변환한 결과입니다. (예외를 발생시킬 수 있습니다.).

  2. context는 새로운 CanvasRenderingContext2D 객체입니다.

  3. contextcanvas 속성을 target을 가리키도록 초기화합니다.

  4. context출력 비트맵target의 비트맵과 동일하게 설정합니다(이 비트맵은 공유됩니다).

  5. 비트맵 크기 설정수치 값으로 target너비높이 콘텐츠 속성으로 설정합니다.

  6. context알파settings["alpha"]로 설정합니다.

  7. context비동기화settings["desynchronized"]로 설정합니다.

  8. context색 공간settings["colorSpace"]로 설정합니다.

  9. context자주 읽기settings["willReadFrequently"]로 설정합니다.

  10. context를 반환합니다.


사용자 에이전트가 비트맵 크기 설정widthheight로 설정하려면 다음 단계를 실행해야 합니다:

  1. 렌더링 컨텍스트를 기본 상태로 재설정합니다.

  2. 출력 비트맵을 새로운 widthheight로 크기를 조정합니다.

  3. canvas는 렌더링 컨텍스트의 canvas 속성이 초기화된 canvas 요소입니다.

  4. 만약 canvaswidth 콘텐츠 속성의 숫자 값이 width와 다르다면, canvaswidth 콘텐츠 속성을 width를 나타내는 가장 짧은 문자열로 설정합니다. 이 문자열은 유효한 0 이상의 정수이어야 합니다.

  5. 만약 canvasheight 콘텐츠 속성의 숫자 값이 height와 다르다면, canvasheight 콘텐츠 속성을 height를 나타내는 가장 짧은 문자열로 설정합니다. 이 문자열은 유효한 0 이상의 정수이어야 합니다.

다음 예제에서는 단 하나의 사각형만 그려지는 것으로 나타납니다:

// canvas는 <canvas> 요소에 대한 참조입니다.
    var context = canvas.getContext('2d');
    context.fillRect(0,0,50,50);
    canvas.setAttribute('width', '300'); // 캔버스를 초기화합니다.
    context.fillRect(0,100,50,50);
    canvas.width = canvas.width; // 캔버스를 초기화합니다.
    context.fillRect(100,0,50,50); // 이 사각형만 남습니다.

canvas 속성은 객체가 생성될 때 초기화된 값을 반환해야 합니다.


PredefinedColorSpace 열거형은 캔버스의 백킹 스토어의 색 공간을 지정하는 데 사용됩니다.

"srgb" 값은 'srgb' 색 공간을 나타냅니다.

"display-p3" 값은 'display-p3' 색 공간을 나타냅니다.

색 공간 간 변환 알고리즘은 CSS 색상미리 정의된 색상 공간 섹션에 설명되어 있습니다. [CSSCOLOR]


CanvasFillRule 열거형은 경로 안에 있는지 또는 밖에 있는지를 결정하는 채우기 규칙 알고리즘을 선택하는 데 사용됩니다.

"nonzero" 값은 비영수 규칙을 나타내며, 한 점이 도형 밖에 있다고 간주되려면, 그 점에서 그려진 반무한 직선이 한 방향으로 도형의 경로를 가로지르는 횟수와 다른 방향으로 경로를 가로지르는 횟수가 같아야 합니다.

"evenodd" 값은 홀짝 규칙을 나타내며, 한 점이 도형 밖에 있다고 간주되려면, 그 점에서 그려진 반무한 직선이 도형의 경로를 가로지르는 횟수가 짝수여야 합니다.

한 점이 도형 밖에 있지 않다면, 그 점은 도형 안에 있습니다.


ImageSmoothingQuality 열거형은 이미지를 부드럽게 할 때 사용할 보간 품질에 대한 선호도를 표현하는 데 사용됩니다.

"low" 값은 낮은 수준의 이미지 보간 품질을 선호하는 것을 나타냅니다. 낮은 품질의 이미지 보간은 더 높은 설정보다 계산 효율이 높을 수 있습니다.

"medium" 값은 중간 수준의 이미지 보간 품질을 선호하는 것을 나타냅니다.

"high" 값은 높은 수준의 이미지 보간 품질을 선호하는 것을 나타냅니다. 높은 품질의 이미지 보간은 더 낮은 설정보다 계산 비용이 더 많이 들 수 있습니다.

바이리니어 스케일링은 비교적 빠르고 낮은 품질의 이미지 부드럽게 처리 알고리즘의 예입니다. 바이큐빅 또는 Lanczos 스케일링은 더 높은 품질의 출력을 생성하는 이미지 부드럽게 처리 알고리즘의 예입니다. 이 사양에서는 특정 보간 알고리즘을 사용하도록 요구하지 않습니다.

4.12.5.1.1 구현 노트

이 섹션은 비규범적입니다.

출력 비트맵이 사용자 에이전트에 의해 직접 표시되지 않을 때, 구현체는 이 비트맵을 업데이트하는 대신, 비트맵의 실제 데이터가 필요해질 때까지(예를 들어 drawImage() 호출 또는 createImageBitmap() 팩토리 메서드 때문에) 이 비트맵에 적용된 그리기 작업의 순서를 기억하는 것으로 대체할 수 있습니다. 많은 경우, 이는 메모리 효율을 높일 수 있습니다.

canvas 요소의 비트맵은 실제로 항상 필요하게 되는 비트맵 중 하나입니다. 렌더링 컨텍스트의 출력 비트맵은 존재할 경우, 항상 canvas 요소의 비트맵에 대한 별칭입니다.

추가적인 비트맵이 필요한 경우도 있습니다. 예를 들어, 캔버스가 자연 크기와 다른 크기로 페인팅될 때 빠른 그리기를 가능하게 하거나, 페이지 스크롤링과 같은 그래픽 업데이트가 캔버스 그리기 명령이 실행되는 동안 동시에 처리될 수 있도록 이중 버퍼링을 가능하게 하기 위해서입니다.

4.12.5.1.2 캔버스 상태

이 섹션은 비규범적입니다.

CanvasState 인터페이스를 구현하는 객체는 그리기 상태의 스택을 유지합니다. 그리기 상태는 다음으로 구성됩니다:

렌더링 컨텍스트의 비트맵은 그리기 상태의 일부가 아닙니다. 이는 렌더링 컨텍스트가 캔버스 요소에 어떻게 바인딩되었는지에 따라 달라지기 때문입니다.

CanvasState 믹스인을 구현하는 객체는 생성될 때 초기값이 false인 컨텍스트 손실이라는 불리언을 가지고 있습니다. 컨텍스트 손실 값은 컨텍스트 손실 단계에서 업데이트됩니다.

context.save()

CanvasRenderingContext2D/save

모든 현재 엔진에서 지원됨.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 상태를 스택에 푸시합니다.

context.restore()

CanvasRenderingContext2D/restore

모든 현재 엔진에서 지원됨.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

스택의 맨 위 상태를 팝하여, 컨텍스트를 해당 상태로 복원합니다.

context.reset()

렌더링 컨텍스트를 재설정하며, 여기에는 백업 버퍼, 그리기 상태 스택, 경로 및 스타일이 포함됩니다.

context.isContextLost()

렌더링 컨텍스트가 손실되었는지 여부를 반환합니다. 컨텍스트 손실은 드라이버 충돌, 메모리 부족 등으로 인해 발생할 수 있습니다. 이러한 경우, 캔버스는 백업 스토리지를 잃고 렌더링 컨텍스트를 기본 상태로 재설정하기 위한 단계를 수행합니다.

save() 메서드는 현재 그리기 상태의 복사본을 그리기 상태 스택에 푸시하는 단계로 이루어집니다.

restore() 메서드는 그리기 상태 스택의 맨 위 항목을 팝하고, 그리기 상태를 초기화하는 단계로 이루어집니다. 저장된 상태가 없는 경우, 메서드는 아무 작업도 하지 않아야 합니다.

CanvasRenderingContext2D/reset

Firefox113+SafariNoChrome99+
Opera?Edge99+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

OffscreenCanvasRenderingContext2D#canvasrenderingcontext2d.reset

Firefox113+SafariNoChrome99+
Opera?Edge99+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

reset() 메서드는 렌더링 컨텍스트를 기본 상태로 재설정하는 단계로 구성됩니다.

렌더링 컨텍스트를 기본 상태로 재설정하려면 다음 단계를 수행합니다:

  1. 캔버스의 비트맵을 투명한 검정색으로 지웁니다.

  2. 컨텍스트의 현재 기본 경로에 있는 서브 경로 목록을 비웁니다.

  3. 컨텍스트의 그리기 상태 스택을 지웁니다.

  4. 그리기 상태를 초기값으로 재설정합니다.

CanvasRenderingContext2D/isContextLost

한 가지 엔진에서만 지원됨.

FirefoxNoSafariNoChrome99+
Opera?Edge99+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

isContextLost() 메서드는 this컨텍스트 손실을 반환하는 단계로 이루어집니다.

4.12.5.1.3 선 스타일
context.lineWidth [ = value ]

CanvasRenderingContext2D/lineWidth

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (이전 버전)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
styles.lineWidth [ = value ]

현재 선의 두께를 반환합니다.

설정할 수 있으며, 선의 두께를 변경합니다. 무한대가 아닌 0보다 큰 값만 유효합니다.

context.lineCap [ = value ]

CanvasRenderingContext2D/lineCap

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (이전 버전)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
styles.lineCap [ = value ]

현재 선 끝 스타일을 반환합니다.

설정할 수 있으며, 선 끝 스타일을 변경합니다.

가능한 선 끝 스타일은 "butt", "round", "square"입니다. 다른 값은 무시됩니다.

context.lineJoin [ = value ]

CanvasRenderingContext2D/lineJoin

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (이전 버전)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
styles.lineJoin [ = value ]

현재 선 결합 스타일을 반환합니다.

설정할 수 있으며, 선 결합 스타일을 변경합니다.

가능한 선 결합 스타일은 "bevel", "round", "miter"입니다. 다른 값은 무시됩니다.

context.miterLimit [ = value ]

CanvasRenderingContext2D/miterLimit

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (이전 버전)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
styles.miterLimit [ = value ]

현재 마이터 제한 비율을 반환합니다.

설정할 수 있으며, 마이터 제한 비율을 변경합니다. 무한대가 아닌 0보다 큰 값만 유효합니다.

context.setLineDash(segments)

CanvasRenderingContext2D/setLineDash

모든 현재 엔진에서 지원.

Firefox27+Safari7+Chrome23+
Opera?Edge79+
Edge (이전 버전)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
styles.setLineDash(segments)

현재 선 대시 패턴을 설정합니다(선을 그릴 때 사용됨). 인수는 선이 켜지고 꺼지도록 번갈아 가며 가지는 거리 목록입니다.

segments = context.getLineDash()

CanvasRenderingContext2D/getLineDash

모든 현재 엔진에서 지원.

Firefox27+Safari7+Chrome23+
Opera?Edge79+
Edge (이전 버전)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
segments = styles.getLineDash()

현재 선 대시 패턴의 복사본을 반환합니다. 반환된 배열에는 항상 짝수 항목이 있습니다(즉, 패턴이 정규화됨).

context.lineDashOffset

CanvasRenderingContext2D/lineDashOffset

모든 현재 엔진에서 지원.

Firefox27+Safari7+Chrome23+
Opera?Edge79+
Edge (이전 버전)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
styles.lineDashOffset

위상 오프셋(선 대시 패턴과 동일한 단위로)을 반환합니다.

설정할 수 있으며, 위상 오프셋을 변경합니다. 무한대가 아닌 값만 유효합니다.

CanvasPathDrawingStyles 인터페이스를 구현하는 객체에는 해당 객체에서 선이 처리되는 방식을 제어하는 속성과 메서드(이 섹션에 정의됨)가 있습니다.

lineWidth 속성은 선의 너비를 좌표 공간 단위로 제공합니다. 가져올 때 현재 값을 반환해야 합니다. 설정할 때 0, 음수, 무한대 및 NaN 값은 무시되어 값이 변경되지 않습니다. 다른 값은 현재 값을 새 값으로 변경해야 합니다.

CanvasPathDrawingStyles 인터페이스를 구현하는 객체가 생성될 때 lineWidth 속성은 초기값이 1.0이어야 합니다.


lineCap 속성은 UAs가 선의 끝에 배치할 엔딩 유형을 정의합니다. 유효한 세 가지 값은 "butt", "round", "square"입니다.

가져올 때 현재 값을 반환해야 합니다. 설정할 때 현재 값은 새 값으로 변경되어야 합니다.

CanvasPathDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, lineCap 속성은 초기값으로 "butt" 값을 가져야 합니다.


lineJoin 속성은 두 선이 만나는 지점에서 UAs가 배치할 코너 유형을 정의합니다. 유효한 세 가지 값은 "bevel", "round", "miter"입니다.

가져올 때 현재 값을 반환해야 합니다. 설정할 때 현재 값은 새 값으로 변경되어야 합니다.

CanvasPathDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, lineJoin 속성은 초기값으로 "miter" 값을 가져야 합니다.


lineJoin 속성이 "miter" 값을 가질 때, 스트로크는 조인을 렌더링하는 방법을 결정하기 위해 마이터 제한 비율을 사용합니다. 마이터 제한 비율은 miterLimit 속성을 사용하여 명시적으로 설정할 수 있습니다. 가져올 때 현재 값을 반환해야 합니다. 설정할 때 0, 음수, 무한대, NaN 값은 무시되어 값이 변경되지 않습니다. 다른 값은 현재 값을 새 값으로 변경해야 합니다.

CanvasPathDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, miterLimit 속성은 초기값으로 10.0 값을 가져야 합니다.


CanvasPathDrawingStyles 객체는 대시 목록을 가지고 있으며, 이는 비어 있거나 짝수 개의 음수가 아닌 숫자로 구성됩니다. 초기에는 대시 목록이 비어 있어야 합니다.

setLineDash(segments) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. segments의 값 중 하나라도 유한하지 않거나(예: Infinity 또는 NaN 값), 음수(0보다 작은 값)일 경우 반환합니다(예외를 던지지 않고; 그러나 사용자 에이전트는 개발자 콘솔에 메시지를 표시할 수 있으며, 이는 디버깅에 도움이 될 것입니다).

  2. segments의 요소 수가 홀수인 경우, segments를 두 개의 segments 사본으로 연결된 값으로 만듭니다.

  3. 객체의 대시 목록segments로 설정합니다.

getLineDash() 메서드가 호출되면, 객체의 대시 목록 값을 동일한 순서로 반환하는 시퀀스를 반환해야 합니다.

"행진하는 개미" 효과를 얻기 위해 대시 패턴의 "위상"을 변경하는 것이 유용할 때가 있습니다. 위상은 lineDashOffset 속성을 사용하여 설정할 수 있습니다. 가져올 때 현재 값을 반환해야 합니다. 설정할 때 무한대와 NaN 값은 무시되어 값이 변경되지 않습니다. 다른 값은 현재 값을 새 값으로 변경해야 합니다.

CanvasPathDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, lineDashOffset 속성은 초기값으로 0.0 값을 가져야 합니다.


사용자 에이전트가 경로를 추적해야 할 때, CanvasPathDrawingStyles 인터페이스를 구현하는 style 객체를 지정하고, 다음 알고리즘을 실행해야 합니다. 이 알고리즘은 새로운 경로를 반환합니다.

  1. path를 추적 중인 경로의 복사본으로 설정합니다.

  2. path에서 모든 길이가 0인 선분을 제거합니다.

  3. 선이 없는 서브패스(즉, 한 점만 포함된 서브패스)를 path에서 제거합니다.

  4. 각 서브패스에서 첫 번째 점과 마지막 점 이외의 모든 점을 한 줄에서 다른 줄로 이어지는 조인으로 대체하여, 각 서브패스가 두 점(출발점과 도착점)과 이를 연결하는 선분, 그리고 각 조인을 포함한 일련의 선분으로 구성되도록 합니다.

  5. 각 닫힌 서브패스에 마지막 점과 첫 번째 점을 연결하는 직선을 추가합니다. 이전 마지막 선에서 새로 추가된 닫는 선으로 연결된 조인으로 마지막 점을 변경하고, 새로 추가된 닫는 선에서 첫 번째 선으로 연결된 조인으로 첫 번째 점을 변경합니다.

  6. 만약 style대시 목록이 비어 있다면, 변환으로 표시된 단계로 이동합니다.

  7. style대시 목록의 모든 항목을 좌표 공간 단위로 연결한 값을 패턴 너비로 설정합니다.

  8. 각 서브패스 subpath에 대해, path에서 서브패스를 변형하는 다음 단계들을 실행합니다.

    1. subpath의 모든 선분의 길이를 좌표 공간 단위로 계산하여 subpath 너비를 설정합니다.

    2. stylelineDashOffset 값을 좌표 공간 단위로 변환하여 오프셋을 설정합니다.

    3. 오프셋패턴 너비보다 클 경우, 패턴 너비만큼 감소시킵니다.

      오프셋이 0보다 작을 경우, 패턴 너비만큼 증가시킵니다.

    4. Lsubpath의 모든 선을 따라 정의된 선형 좌표선으로 설정합니다. subpath의 첫 번째 선의 시작점은 좌표 0으로 정의되고, 마지막 선의 끝점은 subpath 너비로 정의됩니다.

    5. position을 0에서 오프셋을 뺀 값으로 설정합니다.

    6. index를 0으로 설정합니다.

    7. 현재 상태off로 설정합니다(다른 상태는 onzero-on입니다).

    8. 대시 켜짐: segment lengthstyle대시 목록index번째 항목의 값으로 설정합니다.

    9. positionsegment length만큼 증가시킵니다.

    10. positionsubpath 너비보다 크다면, 이 서브패스에 대한 단계를 종료하고 다음 서브패스에 대해 다시 시작합니다. 더 이상 서브패스가 없다면, 변환 단계로 이동합니다.

    11. segment length가 0이 아니면, 현재 상태on으로 설정합니다.

    12. index를 1씩 증가시킵니다.

    13. 대시 꺼짐: segment lengthstyle대시 목록index번째 항목의 값으로 설정합니다.

    14. startLposition 오프셋으로 설정합니다.

    15. positionsegment length만큼 증가시킵니다.

    16. position이 0보다 작으면, 포스트 컷 단계로 이동합니다.

    17. start가 0보다 작으면, start를 0으로 설정합니다.

    18. positionsubpath 너비보다 크면, endLsubpath 너비 오프셋으로 설정합니다. 그렇지 않으면 endLposition 오프셋으로 설정합니다.

    19. 적절한 첫 번째 단계로 이동합니다:

      만약 segment length가 0이고 현재 상태off라면

      아무 것도 하지 않고 다음 단계로 계속 진행합니다.

      현재 상태off라면

      end에서 시작하는 선을 end에서 짧게 자르고 그곳에 점을 배치합니다. 두 서브패스를 자르고 startend 사이에 있는 모든 선분, 조인, 점, 서브패스를 제거한 후, start에 연결되지 않은 점을 하나 배치합니다.

      점은 선 캡을 그릴 때 방향성을 가집니다. 방향성은 해당 지점에서 원래 선이 가졌던 방향입니다.

      그 외의 경우

      start에서 시작하는 선을 start에서 자르고 그곳에 점을 배치한 후, end에서 끝나는 선을 end에서 자르고 그곳에 점을 배치하여 두 서브패스를 자르고, startend 사이에 있는 모든 선분, 조인, 점, 서브패스를 제거합니다.

      startend가 동일한 점이라면, 선만 두 부분으로 나뉘고 점 두 개가 삽입되며, 조인이 같은 지점에 있는 경우를 제외하고는 아무 것도 제거되지 않습니다.

    20. 포스트 컷: positionsubpath 너비보다 크면, 변환 단계로 이동합니다.

    21. 만약 segment length가 0보다 크면, positioned-at-on-dash를 false로 설정합니다.

    22. index를 1씩 증가시킵니다. 만약 style대시 목록 항목 수와 같다면, index를 0으로 설정합니다.

    23. 대시 켜짐 단계로 돌아갑니다.

  9. 변환: 경로를 새로운 경로로 변환하는 단계입니다.

    경로를 따라 stylelineWidth 길이만큼의 직선을 스윕하며, 선이 경로에 수직을 유지하도록 하여 경로를 생성합니다. 이 때 각 점을 stylelineCap 속성에 맞는 엔드 캡으로 대체하고, 각 조인을 stylelineJoin 유형에 맞는 조인으로 대체합니다.

    : 각 점에는 나오는 선의 방향과 수직인 평평한 모서리가 있습니다. stylelineCap 값에 따라 추가적인 선 캡이 추가됩니다. "butt" 값은 추가적인 선 캡이 추가되지 않음을 의미합니다. "round" 값은 stylelineWidth 폭과 같은 직경의 반원형이 각 점에 추가됨을 의미합니다. "square" 값은 stylelineWidth 폭의 절반 길이만큼의 직사각형이 점에 추가됨을 의미합니다.

    점에 연결된 선이 없는 경우, 두 개의 캡이 방향성을 따라 서로 등을 맞대고 배치됩니다.

    조인: 조인이 발생하는 지점 외에도 각 선에 대해 두 개의 추가적인 점이 있습니다: 조인 지점에서 선의 반 너비만큼 떨어진 두 모서리입니다.

    이 두 모서리를 직선으로 연결한 삼각형이 모든 조인에 추가됩니다. lineJoin 속성은 이 외에 추가로 그려질 항목을 제어합니다. "bevel" 값은 조인에서 삼각형만 그려지는 것을 의미합니다.

    "round" 값은 조인의 두 모서리를 연결하는 호가 삼각형에 추가됨을 의미합니다.

    "miter" 값은 조인에서 두 번째 삼각형이 추가됨을 의미하며, 이는 첫 번째 삼각형에 인접하게 위치하고, 두 번째 삼각형의 선은 두 선의 바깥쪽 가장자리의 연장선으로 구성됩니다. 이 삼각형은 마이터 길이가 초과되지 않을 때까지 추가됩니다.

    새로 생성된 경로의 서브패스는 각 점에서 반-무한 직선을 그려 교차하는 횟수가 짝수인 경우와 동일한 방향으로 교차하는 횟수가 같은 경우에만 짝수로 유지되도록 방향을 지정해야 합니다.

  10. 새로 생성된 경로를 반환합니다.

4.12.5.1.4 텍스트 스타일
context.font [ = value ]

CanvasRenderingContext2D/font

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
styles.font [ = value ]

현재 글꼴 설정을 반환합니다.

설정할 수 있으며, 글꼴을 변경할 수 있습니다. 구문은 CSS 'font' 속성과 동일합니다. CSS 글꼴 값으로 구문 분석할 수 없는 값은 무시됩니다.

상대적 키워드 및 길이는 캔버스 요소의 글꼴에 상대적으로 계산됩니다.

context.textAlign [ = value ]

CanvasRenderingContext2D/textAlign

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
styles.textAlign [ = value ]

현재 텍스트 정렬 설정을 반환합니다.

설정할 수 있으며, 정렬을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "start"입니다.

context.textBaseline [ = value ]

CanvasRenderingContext2D/textBaseline

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
styles.textBaseline [ = value ]

현재 기준선 정렬 설정을 반환합니다.

설정할 수 있으며, 기준선 정렬을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "alphabetic"입니다.

context.direction [ = value ]

CanvasRenderingContext2D/direction

모든 현재 엔진에서 지원됩니다.

Firefox101+Safari9+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
styles.direction [ = value ]

현재 방향성을 반환합니다.

설정할 수 있으며, 방향성을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "inherit"입니다.

context.letterSpacing [ = value ]
styles.letterSpacing [ = value ]

현재 텍스트의 문자 간격을 반환합니다.

설정할 수 있으며, 문자 간격을 변경할 수 있습니다. CSS <길이>로 구문 분석할 수 없는 값은 무시됩니다. 기본값은 "0px"입니다.

context.fontKerning [ = value ]
styles.fontKerning [ = value ]

현재 글꼴 커닝 설정을 반환합니다.

설정할 수 있으며, 글꼴 커닝을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "auto"입니다.

context.fontStretch [ = value ]
styles.fontStretch [ = value ]

현재 글꼴 확장 설정을 반환합니다.

설정할 수 있으며, 글꼴 확장을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "normal"입니다.

context.fontVariantCaps [ = value ]
styles.fontVariantCaps [ = value ]

현재 글꼴 대문자 변형 설정을 반환합니다.

설정할 수 있으며, 글꼴 대문자 변형을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "normal"입니다.

context.textRendering [ = value ]
styles.textRendering [ = value ]

현재 텍스트 렌더링 설정을 반환합니다.

설정할 수 있으며, 텍스트 렌더링을 변경할 수 있습니다. 가능한 값과 그 의미는 아래에 설명되어 있습니다. 다른 값은 무시됩니다. 기본값은 "auto"입니다.

context.wordSpacing [ = value ]
styles.wordSpacing [ = value ]

현재 텍스트의 단어 간격을 반환합니다.

설정할 수 있으며, 단어 간격을 변경할 수 있습니다. CSS <길이>로 구문 분석할 수 없는 값은 무시됩니다. 기본값은 "0px"입니다.

다음 인터페이스를 구현하는 객체는 CanvasTextDrawingStyles로, 이 섹션에서 정의된 텍스트가 어떻게 배치되는지(래스터화 또는 윤곽화) 제어하는 속성을 가지고 있습니다. 이러한 객체는 또한 글꼴 스타일 소스 객체를 가질 수 있습니다. CanvasRenderingContext2D 객체의 경우, 이 값은 컨텍스트의 캔버스 요소에 의해 결정됩니다. OffscreenCanvasRenderingContext2D 객체의 경우, 이것은 관련된 OffscreenCanvas 객체입니다.

글꼴 스타일 소스 객체에 대한 글꼴 해상도는 글꼴 소스를 필요로 합니다. 이는 CanvasTextDrawingStyles를 구현하는 주어진 객체에 대해 다음 단계에 따라 결정됩니다: [CSSFONTLOAD]

  1. 객체글꼴 스타일 소스 객체캔버스 요소인 경우, 요소의 노드 문서를 반환합니다.

  2. 그렇지 않은 경우, 객체글꼴 스타일 소스 객체OffscreenCanvas 객체입니다:

    1. global객체관련 글로벌 객체로 설정합니다.

    2. globalWindow 객체인 경우, global관련 문서를 반환합니다.

    3. 확인: globalWorkerGlobalScope를 구현합니다.

    4. global을 반환합니다.

다음은 ID가 c1인 일반 캔버스 요소를 사용한 글꼴 해상도의 예입니다.

const font = new FontFace("MyCanvasFont", "url(mycanvasfont.ttf)"); documents.fonts.add(font);const context = document.getElementById("c1").getContext("2d"); document.fonts.ready.then(function() { context.font = "64px MyCanvasFont"; context.fillText("hello", 0, 0); });

이 예제에서 캔버스는 글꼴로 mycanvasfont.ttf를 사용하여 텍스트를 표시합니다.

다음은 OffscreenCanvas를 사용하여 글꼴 해상도가 어떻게 발생할 수 있는지에 대한 예입니다. ID가 c2캔버스 요소가 작업자에게 다음과 같이 전송된다고 가정합니다:

const offscreenCanvas = document.getElementById("c2").transferControlToOffscreen(); worker.postMessage(offscreenCanvas, [offscreenCanvas]);

그런 다음, 작업자에서:

self.onmessage = function(ev) { const transferredCanvas = ev.data; const context = transferredCanvas.getContext("2d"); const font = new FontFace("MyFont", "url(myfont.ttf)"); self.fonts.add(font); self.fonts.ready.then(function() { context.font = "64px MyFont"; context.fillText("hello", 0, 0); }); };

이 예제에서 캔버스는 myfont.ttf를 사용하여 텍스트를 표시합니다. 이때 글꼴은 문서 컨텍스트가 아닌 작업자 내에서만 로드된다는 점에 주목하세요.

font IDL 속성은 설정 시 CSS <'font'> 값으로 파싱되어야 하며, 결과적인 글꼴은 컨텍스트에 할당되어야 합니다. 여기서 'line-height' 구성 요소는 'normal'로 강제되며, 'font-size' 구성 요소는 CSS 픽셀로 변환되고, 시스템 글꼴은 명시적인 값으로 계산됩니다. 새로운 값이 구문적으로 잘못된 경우(예: 'inherit' 또는 'initial'과 같은 독립적인 스타일 시트 구문 사용 포함) 새 글꼴 값을 할당하지 않고 무시되어야 합니다. [CSS]

글꼴 패밀리 이름은 글꼴이 사용될 때 글꼴 스타일 소스 객체의 컨텍스트에서 해석되어야 합니다. 따라서 @font-face를 사용하여 임베드된 모든 글꼴 또는 FontFace 객체를 사용하여 로드된 글꼴은 로드된 후에 사용할 수 있어야 합니다. (각 글꼴 스타일 소스 객체에는 글꼴 소스가 있으며, 이는 사용 가능한 글꼴을 결정합니다.) 글꼴이 완전히 로드되기 전에 사용되거나 글꼴 스타일 소스 객체가 해당 글꼴을 사용해야 하는 시점에 그 글꼴을 범위에 포함하지 않는 경우, 이는 알 수 없는 글꼴로 간주되어 관련 CSS 사양에 따라 다른 글꼴로 대체되어야 합니다. [CSSFONTS] [CSSFONTLOAD]

속성 취득 시, font 속성은 컨텍스트의 현재 글꼴을 직렬화된 형태로 반환해야 합니다 (여기에는 'line-height' 구성 요소가 포함되지 않습니다). [CSSOM]

예를 들어, 다음 문장 후:

context.font = 'italic 400 12px/2 Unknown Font, sans-serif';

...context.font 표현식은 "italic 12px "Unknown Font", sans-serif" 문자열로 평가됩니다. "400" 폰트 무게는 기본값이기 때문에 나타나지 않습니다. 라인 높이는 "normal"로 강제되므로 나타나지 않습니다.

CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, 컨텍스트의 글꼴은 10px sans-serif로 설정되어야 합니다. 'font-size' 구성 요소가 퍼센트, 'em' 또는 'ex' 단위, 또는 'larger' 또는 'smaller' 키워드를 사용하여 설정된 경우, 이는 계산된 값을 기준으로 해석되어야 합니다. 이 속성이 설정된 시점에 글꼴 스타일 소스 객체가 요소인 경우, 'font-weight' 구성 요소가 'bolder'와 'lighter' 상대값으로 설정된 경우, 이는 계산된 값을 기준으로 해석되어야 합니다. 특정 사례에 대해 계산된 값이 정의되지 않은 경우(예: 글꼴 스타일 소스 객체가 요소가 아니거나 렌더링되지 않음인 경우), 상대 키워드는 기본값인 normal-weight 10px sans-serif에 대해 상대적으로 해석되어야 합니다.

textAlign IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, textAlign 속성은 처음에 start 값을 가져야 합니다.

textBaseline IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, textBaseline 속성은 처음에 alphabetic 값을 가져야 합니다.

direction IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, direction 속성은 처음에 "inherit" 값을 가져야 합니다.

CanvasTextDrawingStyles 인터페이스를 구현하는 객체는 글자 간 및 단어 간의 간격을 제어하는 속성을 가지고 있습니다. 이러한 객체는 글자 간격단어 간격 값을 가지며, 이는 CSS <길이> 값입니다. 초기에는 둘 다 CSS <길이>로 "0px"을 파싱한 결과로 설정되어야 합니다.

CanvasRenderingContext2D/letterSpacing

한 개의 엔진에서만 지원됩니다.

Firefox아니요Safari아니요Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

letterSpacing getter 단계는 직렬화된 형태로 반환하는 것입니다. this's letter spacing.

letterSpacing setter 단계는 다음과 같습니다:

  1. parsed 값을 파싱 결과로 CSS <length>으로 변환합니다.

  2. parsed 값이 실패하면, 반환합니다.

  3. this's letter spacingparsed 값으로 설정합니다.

CanvasRenderingContext2D/wordSpacing

한 개의 엔진에서만 지원됩니다.

Firefox아니요Safari아니요Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

wordSpacing getter 단계는 직렬화된 형태로 반환하는 것입니다. this's word spacing.

wordSpacing setter 단계는 다음과 같습니다:

  1. parsed 값을 파싱 결과로 CSS <length>으로 변환합니다.

  2. parsed 값이 실패하면, 반환합니다.

  3. this's word spacingparsed 값으로 설정합니다.

CanvasRenderingContext2D/fontKerning

Firefox104+Safari아니요Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

fontKerning IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, fontKerning 속성은 처음에 "auto" 값을 가져야 합니다.

CanvasRenderingContext2D/fontStretch

한 개의 엔진에서만 지원됩니다.

Firefox아니요Safari아니요Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

fontStretch IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, fontStretch 속성은 처음에 "normal" 값을 가져야 합니다.

CanvasRenderingContext2D/fontVariantCaps

한 개의 엔진에서만 지원됩니다.

Firefox아니요Safari아니요Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

fontVariantCaps IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, fontVariantCaps 속성은 처음에 "normal" 값을 가져야 합니다.

CanvasRenderingContext2D/textRendering

한 개의 엔진에서만 지원됩니다.

Firefox아니요Safari아니요Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

textRendering IDL 속성은 취득 시 현재 값을 반환해야 합니다. 설정 시, 현재 값은 새 값으로 변경되어야 합니다. CanvasTextDrawingStyles 인터페이스를 구현하는 객체가 생성될 때, textRendering 속성은 처음에 "auto" 값을 가져야 합니다.

textAlign 속성의 허용된 키워드는 다음과 같습니다:

start

텍스트의 시작 가장자리에 맞춥니다(왼쪽에서 오른쪽으로 쓰는 텍스트의 경우 왼쪽, 오른쪽에서 왼쪽으로 쓰는 텍스트의 경우 오른쪽).

end

텍스트의 끝 가장자리에 맞춥니다(왼쪽에서 오른쪽으로 쓰는 텍스트의 경우 오른쪽, 오른쪽에서 왼쪽으로 쓰는 텍스트의 경우 왼쪽).

left

왼쪽에 맞춥니다.

right

오른쪽에 맞춥니다.

center

가운데에 맞춥니다.

textBaseline 속성의 허용된 키워드는 폰트의 정렬 지점에 해당합니다:

글꼴에서 em 사각형의 맨 위는 글리프의 맨 위에 대략 위치하며, 'hanging' 기준선은 आ와 같은 글리프가 앵커되는 위치입니다. 중간은 em 사각형의 맨 위와 맨 아래 사이의 중간 지점에 위치하며, 알파벳 기준선은 Á, ÿ, f, Ω과 같은 문자가 앵커되는 위치입니다. 'ideographic-under' 기준선은 私, 達와 같은 글리프가 앵커되는 위치입니다. em 사각형의 맨 아래는 글꼴에서 글리프의 맨 아래에 대략 위치합니다. 경계 상자의 맨 위와 맨 아래는 글리프가 em 사각형 밖으로 크게 확장될 수 있기 때문에 이러한 기준선에서 멀리 떨어질 수 있습니다.

키워드는 다음과 같은 정렬 지점에 매핑됩니다:

top
em 사각형의 맨 위
hanging
hanging 기준선
middle
em 사각형의 중간
alphabetic
알파벳 기준선
ideographic
ideographic-under 기준선
bottom
em 사각형의 맨 아래

direction 속성의 허용된 키워드는 다음과 같습니다:

ltr

입력을 텍스트 준비 알고리즘에서 왼쪽에서 오른쪽으로 읽히는 텍스트로 처리합니다.

rtl

입력을 텍스트 준비 알고리즘에서 오른쪽에서 왼쪽으로 읽히는 텍스트로 처리합니다.

inherit

기본적으로 캔버스 요소나 document의 방향성을 따릅니다.

fontKerning 속성의 허용된 키워드는 다음과 같습니다:

auto

커닝이 사용자 에이전트의 재량에 따라 적용됩니다.

normal

커닝이 적용됩니다.

none

커닝이 적용되지 않습니다.

fontStretch 속성의 허용된 키워드는 다음과 같습니다:

ultra-condensed

CSS 'font-stretch' 'ultra-condensed' 설정과 동일합니다.

extra-condensed

CSS 'font-stretch' 'extra-condensed' 설정과 동일합니다.

condensed

CSS 'font-stretch' 'condensed' 설정과 동일합니다.

semi-condensed

CSS 'font-stretch' 'semi-condensed' 설정과 동일합니다.

normal

기본 설정으로, 글리프의 너비가 100%입니다.

semi-expanded

CSS 'font-stretch' 'semi-expanded' 설정과 동일합니다.

expanded

CSS 'font-stretch' 'expanded' 설정과 동일합니다.

extra-expanded

CSS 'font-stretch' 'extra-expanded' 설정과 동일합니다.

ultra-expanded

CSS 'font-stretch' 'ultra-expanded' 설정과 동일합니다.

fontVariantCaps 속성의 허용된 키워드는 다음과 같습니다:

normal

아래에 나열된 기능 중 어느 것도 활성화되지 않습니다.

small-caps

CSS 'font-variant-caps' 'small-caps' 설정과 동일합니다.

all-small-caps

CSS 'font-variant-caps' 'all-small-caps' 설정과 동일합니다.

petite-caps

CSS 'font-variant-caps' 'petite-caps' 설정과 동일합니다.

all-petite-caps

CSS 'font-variant-caps' 'all-petite-caps' 설정과 동일합니다.

unicase

CSS 'font-variant-caps' 'unicase' 설정과 동일합니다.

titling-caps

CSS 'font-variant-caps' 'titling-caps' 설정과 동일합니다.

textRendering 속성의 허용된 키워드는 다음과 같습니다:

auto

SVG 텍스트 렌더링 속성에서 'auto'와 동일합니다.

optimizeSpeed

SVG 텍스트 렌더링 속성에서 'optimizeSpeed'와 동일합니다.

optimizeLegibility

SVG 텍스트 렌더링 속성에서 'optimizeLegibility'와 동일합니다.

geometricPrecision

SVG 텍스트 렌더링 속성에서 'geometricPrecision'과 동일합니다.

텍스트 준비 알고리즘은 다음과 같습니다. 이 알고리즘은 문자열 text, CanvasTextDrawingStyles 객체 target, 그리고 선택적인 길이 maxWidth를 입력으로 받습니다. 이 알고리즘은 공통 좌표 공간에 위치한 글리프 형태 배열, 왼쪽, 오른쪽, 중앙 중 하나인 물리적 정렬, 그리고 인라인 박스를 반환합니다. (이 알고리즘을 호출하는 대부분의 호출자는 물리적 정렬인라인 박스를 무시합니다.)

  1. maxWidth가 제공되었지만 0 이하이거나 NaN인 경우 빈 배열을 반환합니다.

  2. text의 모든 ASCII 공백 문자를 U+0020 SPACE 문자로 대체합니다.

  3. fonttargetfont 속성으로부터 가져와 설정합니다.

  4. 다음 목록에서 적절한 단계를 적용하여 direction 값을 결정합니다:

    target 객체의 direction 속성 값이 "ltr"인 경우
    direction 값을 'ltr'로 설정합니다.
    target 객체의 direction 속성 값이 "rtl"인 경우
    direction 값을 'rtl'로 설정합니다.
    target 객체의 글꼴 스타일 소스 객체가 요소인 경우
    direction 값을 target 객체의 글꼴 스타일 소스 객체방향성으로 설정합니다.
    target 객체의 글꼴 스타일 소스 객체document이며 null이 아닌 문서 요소를 가지고 있는 경우
    direction 값을 target 객체의 글꼴 스타일 소스 객체문서 요소방향성으로 설정합니다.
    그 외의 경우
    direction 값을 'ltr'로 설정합니다.
  5. 가상으로 무한히 넓은 CSS 라인 박스를 형성하여 text가 포함된 단일 인라인 박스를 포함시키며, 이 박스의 CSS 속성은 다음과 같이 설정됩니다:

    속성 소스
    'direction' direction
    'font' font
    'font-kerning' targetfontKerning
    'font-stretch' targetfontStretch
    'font-variant-caps' targetfontVariantCaps
    'letter-spacing' targetletter spacing
    SVG text-rendering targettextRendering
    'white-space' 'pre'
    'word-spacing' targetword spacing

    모든 다른 속성은 초기 값으로 설정됩니다.

  6. maxWidth가 제공되고 가상 라인 박스 내의 인라인 박스의 가상 너비가 maxWidth보다 큰 경우, font를 더 압축된 글꼴로 변경(사용 가능한 경우 또는 가로 축소 인자를 적용하여 합리적으로 읽을 수 있는 글꼴이 생성될 수 있는 경우)하거나 더 작은 글꼴로 변경하고 이전 단계로 돌아갑니다.

  7. 앵커 포인트인라인 박스의 한 지점이며, 물리적 정렬왼쪽, 오른쪽, 중앙 중 하나입니다. 이 변수들은 textAligntextBaseline 값에 따라 다음과 같이 결정됩니다:

    수평 위치:

    textAlignleft인 경우
    textAlignstart이고 direction이 'ltr'인 경우
    textAlignend이고 direction이 'rtl'인 경우
    앵커 포인트의 수평 위치를 인라인 박스의 왼쪽 가장자리로 설정하고, 물리적 정렬왼쪽으로 설정합니다.
    textAlignright인 경우
    textAlignend이고 direction이 'ltr'인 경우
    textAlignstart이고 direction이 'rtl'인 경우
    앵커 포인트의 수평 위치를 인라인 박스의 오른쪽 가장자리로 설정하고, 물리적 정렬오른쪽으로 설정합니다.
    textAligncenter인 경우
    앵커 포인트의 수평 위치를 인라인 박스의 왼쪽과 오른쪽 가장자리 사이의 중간으로 설정하고, 물리적 정렬중앙으로 설정합니다.

    수직 위치:

    textBaselinetop인 경우
    앵커 포인트의 수직 위치를 첫 번째 사용 가능한 글꼴의 em 상자의 상단으로 설정합니다.
    textBaselinehanging인 경우
    앵커 포인트의 수직 위치를 행잉 기준선첫 번째 사용 가능한 글꼴의 em 상자의 상단으로 설정합니다.
    textBaselinemiddle인 경우
    앵커 포인트의 수직 위치를 첫 번째 사용 가능한 글꼴의 em 상자의 하단과 상단 사이 중간으로 설정합니다.
    textBaselinealphabetic인 경우
    앵커 포인트의 수직 위치를 알파벳 기준선첫 번째 사용 가능한 글꼴의 em 상자의 상단으로 설정합니다.
    textBaselineideographic인 경우
    앵커 포인트의 수직 위치를 이데오그래픽 언더 기준선첫 번째 사용 가능한 글꼴의 em 상자의 상단으로 설정합니다.
    textBaselinebottom인 경우
    앵커 포인트의 수직 위치를 첫 번째 사용 가능한 글꼴의 em 상자의 하단으로 설정합니다.
  8. result는 가상의 인라인 박스 내의 각 글리프를 왼쪽에서 오른쪽으로 반복하며, 각각의 글리프를 CSS 픽셀 단위로 앵커 포인트에서 원점을 두고 좌표 공간에 배치된 상태로 배열에 추가합니다.

  9. result, 물리적 정렬, 그리고 인라인 박스를 반환합니다.

4.12.5.1.5 경로 구축

CanvasPath 인터페이스를 구현하는 객체는 경로를 가지고 있습니다. 경로는 0개 이상의 하위 경로 목록을 포함합니다. 각 하위 경로는 하나 이상의 점 목록으로 구성되며, 직선 또는 곡선 선분으로 연결되고, 하위 경로가 닫혀 있는지 여부를 나타내는 플래그가 있습니다. 닫힌 하위 경로는 하위 경로의 마지막 점이 직선으로 첫 번째 점에 연결된 것입니다. 점이 하나뿐인 하위 경로는 경로를 그릴 때 무시됩니다.

경로새 하위 경로 필요 플래그를 가지고 있습니다. 이 플래그가 설정되면 특정 API는 이전 경로를 확장하는 대신 새 하위 경로를 만듭니다. 경로가 생성될 때, 그 새 하위 경로 필요 플래그가 설정되어야 합니다.

CanvasPath 인터페이스를 구현하는 객체가 생성될 때, 그 경로는 0개의 하위 경로로 초기화되어야 합니다.

context.moveTo(x, y)

CanvasRenderingContext2D/moveTo

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.moveTo(x, y)

지정된 점으로 새 하위 경로를 만듭니다.

context.closePath()

CanvasRenderingContext2D/closePath

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.closePath()

현재 하위 경로를 닫히도록 표시하고, 닫힌 새 하위 경로와 동일한 시작점으로 새 하위 경로를 시작합니다.

context.lineTo(x, y)

CanvasRenderingContext2D/lineTo

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.lineTo(x, y)

지정된 점을 현재 하위 경로에 추가하며, 이전 점과 직선으로 연결합니다.

context.quadraticCurveTo(cpx, cpy, x, y)

CanvasRenderingContext2D/quadraticCurveTo

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari3+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.quadraticCurveTo(cpx, cpy, x, y)

지정된 제어점으로 연결된 곡선으로 현재 하위 경로에 지정된 점을 추가합니다.

context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

CanvasRenderingContext2D/bezierCurveTo

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

지정된 제어점으로 연결된 곡선으로 현재 하위 경로에 지정된 점을 추가합니다.

context.arcTo(x1, y1, x2, y2, radius)

CanvasRenderingContext2D/arcTo

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.arcTo(x1, y1, x2, y2, radius)

지정된 제어점과 반경으로 현재 하위 경로에 호를 추가하며, 이전 점과 직선으로 연결합니다.

주어진 반경이 음수인 경우, "IndexSizeError" DOMException을 던집니다.

context.arc(x, y, radius, startAngle, endAngle [, counterclockwise ])

CanvasRenderingContext2D/arc

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari3+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.arc(x, y, radius, startAngle, endAngle [, counterclockwise ])

지정된 시작 각도에서 끝 각도까지 주어진 방향(기본적으로 시계 방향)으로 주어진 원의 호를 그리며, 이전 점과 직선으로 연결하여 경로에 추가합니다.

주어진 반경이 음수인 경우, "IndexSizeError" DOMException을 던집니다.

context.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, counterclockwise])

CanvasRenderingContext2D/ellipse

모든 최신 엔진에서 지원됩니다.

Firefox48+ Safari9+ Chrome31+
Opera? Edge79+
Edge (Legacy)13+ Internet ExplorerNo
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?
path.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, counterclockwise])

지정된 시작 각도에서 끝 각도까지 주어진 방향(기본적으로 시계 방향)으로 주어진 타원의 호를 그리며, 이전 점과 직선으로 연결하여 경로에 추가합니다.

주어진 반경이 음수인 경우, "IndexSizeError" DOMException을 던집니다.

context.rect(x, y, w, h)

CanvasRenderingContext2D/rect

모든 최신 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera11.6+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
path.rect(x, y, w, h)

지정된 직사각형을 나타내는 새로운 닫힌 하위 경로를 경로에 추가합니다.

context.roundRect(x, y, w, h, radii)
path.roundRect(x, y, w, h, radii)

지정된 반경의 둥근 직사각형을 나타내는 새로운 닫힌 하위 경로를 경로에 추가합니다. radii는 반경 목록이거나 픽셀 단위로 직사각형의 모서리를 나타내는 단일 반경일 수 있습니다. 목록이 제공되면 이러한 반경의 수와 순서는 CSS 'border-radius' 속성과 동일한 방식으로 동작합니다. 단일 반경은 단일 요소가 있는 목록과 동일한 방식으로 동작합니다.

wh가 모두 0 이상이거나 둘 다 0 미만인 경우, 경로는 시계 방향으로 그려집니다. 그렇지 않으면 반시계 방향으로 그려집니다.

w가 음수일 때, 둥근 직사각형은 수평으로 뒤집히며, 일반적으로 왼쪽 모서리에 적용되는 반경 값이 오른쪽에 사용됩니다. 마찬가지로, h가 음수일 때, 둥근 직사각형은 수직으로 뒤집힙니다.

radii의 값이 숫자인 경우, 해당 모서리(들)는 반경 r의 원호로 그려집니다.

radii의 값이 { x, y } 속성이 있는 객체인 경우, 해당 모서리(들)는 각각 r.xr.y의 반경으로 타원호로 그려집니다.

동일한 모서리의 두 모서리 반경의 합이 모서리 길이보다 클 때, 모든 둥근 직사각형의 반경이 길이 / (r1 + r2) 비율로 스케일링됩니다. 여러 모서리가 이 속성을 가지고 있는 경우, 가장 작은 스케일 비율의 모서리가 사용됩니다. 이는 CSS 동작과 일치합니다.

목록의 크기가 1, 2, 3 또는 4가 아닌 radii의 경우, RangeError를 던집니다.

radii의 값이 음수인 경우 또는 { x, y } 객체의 x 또는 y 속성이 음수인 경우, RangeError를 던집니다.

다음 메서드는 CanvasPath 인터페이스를 구현하는 객체의 경로를 조작할 수 있게 해줍니다.

CanvasDrawPathCanvasTransform 인터페이스를 구현하는 객체의 경우, 이 메서드를 통해 전달된 점들과 이 메서드가 현재 기본 경로에 추가하는 결과 선은 경로에 추가되기 전에 현재 변환 행렬에 따라 변환되어야 합니다.

moveTo(x, y) 메서드가 호출될 때, 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN이면 반환합니다.

  2. 지정된 점을 첫 번째(및 유일한) 점으로 하는 새로운 하위 경로를 생성합니다.

사용자 에이전트가 하위 경로를 보장하기 위해 경로에서 좌표 (x, y)를 확인할 때, 새 하위 경로 필요 플래그가 설정되어 있는지 확인해야 합니다. 설정되어 있으면, moveTo() 메서드가 호출된 것처럼 점 (x, y)을 첫 번째(및 유일한) 점으로 하여 새로운 하위 경로를 생성하고, 새 하위 경로 필요 플래그를 해제해야 합니다.

closePath() 메서드가 호출될 때, 객체의 경로에 하위 경로가 없으면 아무 작업도 수행하지 않아야 합니다. 그렇지 않으면, 마지막 하위 경로를 닫힌 것으로 표시하고, 이전 하위 경로의 첫 번째 점과 동일한 점을 첫 번째 점으로 하는 새 하위 경로를 생성한 다음, 이 새 하위 경로를 경로에 추가해야 합니다.

마지막 하위 경로에 여러 점이 있는 경우, 이는 마지막 점을 마지막 하위 경로의 첫 번째 점으로 연결하는 직선을 추가하여 하위 경로를 "닫는" 것과 같습니다.


새 점과 그 점을 연결하는 선은 아래 설명된 메서드를 사용하여 하위 경로에 추가됩니다. 모든 경우에 이 메서드는 객체의 경로에서 마지막 하위 경로만 수정합니다.

lineTo(x, y) 메서드가 호출될 때, 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN이면 반환합니다.

  2. 객체의 경로에 하위 경로가 없으면 하위 경로가 보장되도록 합니다 (x, y).

  3. 그렇지 않으면, 하위 경로의 마지막 점을 지정된 점 (x, y)에 직선으로 연결한 다음, 지정된 점 (x, y)을 하위 경로에 추가합니다.

quadraticCurveTo(cpx, cpy, x, y) 메서드가 호출될 때, 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN이면 반환합니다.

  2. 하위 경로가 보장되도록 합니다 (cpx, cpy)

  3. 하위 경로의 마지막 점을 지정된 점 (x, y)에 제어점 (cpx, cpy)을 사용하여 이차 베지어 곡선으로 연결합니다. [BEZIER]

  4. 지정된 점 (x, y)을 하위 경로에 추가합니다.

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) 메서드가 호출될 때, 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN이면 반환합니다.

  2. 하위 경로가 보장되도록 합니다 (cp1x, cp1y).

  3. 하위 경로의 마지막 점을 지정된 점 (x, y)에 제어점 (cp1x, cp1y) 및 (cp2x, cp2y)을 사용하여 삼차 베지어 곡선으로 연결합니다. [BEZIER]

  4. 지정된 점 (x, y)을 하위 경로에 추가합니다.


arcTo(x1, y1, x2, y2, radius) 메서드가 호출될 때, 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN이면 반환합니다.

  2. 하위 경로가 보장되도록 합니다 (x1, y1).

  3. radius가 음수이면 "IndexSizeError" DOMException을 던집니다.

  4. 점 (x0, y0)을 현재 변환 행렬의 역행렬로 변환한 하위 경로의 마지막 점으로 설정합니다(이렇게 하면 메서드에 전달된 점과 동일한 좌표계에 있게 됩니다).

  5. 점 (x0, y0)이 점 (x1, y1)과 같거나, 점 (x1, y1)이 점 (x2, y2)과 같거나, radius가 0이면 점 (x1, y1)을 하위 경로에 추가하고, 그 점을 이전 점 (x0, y0)과 직선으로 연결합니다.

  6. 그렇지 않으면, 점 (x0, y0), (x1, y1), 및 (x2, y2)이 모두 하나의 직선에 놓여 있으면, 점 (x1, y1)을 하위 경로에 추가하고, 그 점을 이전 점 (x0, y0)과 직선으로 연결합니다.

  7. 그렇지 않으면, The Arcradius가 있는 원의 둘레가 제공하는 가장 짧은 호로 설정합니다. 이 호는 점 (x0, y0)에서 시작하여 점 (x1, y1)에서 끝나는 반무한 직선에 접하는 한 점과, 점 (x1, y1)에서 시작하여 점 (x2, y2)에서 끝나는 반무한 직선에 접하는 다른 점을 가집니다. 이 원이 이 두 직선과 접하는 점을 각각 시작 접선점과 끝 접선점이라고 합니다. 점 (x0, y0)을 시작 접선점에 직선으로 연결하고, 시작 접선점을 하위 경로에 추가한 다음, 시작 접선점을 The Arc로 끝 접선점에 연결하고, 끝 접선점을 하위 경로에 추가합니다.


arc(x, y, radius, startAngle, endAngle, counterclockwise) 메서드는 호출되면, ellipse 메서드 steps와 함께 this, x, y, radius, radius, 0, startAngle, endAngle, 그리고 counterclockwise를 실행해야 합니다.

이는 두 반지름이 같고 rotation이 0인 경우 ellipse()과 동등합니다.

ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise) 메서드는 호출되면, ellipse 메서드 steps와 함께 this, x, y, radiusX, radiusY, rotation, startAngle, endAngle, 그리고 counterclockwise를 실행해야 합니다.

ellipse에서 점을 결정하는 단계, 주어진 ellipseangle은 다음과 같습니다:

  1. eccentricCircleellipse와 동일한 원점에 반지름이 ellipse의 반장축과 같은 원으로 정의합니다.

  2. outerPointangle에서 ellipse의 반장축에서 시계 방향으로 라디안 단위로 측정된 eccentricCircle의 원주상의 점으로 정의합니다.

  3. chordellipse의 주축에 수직인 선으로, 이 축과 outerPoint 사이의 선으로 정의합니다.

  4. chordellipse의 원주를 가로지르는 지점을 반환합니다.

ellipse 메서드 steps, 주어진 canvasPath, x, y, radiusX, radiusY, rotation, startAngle, endAngle, 그리고 counterclockwise는 다음과 같습니다:

  1. 인자가 무한대이거나 NaN이면, return 합니다.

  2. radiusX 또는 radiusY가 음수인 경우, "IndexSizeError" DOMException를 throw 합니다.

  3. canvasPath의 경로에 하위 경로가 있는 경우, 하위 경로의 마지막 점에서 호의 시작점까지 직선을 추가합니다.

  4. 호의 시작점과 끝점을 하위 경로에 추가하고, 그것들을 호로 연결합니다. 호와 그 시작점 및 끝점은 다음과 같이 정의됩니다:

    x, y에 원점을 둔 타원은 주축 반지름 radiusX와 소축 반지름 radiusY를 가지며, 원점을 기준으로 시계 방향으로 x축에서 rotation 라디안 회전한 상태로 가정합니다.

    counterclockwise가 false이고 endAnglestartAngle 이상이거나, counterclockwise가 true이고 startAngleendAngle 이상인 경우, 호는 이 타원의 전체 원주이며, 시작점과 끝점은 모두 ellipse에서 점을 결정하는 단계를 실행하여 얻은 startAngle입니다.

    그렇지 않은 경우, 시작점은 ellipse에서 점을 결정하는 단계를 통해 얻은 startAngle이고, 끝점은 ellipse에서 점을 결정하는 단계를 통해 얻은 endAngle이며, 호는 counterclockwise가 true이면 반시계 방향으로, 그렇지 않으면 시계 방향으로 진행됩니다. 점들이 타원 위에 있으므로, 호는 라디안을 넘는 각도를 가질 수 없습니다.

    호가 타원의 전체 원주를 커버하고 하위 경로에 다른 점이 없는 경우에도, closePath() 메서드가 적절히 호출되지 않으면 경로가 닫히지 않습니다.


rect(x, y, w, h) 메서드는 호출되면, 다음 단계를 실행해야 합니다:

  1. 인자가 무한대이거나 NaN이면, return 합니다.

  2. 새 하위 경로를 생성하여, 네 개의 점 (x, y), (x+w, y), (x+w, y+h), (x, y+h)만 포함하고, 이 점들을 직선으로 연결합니다.

  3. 하위 경로를 닫힌 상태로 표시합니다.

  4. 하위 경로에 (x, y) 점만 포함하는 새 하위 경로를 생성합니다.

CanvasRenderingContext2D/roundRect

현재 모든 엔진에서 지원됩니다.

Firefox112+ Safari16+ Chrome99+
Opera? Edge99+
Edge (Legacy)? Internet Explorer지원 안 함
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

roundRect(x, y, w, h, radii) 메서드의 단계는 다음과 같습니다:

  1. x, y, w, 또는 h가 무한대이거나 NaN인 경우, return 합니다.

  2. radiiunrestricted double이거나 DOMPointInit인 경우, radii를 « radii »로 설정합니다.

  3. radii의 크기가 1, 2, 3, 또는 4가 아닌 경우, RangeError를 throw 합니다.

  4. normalizedRadii를 빈 리스트로 설정합니다.

  5. radii의 각 radius에 대해:

    1. radiusDOMPointInit인 경우:

      1. radius["x"] 또는 radius["y"] 가 무한대이거나 NaN이면, return 합니다.

      2. radius["x"] 또는 radius["y"] 가 음수인 경우, RangeError를 throw 합니다.

      3. 그 외의 경우, radiusnormalizedRadii에 추가합니다.

    2. radius unrestricted double인 경우:

      1. radius가 무한대이거나 NaN인 경우, return 합니다.

      2. radius가 음수인 경우, RangeError를 throw 합니다.

      3. 그 외의 경우, «[ "x" → radius, "y" → radius ]»를 normalizedRadii에 추가합니다.

  6. upperLeft, upperRight, lowerRight, 및 lowerLeft를 null로 설정합니다.

  7. normalizedRadii의 크기가 4인 경우, upperLeftnormalizedRadii[0]으로 설정하고, upperRightnormalizedRadii[1]으로 설정하고, lowerRightnormalizedRadii[2]로 설정하고, lowerLeftnormalizedRadii[3]으로 설정합니다.

  8. normalizedRadii의 크기가 3인 경우, upperLeftnormalizedRadii[0]으로 설정하고, upperRightlowerLeftnormalizedRadii[1]로 설정하고, lowerRightnormalizedRadii[2]로 설정합니다.

  9. normalizedRadii의 크기가 2인 경우, upperLeftlowerRightnormalizedRadii[0]으로 설정하고, upperRightlowerLeftnormalizedRadii[1]로 설정합니다.

  10. normalizedRadii의 크기가 1인 경우, upperLeft, upperRight, lowerRight, 및 lowerLeftnormalizedRadii[0]으로 설정합니다.

  11. 코너 곡선이 겹치지 않아야 합니다. 이를 방지하기 위해 모든 반지름을 스케일합니다:

    1. topupperLeft["x"] + upperRight["x"]로 설정합니다.

    2. rightupperRight["y"] + lowerRight["y"]로 설정합니다.

    3. bottomlowerRight["x"] + lowerLeft["x"]로 설정합니다.

    4. leftupperLeft["y"] + lowerLeft["y"]로 설정합니다.

    5. scale을 비율 w / top, h / right, w / bottom, h / left 중 최소값으로 설정합니다.

    6. scale이 1보다 작으면, xy 멤버의 값을 현재 값에 scale을 곱하여 upperLeft, upperRight, lowerLeft, 및 lowerRight에 설정합니다.

  12. 새 하위 경로를 생성합니다:

    1. 점 (x + upperLeft["x"], y)로 이동합니다.

    2. 점 (x + wupperRight["x"], y)까지 직선을 그립니다.

    3. 점 (x + w, y + upperRight["y"])로 호를 그립니다.

    4. 점 (x + w, y + hlowerRight["y"])까지 직선을 그립니다.

    5. 점 (x + wlowerRight["x"], y + h)까지 호를 그립니다.

    6. 점 (x + lowerLeft["x"], y + h)까지 직선을 그립니다.

    7. 점 (x, y + hlowerLeft["y"])로 호를 그립니다.

    8. 점 (x, y + upperLeft["y"])까지 직선을 그립니다.

    9. 점 (x + upperLeft["x"], y)로 호를 그립니다.

  13. 하위 경로를 닫힌 상태로 표시합니다.

  14. 하위 경로에 (x, y) 점만 포함하는 새 하위 경로를 생성합니다.

이것은 CSS의 'border-radius' 속성과 유사하게 동작하도록 설계되었습니다.

4.12.5.1.6 Path2D 객체

Path2D

모든 현재 엔진에서 지원.

Firefox31+Safari8+Chrome36+
Opera?Edge79+
Edge (Legacy)14+Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Path2D 객체는 경로를 선언하는 데 사용되며, 나중에 CanvasDrawPath 인터페이스를 구현하는 객체에서 사용됩니다. 앞에서 설명한 많은 API들 외에도 Path2D 객체에는 경로를 결합하고 경로에 텍스트를 추가하는 메서드가 있습니다.

path = new Path2D()

Path2D/Path2D

모든 현재 엔진에서 지원.

Firefox31+Safari8+Chrome36+
Opera?Edge79+
Edge (Legacy)14+Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

새로운 빈 Path2D 객체를 생성합니다.

path = new Path2D(path)

pathPath2D 객체인 경우, 복사본을 반환합니다.

path가 문자열인 경우, 인수로 전달된 경로를 SVG 경로 데이터로 해석하여 생성합니다. [SVG]

path.addPath(path [, transform ])

Path2D/addPath

모든 현재 엔진에서 지원.

Firefox34+Safari9+Chrome68+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

인수로 전달된 경로를 추가합니다.

Path2D(path) 생성자는, 호출될 때, 다음 단계를 실행해야 합니다:

  1. output이라는 새 Path2D 객체를 생성합니다.

  2. path가 주어지지 않으면, output을 반환합니다.

  3. pathPath2D 객체인 경우, path의 모든 하위 경로를 output에 추가하고 output을 반환합니다. (즉, 전달된 인수의 복사본을 반환합니다.)

  4. svgPathpath에 따라 해석하고 SVG 2의 경로 데이터 규칙에 따라 파싱한 결과로 설정합니다. [SVG]

    결과 경로는 비어 있을 수 있습니다. SVG는 경로 데이터를 파싱하고 적용하는 규칙을 정의합니다.

  5. svgPath에서 마지막 점(x, y)을 가져옵니다.

  6. 경로가 있다면, svgPath의 모든 하위 경로를 output에 추가합니다.

  7. 새 하위 경로를 output에 생성하고, 그 하위 경로의 유일한 점으로 (x, y)를 설정합니다.

  8. output을 반환합니다.


addPath(path, transform) 메서드는, Path2D 객체 a에서 호출될 때, 다음 단계를 실행해야 합니다:

  1. Path2D 객체 path 에 하위 경로가 없으면, 반환합니다.

  2. matrix2D 사전에서 DOMMatrix 생성하기 의 결과로 설정합니다. transform.

  3. matrixm11 요소, m12 요소, m21 요소, m22 요소, m41 요소, 또는 m42 요소 중 하나 이상이 무한대이거나 NaN이면, 반환합니다.

  4. path에 있는 모든 하위 경로의 복사본을 생성합니다. 이 복사본을 c라고 합니다.

  5. c에 있는 모든 좌표와 선을 변환 행렬 matrix로 변환합니다.

  6. c의 마지막 하위 경로에서 마지막 점(x, y)을 가져옵니다.

  7. c의 모든 하위 경로를 a에 추가합니다.

  8. 새 하위 경로를 a에 생성하고, 그 하위 경로의 유일한 점으로 (x, y)를 설정합니다.

4.12.5.1.7 변환

CanvasTransform 인터페이스를 구현하는 객체는 현재 변환 행렬과 이를 조작하기 위한 메서드(이 섹션에서 설명)를 가지고 있습니다. CanvasTransform 인터페이스를 구현하는 객체가 생성될 때, 그 변환 행렬은 항등 행렬로 초기화되어야 합니다.

현재 변환 행렬현재 기본 경로를 생성할 때, 그리고 Path2D 객체와 텍스트, 도형을 페인팅할 때 적용됩니다. 이러한 객체들은 CanvasTransform 인터페이스를 구현합니다.

변환은 역순으로 수행되어야 합니다.

예를 들어, 너비를 두 배로 하는 스케일 변환이 캔버스에 적용된 후, 그리기 작업이 1/4 회전하는 회전 변환이 뒤따른다면, 두 배의 너비와 높이를 가지는 사각형을 캔버스에 그리면 실제 결과는 정사각형이 됩니다.

context.scale(x, y)

CanvasRenderingContext2D/scale

모든 최신 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 변환 행렬을 주어진 특성으로 스케일 변환을 적용하도록 변경합니다.

context.rotate(angle)

CanvasRenderingContext2D/rotate

모든 최신 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 변환 행렬을 주어진 특성으로 회전 변환을 적용하도록 변경합니다. 각도는 라디안 단위입니다.

context.translate(x, y)

CanvasRenderingContext2D/translate

모든 최신 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 변환 행렬을 주어진 특성으로 번역 변환을 적용하도록 변경합니다.

context.transform(a, b, c, d, e, f)

CanvasRenderingContext2D/transform

모든 최신 엔진에서 지원됩니다.

Firefox3+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 변환 행렬을 주어진 특성으로 변경합니다.

matrix = context.getTransform()

CanvasRenderingContext2D/getTransform

모든 최신 엔진에서 지원됩니다.

Firefox70+Safari11.1+Chrome68+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 변환 행렬의 복사본을 새로 생성된 DOMMatrix 객체로 반환합니다.

context.setTransform(a, b, c, d, e, f)

CanvasRenderingContext2D/setTransform

모든 최신 엔진에서 지원됩니다.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

현재 변환 행렬을 아래에서 설명한 대로 인수로 지정된 행렬로 변경합니다.

context.setTransform(transform)

현재 변환 행렬을 전달된 DOMMatrix2DInit 사전으로 표현된 행렬로 변경합니다.

context.resetTransform()

CanvasRenderingContext2D/resetTransform

모든 최신 엔진에서 지원됩니다.

Firefox36+Safari10.1+Chrome31+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 변환 행렬을 항등 행렬로 변경합니다.

scale(x, y) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. 인수로 설명된 스케일 변환을 현재 변환 행렬에 추가합니다. x 인수는 수평 방향의 스케일 계수를 나타내고, y 인수는 수직 방향의 스케일 계수를 나타냅니다. 계수는 배수입니다.

rotate(angle) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. angle이 무한대이거나 NaN인 경우, 반환합니다.

  2. 인수로 설명된 회전 변환을 현재 변환 행렬에 추가합니다. angle 인수는 라디안 단위로 표현된 시계 방향 회전 각도를 나타냅니다.

translate(x, y) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. 인수로 설명된 번역 변환을 현재 변환 행렬에 추가합니다. x 인수는 수평 방향의 번역 거리를 나타내고, y 인수는 수직 방향의 번역 거리를 나타냅니다. 인수는 좌표 공간 단위로 표현됩니다.

transform(a, b, c, d, e, f) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. 현재 변환 행렬을 다음과 같은 방법으로 인수로 설명된 행렬로 교체합니다:

    a c e
    b d f
    0 0 1

인수 a, b, c, d, e, f는 때때로 m11, m12, m21, m22, dx, dy 또는 m11, m21, m12, m22, dx, dy로 불립니다. 특히 두 번째와 세 번째 인수(bc)의 순서에 주의해야 하며, API마다 순서가 다르기 때문에, API에서 때때로 m12/m21 또는 m21/m12를 사용합니다.

getTransform() 메서드가 호출되면, 컨텍스트의 현재 변환 행렬의 복사본을 새로 생성된 DOMMatrix 객체로 반환해야 합니다.

이 반환된 객체는 실시간이 아니므로, 이를 업데이트해도 현재 변환 행렬에 영향을 미치지 않으며, 현재 변환 행렬을 업데이트해도 이미 반환된 DOMMatrix에 영향을 미치지 않습니다.

setTransform(a, b, c, d, e, f) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. 현재 변환 행렬을 아래와 같이 설명된 행렬로 재설정합니다:

    a c e
    b d f
    0 0 1

setTransform(transform) 메서드가 호출되면 다음 단계를 실행해야 합니다:

  1. 2D 사전에서 DOMMatrix를 생성하여 transform의 결과로 matrix를 생성합니다.

  2. matrixm11 요소, m12 요소, m21 요소, m22 요소, m41 요소, m42 요소 중 하나 이상이 무한대이거나 NaN인 경우, 반환합니다.

  3. 현재 변환 행렬matrix로 재설정합니다.

resetTransform() 메서드가 호출되면 현재 변환 행렬을 항등 행렬로 재설정해야 합니다.

transform()setTransform() 메서드로 생성된 행렬의 형식을 고려하면,

a c e
b d f
0 0 1

변환 행렬 곱셈 후에 변환된 결과 좌표는 다음과 같습니다:

xnew = a x + c y + e
ynew = b x + d y + f

4.12.5.1.8 2D 렌더링 컨텍스트용 이미지 소스

일부 CanvasDrawImageCanvasFillStrokeStyles 인터페이스의 메서드는 CanvasImageSource 유니온 타입을 인수로 사용합니다.

이 유니온 타입은 다음 인터페이스를 구현하는 객체를 이미지 소스로 사용할 수 있도록 허용합니다:

정식으로 명시된 것은 아니지만, SVG image 요소는 img 요소와 거의 동일하게 구현될 것으로 예상됩니다. 즉, SVG image 요소는 img 요소와 기본 개념과 기능을 공유합니다.

ImageBitmap 인터페이스는 ImageData를 포함한 여러 이미지 표현 타입에서 생성할 수 있습니다.

image 인수의 사용 가능 여부를 확인하려면, imageCanvasImageSource 객체인 경우 다음 단계를 실행합니다:

  1. image에 따라 전환합니다:

    HTMLOrSVGImageElement
    image현재 요청상태손상됨 상태라면, "InvalidStateError" DOMException을 발생시킵니다.
    image완전히 디코딩 가능하지 않다면, bad를 반환합니다.
    image자연 너비 또는 자연 높이(또는 둘 다)가 0이라면 bad를 반환합니다.
    HTMLVideoElement
    imagereadyState 속성이 HAVE_NOTHING 또는 HAVE_METADATA라면, bad를 반환합니다.
    HTMLCanvasElement
    OffscreenCanvas
    image가 가로 또는 세로 크기 중 하나가 0이면 "InvalidStateError" DOMException을 발생시킵니다.
    ImageBitmap
    VideoFrame
    image[[Detached]] 내부 슬롯 값이 true로 설정되어 있으면 "InvalidStateError" DOMException을 발생시킵니다.
  2. good을 반환합니다.

CanvasImageSource 객체가 HTMLOrSVGImageElement을 나타내는 경우, 요소의 이미지는 소스 이미지로 사용됩니다.

특히, CanvasImageSource 객체가 HTMLOrSVGImageElement에서 애니메이션 이미지를 나타내는 경우, 사용자 에이전트는 애니메이션을 지원하지 않거나 비활성화된 경우 사용하기로 정의된 기본 이미지를 사용하거나, 그러한 이미지가 없으면, CanvasRenderingContext2D API를 사용하여 이미지를 렌더링할 때 애니메이션의 첫 번째 프레임을 사용해야 합니다.

CanvasImageSource 객체가 HTMLVideoElement을 나타내는 경우, 해당 인수로 메서드를 호출할 때 현재 재생 위치의 프레임이 CanvasRenderingContext2D API를 사용하여 이미지를 렌더링할 때 소스 이미지로 사용되며, 소스 이미지의 크기는 자연 너비자연 높이여야 합니다.

CanvasImageSource 객체가 HTMLCanvasElement을 나타내는 경우, 요소의 비트맵이 소스 이미지로 사용됩니다.

CanvasImageSource 객체가 렌더링 중인 요소를 나타내며 해당 요소가 크기 조정된 경우, 소스 이미지의 원본 이미지 데이터가 사용되어야 하며, 렌더링된 이미지가 아닌 소스 요소의 너비높이 속성은 CanvasRenderingContext2D API를 사용하여 이미지를 렌더링할 때 해당 객체를 해석하는 방식에 영향을 주지 않습니다.

CanvasImageSource 객체가 ImageBitmap을 나타내는 경우, 객체의 비트맵 이미지 데이터가 소스 이미지로 사용되어야 합니다.

CanvasImageSource 객체가 OffscreenCanvas을 나타내는 경우, 객체의 비트맵이 소스 이미지로 사용되어야 합니다.

CanvasImageSource 객체가 VideoFrame을 나타내는 경우, 객체의 픽셀 데이터가 소스 이미지로 사용되어야 하며, 소스 이미지의 크기는 객체의 [[display width]][[display height]]이어야 합니다.

image 객체가 원본이 깨끗하지 않은 경우 image 유형에 따라 전환합니다:

HTMLOrSVGImageElement
image현재 요청이미지 데이터CORS-교차 출처입니다.
HTMLVideoElement
image미디어 데이터CORS-교차 출처입니다.
HTMLCanvasElement
ImageBitmap
OffscreenCanvas
image의 비트맵의 원본-깨끗함 플래그가 false입니다.
4.12.5.1.9 채우기 및 스트로크 스타일
context.fillStyle [ = value ]

CanvasRenderingContext2D/fillStyle

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

도형을 채우는 데 사용되는 현재 스타일을 반환합니다.

설정 가능하며, 채우기 스타일을 변경할 수 있습니다.

스타일은 CSS 색상을 포함하는 문자열이거나 CanvasGradient 또는 CanvasPattern 객체일 수 있습니다. 잘못된 값은 무시됩니다.

context.strokeStyle [ = value ]

CanvasRenderingContext2D/strokeStyle

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

도형의 외곽선을 그리는 데 사용되는 현재 스타일을 반환합니다.

설정 가능하며, 외곽선 스타일을 변경할 수 있습니다.

스타일은 CSS 색상을 포함하는 문자열이거나 CanvasGradient 또는 CanvasPattern 객체일 수 있습니다. 잘못된 값은 무시됩니다.

CanvasFillStrokeStyles 인터페이스를 구현하는 객체는 도형이 객체에 의해 처리되는 방법을 제어하는 속성과 메서드를 가지고 있습니다.

이러한 객체에는 CSS 색상, CanvasPattern 또는 CanvasGradient 값을 갖는 연관된 채우기 스타일외곽선 스타일 값이 있습니다. 초기에는 둘 다 문자열 "#000000"를 파싱한 결과여야 합니다.

값이 CSS 색상인 경우 비트맵에 그릴 때 변환 행렬의 영향을 받아서는 안 됩니다.

CanvasPattern 또는 CanvasGradient 객체로 설정된 경우, 할당 후 객체에 대한 변경 사항은 이후 도형의 외곽선이나 채우기에 영향을 미칩니다.

fillStyle getter 단계는 다음과 같습니다:

  1. this채우기 스타일이 CSS 색상인 경우, 해당 색상의 직렬화를 반환합니다.

  2. this채우기 스타일을 반환합니다.

fillStyle setter 단계는 다음과 같습니다:

  1. 지정된 값이 문자열인 경우:

    1. contextthiscanvas 속성 값이 요소일 때의 값이며, 그렇지 않으면 null입니다.

    2. parsedValue파싱 결과로 context가 null이 아니면 주어진 값으로 설정됩니다.

    3. parsedValue가 실패하면 반환합니다.

    4. this채우기 스타일parsedValue로 설정합니다.

    5. 반환합니다.

  2. 지정된 값이 CanvasPattern 객체이고 기원이 청정하지 않음으로 표시된 경우, this기원 청정 플래그를 false로 설정합니다.

  3. this채우기 스타일을 지정된 값으로 설정합니다.

strokeStyle getter 단계는 다음과 같습니다:

  1. this외곽선 스타일이 CSS 색상인 경우, 해당 색상의 직렬화를 반환합니다.

  2. this외곽선 스타일을 반환합니다.

strokeStyle setter 단계는 다음과 같습니다:

  1. 지정된 값이 문자열인 경우:

    1. contextthiscanvas 속성 값이 요소일 때의 값이며, 그렇지 않으면 null입니다.

    2. parsedValue파싱 결과로 context가 null이 아니면 주어진 값으로 설정됩니다.

    3. parsedValue가 실패하면 반환합니다.

    4. this외곽선 스타일parsedValue로 설정합니다.

    5. 반환합니다.

  2. 지정된 값이 CanvasPattern 객체이고 기원이 청정하지 않음으로 표시된 경우, this기원 청정 플래그를 false로 설정합니다.

  3. this외곽선 스타일을 지정된 값으로 설정합니다.

색상의 직렬화는 색상 값에 대한 문자열이며, 다음과 같이 계산됩니다: 알파가 1.0이면 문자열은 "#" 문자(U+0023 숫자 기호)가 접두사로 붙는 소문자 6자리 16진수 값입니다. 처음 두 자리는 빨간색 구성 요소를 나타내고, 다음 두 자리는 녹색 구성 요소를 나타내며, 마지막 두 자리는 파란색 구성 요소를 나타내며, 이 숫자들은 ASCII 소문자 16진수입니다. 그렇지 않으면 색상 값의 알파가 1.0보다 작고 문자열은 CSS rgba() 기능 표기법 형식으로 표현됩니다: "rgba"(U+0072 U+0067 U+0062 U+0061) 뒤에 U+0028 왼쪽 괄호가 오고, 빨간색 구성 요소를 나타내는 0-255 범위의 10진수 정수(가장 짧은 형식의 ASCII 숫자를 사용)가 오며, 문자 그대로의 U+002C 쉼표와 U+0020 공백이 오고, 녹색 구성 요소를 나타내는 정수, 쉼표와 공백, 파란색 구성 요소를 나타내는 정수, 또 다른 쉼표와 공백, U+0030 숫자 0, 알파 값이 0보다 크면 U+002E 온점(소수점), 알파 값이 0보다 크면 하나 이상의 ASCII 숫자가 오며, 마지막으로 U+0029 오른쪽 괄호가 옵니다. 사용자 에이전트는 알파 값을 다시 파싱할 때 동일한 알파 값으로 해석될 수 있도록 필요한 수준의 정밀도로 알파 값의 소수 부분을 표현해야 합니다.


그라데이션은 선형 그라데이션, 방사형 그라데이션 및 원뿔형 그라데이션의 세 가지 유형이 있으며, 불투명 CanvasGradient 인터페이스를 구현하는 객체로 표현됩니다.

그라데이션이 생성된 후(아래 참조), 그라데이션을 따라 색상이 분포되는 방식을 정의하기 위해 스톱이 배치됩니다. 각 스톱에서의 그라데이션 색상은 해당 스톱에 대해 지정된 색상입니다. 각 스톱 사이에서 색상과 알파 구성 요소는 알파 값을 미리 곱하지 않고 RGBA 공간에서 선형 보간되어 해당 오프셋에서 사용할 색상을 찾습니다. 첫 번째 스톱 이전에는 색상이 첫 번째 스톱의 색상이 되어야 합니다. 마지막 스톱 이후에는 색상이 마지막 스톱의 색상이 되어야 합니다. 스톱이 없을 때 그라데이션은 투명한 검정색입니다.

gradient.addColorStop(offset, color)

CanvasGradient/addColorStop

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

지정된 색상을 주어진 오프셋의 그라데이션에 색상 스톱으로 추가합니다. 0.0은 그라데이션의 한쪽 끝의 오프셋이고, 1.0은 반대쪽 끝의 오프셋입니다.

"IndexSizeError" DOMException 예외가 오프셋이 범위를 벗어나는 경우 던져집니다. "SyntaxError" DOMException 예외는 색상을 구문 분석할 수 없는 경우 던져집니다.

gradient = context.createLinearGradient(x0, y0, x1, y1)

CanvasRenderingContext2D/createLinearGradient

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

주어진 좌표로 표현된 선을 따라 페인팅하는 선형 그라데이션을 나타내는 CanvasGradient 객체를 반환합니다.

gradient = context.createRadialGradient(x0, y0, r0, x1, y1, r1)

CanvasRenderingContext2D/createRadialGradient

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

주어진 좌표로 표현된 두 원 사이의 원뿔을 따라 페인팅하는 방사형 그라데이션을 나타내는 CanvasGradient 객체를 반환합니다.

반지름 중 하나라도 음수인 경우, "IndexSizeError" DOMException 예외를 던집니다.

gradient = context.createConicGradient(startAngle, x, y)

CanvasRenderingContext2D/createConicGradient

모든 현재 엔진에서 지원됩니다.

Firefox112+Safari16.1+Chrome99+
Opera?Edge99+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

주어진 좌표의 중심을 기준으로 시계 방향으로 페인팅하는 원뿔형 그라데이션을 나타내는 CanvasGradient 객체를 반환합니다.

addColorStop(offset, color) 메서드는 CanvasGradient 객체에 호출될 때 다음 단계를 수행해야 합니다:

  1. offset이 0보다 작거나 1보다 크면 "IndexSizeError" DOMException 예외를 던집니다.

  2. parsed color파싱 color의 결과로 얻어집니다.

    CanvasGradient 객체는 캔버스와 무관하기 때문에 파서에 요소가 전달되지 않습니다 — 하나의 CanvasGradient 객체가 다른 캔버스에서 사용될 수 있으며, 색상이 지정될 때 "문제의 요소"가 무엇인지 알 수 있는 방법이 없습니다.

  3. parsed color가 실패하면 "SyntaxError" DOMException 예외를 던집니다.

  4. 그라데이션의 전체에 대해 offset에 새로운 스톱을 배치하고, 색상 parsed color를 사용합니다.

    하나의 그라데이션에 여러 스톱이 동일한 오프셋에 추가된 경우, 첫 번째 스톱이 그라데이션의 시작 부분에 가장 가깝게 배치되어야 하며, 각 후속 스톱은 점점 더 끝 점에 가깝게 배치되어야 합니다(사실상 각 지점에서 추가된 첫 번째와 마지막 스톱만 제외하고 무시됩니다).

createLinearGradient(x0, y0, x1, y1) 메서드는 시작점(x0, y0)과 종료점(x1, y1)을 나타내는 네 개의 인수를 사용합니다. 메서드는 호출될 때, 지정된 선으로 초기화된 선형 CanvasGradient 객체를 반환해야 합니다.

선형 그라데이션은 시작점과 종료점이 교차하는 선에 수직인 선의 모든 점이 그 지점에서 두 선이 교차하는 지점의 색상을 갖도록 렌더링되어야 합니다(색상은 보간 및 외삽에서 설명된 대로 옵니다). 선형 그라데이션의 점은 렌더링할 때 현재 변환 행렬에 의해 설명된 대로 변환되어야 합니다.

x0 = x1이고 y0 = y1인 경우, 선형 그라데이션은 아무 것도 페인팅하지 않아야 합니다.

createRadialGradient(x0, y0, r0, x1, y1, r1) 메서드는 여섯 개의 인수를 사용합니다. 처음 세 개는 원점(x0, y0)과 반지름 r0을 갖는 시작 원을 나타내며, 마지막 세 개는 원점(x1, y1)과 반지름 r1을 갖는 종료 원을 나타냅니다. 값은 좌표 공간 단위입니다. r0 또는 r1 중 하나라도 음수인 경우, "IndexSizeError" DOMException 예외가 던져져야 합니다. 그렇지 않으면, 메서드는 호출될 때, 두 지정된 원으로 초기화된 방사형 CanvasGradient 객체를 반환해야 합니다.

방사형 그라데이션은 다음 단계를 따르며 렌더링되어야 합니다:

  1. x0 = x1이고 y0 = y1이고 r0 = r1인 경우, 방사형 그라데이션은 아무 것도 페인팅하지 않아야 합니다. 반환합니다.

  2. 다음과 같이 합니다: x(ω) = (x1-x0)ω + x0

    다음과 같이 합니다: y(ω) = (y1-y0)ω + y0

    다음과 같이 합니다: r(ω) = (r1-r0)ω + r0

    ω에서의 색상은 그라데이션의 해당 위치에서의 색상입니다 (색상은 보간 및 외삽에서 설명된 대로 옵니다).

  3. r(ω) > 0ω 값에 대해, 양의 무한대에 가장 가까운 ω 값부터 시작하여 음의 무한대에 가장 가까운 ω 값으로 끝나는 동안, 이전 원들에 의해 아직 페인팅되지 않은 비트맵의 부분에 대해서만 해당 원의 원주를 그립니다.

이는 효과적으로 두 원으로 정의된 그라데이션의 원뿔을 생성하며, 원뿔의 시작 원(0.0) 이전 부분은 첫 번째 오프셋의 색상을 사용하고, 종료 원(1.0) 이후 부분은 마지막 오프셋의 색상을 사용하며, 그라데이션 외부의 영역은 그라데이션에 의해 터치되지 않습니다(투명한 검정색).

그라데이션은 렌더링 시 현재 변환 행렬에 의해 설명된 대로 변환되어야 합니다.

createConicGradient(startAngle, x, y) 메서드는 세 개의 인수를 사용합니다. 첫 번째 인수인 startAngle은 그라데이션이 시작되는 라디안 단위의 각도를 나타내고, 마지막 두 개의 인수(x, y)는 CSS 픽셀에서 그라데이션의 중심을 나타냅니다. 메서드는 호출될 때, 지정된 중심과 각도로 초기화된 원뿔형 CanvasGradient 객체를 반환해야 합니다.

이는 CSS 'conic-gradient'와 동일한 렌더링 규칙을 따르며, CSS 'conic-gradient(from adjustedStartAnglerad at xpx ypx, angularColorStopList)'와 동일합니다. 여기서:

그라데이션은 관련된 외곽선 또는 채우기 효과가 그라데이션을 그릴 것을 요구하는 경우에만 그려야 합니다.


패턴은 불투명 CanvasPattern 인터페이스를 구현하는 객체로 표현됩니다.

pattern = context.createPattern(image, repetition)

CanvasRenderingContext2D/createPattern

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

주어진 이미지와 repetition 인수에 따라 지정된 방향으로 반복되는 CanvasPattern 객체를 반환합니다.

repetition의 허용된 값은 repeat(양방향), repeat-x(수평 방향만), repeat-y(수직 방향만), no-repeat(반복 없음)입니다. repetition 인수가 비어 있으면, repeat 값이 사용됩니다.

이미지가 아직 완전히 디코딩되지 않은 경우, 아무 것도 그려지지 않습니다. 이미지가 데이터가 없는 캔버스인 경우, "InvalidStateError" DOMException 예외가 던져집니다.

pattern.setTransform(transform)

CanvasPattern/setTransform

모든 현재 엔진에서 지원됩니다.

Firefox33+Safari11.1+Chrome68+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

채우기 또는 외곽선 페인팅 작업 중 패턴을 렌더링할 때 사용할 변환 행렬을 설정합니다.

createPattern(image, repetition) 메서드는 호출될 때, 다음 단계를 수행해야 합니다:

  1. usability이미지 인수의 사용 가능성을 확인한 결과로 설정합니다.

  2. usability나쁨이면 null을 반환합니다.

  3. 단언: usability좋음입니다.

  4. repetition이 빈 문자열이면 "repeat"로 설정합니다.

  5. repetition이 "repeat", "repeat-x", "repeat-y", 또는 "no-repeat"와 일치하지 않는 경우, "SyntaxError" DOMException 예외를 던집니다.

  6. imagerepetition에 따라 이미지의 반복 동작을 지정하는 새 CanvasPattern 객체로 pattern을 설정합니다.

  7. image기원이 청정하지 않음인 경우, pattern기원이 청정하지 않음으로 표시합니다.

  8. pattern을 반환합니다.

CanvasPattern 객체를 생성할 때 사용된 imagecreatePattern() 메서드를 호출한 후 수정해도 CanvasPattern 객체에 의해 렌더링되는 패턴에 영향을 미쳐서는 안 됩니다.

패턴에는 변환 행렬이 있으며, 이 행렬은 패턴이 페인팅될 때 패턴의 사용 방식을 제어합니다. 처음에는 패턴의 변환 행렬이 단위 행렬이어야 합니다.

setTransform(transform) 메서드는 호출될 때, 다음 단계를 수행해야 합니다:

  1. matrix2D 사전에서 DOMMatrix 생성한 결과로 설정합니다.

  2. 하나 이상의 matrix m11 요소, m12 요소, m21 요소, m22 요소, m41 요소, 또는 m42 요소가 무한대이거나 NaN인 경우, 반환합니다.

  3. 패턴의 변환 행렬을 matrix로 재설정합니다.

패턴이 영역 내에 렌더링될 때, 사용자 에이전트는 렌더링될 내용을 결정하기 위해 다음 단계를 수행해야 합니다:

  1. 무한한 투명한 검정색 비트맵을 생성합니다.

  2. 이미지의 왼쪽 위 모서리가 좌표 공간의 원점에 고정되도록 비트맵에 이미지를 복사하여 배치하고, 이미지의 CSS 픽셀당 하나의 좌표 공간 단위를 사용하여, repeat-x 반복 동작이면 왼쪽과 오른쪽에, repeat-y 반복 동작이면 위쪽과 아래쪽에, repeat 반복 동작이면 비트맵 전체에 이 이미지를 반복하여 배치합니다.

    원본 이미지 데이터가 비트맵 이미지인 경우, 반복된 영역의 각 지점에 그려지는 값은 원본 이미지 데이터를 필터링하여 계산됩니다. 확대할 때, imageSmoothingEnabled 속성이 false로 설정된 경우, 이미지가 최근린 이웃 보간법을 사용하여 렌더링되어야 합니다. 그렇지 않으면, 사용자 에이전트는 어떤 필터링 알고리즘(예: 양선형 보간법 또는 최근린 이웃 보간법)을 사용할 수 있습니다. 여러 필터링 알고리즘을 지원하는 사용자 에이전트는 imageSmoothingQuality 속성의 값을 사용하여 필터링 알고리즘의 선택을 안내할 수 있습니다. 이러한 필터링 알고리즘이 원본 이미지 데이터 외부의 픽셀 값을 필요로 하는 경우, 원본 이미지의 크기로 픽셀의 좌표를 래핑하여 해당 값을 대신 사용해야 합니다. (즉, 필터는 패턴의 반복 동작 값에 관계없이 'repeat' 동작을 사용합니다.)

  3. 패턴의 변환 행렬에 따라 결과 비트맵을 변환합니다.

  4. 현재 변환 행렬에 따라 결과 비트맵을 다시 변환합니다.

  5. 패턴이 렌더링될 영역 외부의 이미지를 투명한 검정색으로 교체합니다.

  6. 결과 비트맵이 렌더링될 내용이며, 동일한 원점과 동일한 크기를 갖습니다.


변환 행렬이 단수인 경우, 방사형 그라데이션 또는 반복된 패턴을 사용할 때 결과 스타일은 투명한 검정색이어야 합니다 (그렇지 않으면 그라데이션이나 패턴이 점 또는 선으로 축소되어 다른 픽셀은 정의되지 않은 상태로 남게 됩니다). 선형 그라데이션과 단색은 단수 변환 행렬에서도 항상 모든 점을 정의합니다.

4.12.5.1.10 비트맵에 사각형 그리기

CanvasRect 인터페이스를 구현하는 객체는 비트맵에 사각형을 즉시 그리기 위한 다음 메서드를 제공합니다. 각 메서드는 네 개의 인수를 받으며, 처음 두 개는 사각형의 왼쪽 위 모서리의 xy 좌표를 나타내고, 나머지 두 개는 각각 사각형의 너비 w와 높이 h를 나타냅니다.

다음 네 좌표에 현재 변환 행렬을 적용해야 하며, 이 좌표들은 지정된 사각형을 얻기 위해 경로를 닫아야 합니다: (x, y), (x+w, y), (x+w, y+h), (x, y+h).

도형은 현재 기본 경로에 영향을 주지 않고 그려지며, 클리핑 영역clearRect()를 제외한 그림자 효과, 전역 알파, 그리고 현재 합성 및 블렌딩 연산자의 영향을 받습니다.

context.clearRect(x, y, w, h)

CanvasRenderingContext2D/clearRect

모든 현재 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

지정된 사각형 내의 모든 픽셀을 투명한 검정색으로 지웁니다.

context.fillRect(x, y, w, h)

CanvasRenderingContext2D/fillRect

모든 현재 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera9+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

현재 채우기 스타일을 사용하여 지정된 사각형을 비트맵에 그립니다.

context.strokeRect(x, y, w, h)

CanvasRenderingContext2D/strokeRect

모든 현재 엔진에서 지원됩니다.

Firefox1.5+ Safari2+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

현재 선 스타일을 사용하여 지정된 사각형의 외곽선을 비트맵에 그립니다.

clearRect(x, y, w, h) 메서드는 호출될 때, 다음 단계를 수행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. pixels을 현재 클리핑 영역과 교차하는 지정된 사각형 내의 픽셀 집합으로 설정합니다.

  3. pixels의 픽셀을 투명한 검정색으로 지우고, 이전 이미지를 삭제합니다.

높이 또는 너비가 0인 경우, 픽셀 집합이 비어 있기 때문에 이 메서드는 아무런 효과가 없습니다.

fillRect(x, y, w, h) 메서드는 호출될 때, 다음 단계를 수행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. w 또는 h 중 하나라도 0이면, 반환합니다.

  3. 지정된 사각형 영역을 this채우기 스타일을 사용하여 그립니다.

strokeRect(x, y, w, h) 메서드는 호출될 때, 다음 단계를 수행해야 합니다:

  1. 인수 중 하나라도 무한대이거나 NaN인 경우, 반환합니다.

  2. 아래에 설명된 경로 추적 결과를 사용하고, CanvasPathDrawingStyles 인터페이스의 선 스타일을 사용하여 경로를 그립니다.

wh가 모두 0인 경우, 경로에는 x, y로 이루어진 한 개의 점만 있는 단일 하위 경로가 있으며, 이 메서드는 아무런 효과가 없습니다(이 경우 경로 추적 알고리즘이 빈 경로를 반환합니다).

w 또는 h 중 하나만 0인 경우, 경로에는 x, y 좌표와 x+w, y+h 좌표로 이루어진 두 개의 점으로 이루어진 단일 하위 경로가 있으며, 이 두 점은 단일 직선으로 연결됩니다.

그 외의 경우, 경로에는 x, y 좌표, x+w, y 좌표, x+w, y+h 좌표, 그리고 x, y+h 좌표로 이루어진 네 개의 점으로 이루어진 단일 하위 경로가 있으며, 이 점들은 직선으로 순서대로 연결됩니다.

4.12.5.1.11 비트맵에 텍스트 그리기

CanvasRenderingContext2D

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
context.fillText(text, x, y [, maxWidth ])

CanvasRenderingContext2D/fillText

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
context.strokeText(text, x, y [, maxWidth ])

CanvasRenderingContext2D/strokeText

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

주어진 위치에 지정된 텍스트를 각각 채우거나 윤곽선을 그립니다. 최대 너비가 제공된 경우, 텍스트는 필요에 따라 해당 너비에 맞도록 조정됩니다.

metrics = context.measureText(text)

CanvasRenderingContext2D/measureText

모든 현재 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

현재 글꼴의 지정된 텍스트에 대한 메트릭스 객체인 TextMetrics를 반환합니다.

metrics.width

TextMetrics/width

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari4+Chrome2+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android31+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
metrics.actualBoundingBoxLeft

TextMetrics/actualBoundingBoxLeft

모든 현재 엔진에서 지원됩니다.

Firefox74+Safari11.1+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.actualBoundingBoxRight

TextMetrics/actualBoundingBoxRight

모든 현재 엔진에서 지원됩니다.

Firefox74+Safari11.1+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.fontBoundingBoxAscent

TextMetrics/fontBoundingBoxAscent

모든 현재 엔진에서 지원됩니다.

Firefox116+Safari11.1+Chrome87+
Opera?Edge87+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.fontBoundingBoxDescent

TextMetrics/fontBoundingBoxDescent

모든 현재 엔진에서 지원됩니다.

Firefox116+Safari11.1+Chrome87+
Opera?Edge87+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.actualBoundingBoxAscent

TextMetrics/actualBoundingBoxAscent

모든 현재 엔진에서 지원됩니다.

Firefox74+Safari11.1+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.actualBoundingBoxDescent

TextMetrics/actualBoundingBoxDescent

모든 현재 엔진에서 지원됩니다.

Firefox74+Safari11.1+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.emHeightAscent

TextMetrics/emHeightAscent

모든 현재 엔진에서 지원됩니다.

Firefox🔰 74+Safari11.1+Chrome🔰 35+
Opera?Edge🔰 79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.emHeightDescent

TextMetrics/emHeightDescent

모든 현재 엔진에서 지원됩니다.

Firefox🔰 74+Safari11.1+Chrome🔰 35+
Opera?Edge🔰 79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.hangingBaseline

TextMetrics/hangingBaseline

Firefox🔰 74+Safari11.1+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.alphabeticBaseline

TextMetrics/alphabeticBaseline

Firefox🔰 74+Safari11.1+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
metrics.ideographicBaseline

TextMetrics/ideographicBaseline

Firefox🔰 74+Safari11.1+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

아래에서 설명된 측정을 반환합니다.

CanvasText 인터페이스를 구현하는 객체는 텍스트 렌더링을 위한 다음의 메서드를 제공합니다.

fillText(text, x, y, maxWidth)strokeText(text, x, y, maxWidth) 메서드는 지정된 text를 지정된 (x, y) 좌표에 렌더링하며, maxWidth가 지정된 경우 텍스트의 너비가 이를 초과하지 않도록 보장합니다. 현재의 font, textAlign, 및 textBaseline 값을 사용합니다. 구체적으로, 메서드가 호출될 때 사용자 에이전트는 다음 단계들을 수행해야 합니다:

  1. 인수 중 하나라도 무한대나 NaN인 경우, 반환합니다.

  2. 텍스트 준비 알고리즘을 실행하여, text, CanvasText 인터페이스를 구현하는 객체, 그리고 maxWidth 인수가 제공된 경우, 그 인수를 전달합니다. 결과를 glyphs로 합니다.

  3. 모든 glyphs의 도형을 x CSS 픽셀 만큼 오른쪽으로, y CSS 픽셀 만큼 아래로 이동시킵니다.

  4. 현재 변환 행렬에 의해 변환된 도형을, glyphs의 좌표 공간에서 한 좌표 공간 단위에 매핑하여 페인트합니다.

    fillText()의 경우, this채우기 스타일을 도형에 적용하고, this선 스타일은 무시합니다. strokeText()의 경우에는 반대로, this선 스타일CanvasText 인터페이스를 구현하는 객체의 선 스타일로 적용하며, this채우기 스타일은 무시합니다.

    이 도형들은 현재 경로에 영향을 주지 않고 페인트되며, 그림자 효과, 전역 알파, 클리핑 영역, 그리고 현재 합성 및 블렌딩 연산자의 영향을 받습니다.

(이것은 추적 벡터입니다.) measureText(text) 메서드의 단계는 텍스트 준비 알고리즘을 실행하여 textCanvasText 인터페이스를 구현하는 객체를 전달한 다음 반환된 인라인 박스를 사용하여, 다음 목록에서 설명한 대로 구성원들이 동작하는 새 TextMetrics 객체를 반환해야 합니다: [CSS]

width 속성

해당 인라인 박스의 너비, CSS 픽셀 단위입니다. (텍스트의 전진 너비입니다.)

actualBoundingBoxLeft 속성

textAlign 속성으로 지정된 정렬 지점에서 주어진 텍스트의 바운딩 사각형 왼쪽까지의 베이스라인과 평행한 거리, CSS 픽셀 단위입니다. 양수는 지정된 정렬 지점에서 왼쪽으로의 거리를 나타냅니다.

이 값과 다음 값(actualBoundingBoxRight)의 합은 인라인 박스(width)의 너비보다 넓을 수 있습니다. 특히, 기울어진 글꼴의 경우 문자들이 그들의 전진 너비를 넘어서 연장될 수 있습니다.

actualBoundingBoxRight 속성

textAlign 속성으로 지정된 정렬 지점에서 주어진 텍스트의 바운딩 사각형 오른쪽까지의 베이스라인과 평행한 거리, CSS 픽셀 단위입니다. 양수는 지정된 정렬 지점에서 오른쪽으로의 거리를 나타냅니다.

fontBoundingBoxAscent 속성

textBaseline 속성으로 표시된 수평선에서 상승 메트릭까지의 거리, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인에서 위쪽으로의 거리를 나타냅니다.

이 값과 다음 값은 렌더링되는 텍스트가 변경되더라도 배경이 일정한 높이를 유지해야 할 때 유용합니다. actualBoundingBoxAscent 속성(및 내림에 대한 해당 속성)은 특정 텍스트 주위에 바운딩 박스를 그릴 때 유용합니다.

fontBoundingBoxDescent 속성

textBaseline 속성으로 표시된 수평선에서 하강 메트릭까지의 거리, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인에서 아래쪽으로의 거리를 나타냅니다.

actualBoundingBoxAscent 속성

textBaseline 속성으로 표시된 수평선에서 주어진 텍스트의 바운딩 사각형 상단까지의 거리, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인에서 위쪽으로의 거리를 나타냅니다.

이 숫자는 입력 텍스트에 따라 크게 달라질 수 있습니다. 예를 들어, 알파벳 소문자 "o"의 actualBoundingBoxAscent는 대문자 "F"의 값보다 작을 수 있습니다. 이 값은 쉽게 음수가 될 수 있습니다. 예를 들어, 텍스트가 단일 쉼표 ","일 때, em 박스 상단(textBaseline 값 "top")에서 바운딩 사각형 상단까지의 거리는 (폰트가 매우 특이하지 않는 한) 음수일 가능성이 큽니다.

actualBoundingBoxDescent 속성

textBaseline 속성으로 표시된 수평선에서 주어진 텍스트의 바운딩 사각형 하단까지의 거리, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인에서 아래쪽으로의 거리를 나타냅니다.

emHeightAscent 속성

textBaseline 속성으로 표시된 수평선에서 em 사각형 상단까지의 거리, 인라인 박스 내에서, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인이 해당 em 사각형 상단보다 아래에 있음을 나타냅니다(따라서 이 값은 보통 양수입니다). 주어진 베이스라인이 해당 em 사각형의 상단인 경우 0, 주어진 베이스라인이 해당 em 사각형의 중간인 경우 폰트 크기의 절반입니다.

emHeightDescent 속성

textBaseline 속성으로 표시된 수평선에서 em 사각형 하단까지의 거리, 인라인 박스 내에서, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인이 해당 em 사각형 하단보다 위에 있음을 나타냅니다(따라서 이 값은 보통 양수입니다). 주어진 베이스라인이 해당 em 사각형의 하단인 경우 0입니다.

hangingBaseline 속성

textBaseline 속성으로 표시된 수평선에서 걸이 베이스라인까지의 거리, 인라인 박스 내에서, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인이 걸이 베이스라인보다 아래에 있음을 나타냅니다(따라서 이 값은 보통 양수입니다). 주어진 베이스라인이 걸이 베이스라인인 경우 0입니다.

alphabeticBaseline 속성

textBaseline 속성으로 표시된 수평선에서 알파벳 베이스라인까지의 거리, 인라인 박스 내에서, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인이 알파벳 베이스라인보다 아래에 있음을 나타냅니다. (따라서 이 값은 보통 양수입니다.) 주어진 베이스라인이 알파벳 베이스라인인 경우 0입니다.

ideographicBaseline 속성

textBaseline 속성으로 표시된 수평선에서 이데오그래픽 언더 베이스라인까지의 거리, 인라인 박스 내에서, CSS 픽셀 단위입니다. 양수는 지정된 베이스라인이 이데오그래픽 언더 베이스라인보다 아래에 있음을 나타냅니다. (따라서 이 값은 보통 양수입니다.) 주어진 베이스라인이 이데오그래픽 언더 베이스라인인 경우 0입니다.

fillText()strokeText()를 사용하여 렌더링된 글리프는 글꼴 크기(em 사각형 크기)와 measureText()(텍스트 너비)에서 제공된 상자를 넘어서 흐를 수 있습니다. 작성자들은 이 문제가 발생할 경우 위에서 설명한 바운딩 박스 값을 사용하는 것이 좋습니다.

2D 컨텍스트 API의 향후 버전은 CSS를 사용하여 렌더링된 문서 조각을 캔버스로 직접 렌더링하는 방법을 제공할 수 있습니다. 이는 멀티라인 레이아웃을 위한 전용 방법보다 우선적으로 제공될 것입니다.

4.12.5.1.12 캔버스에 경로 그리기

CanvasDrawPath 인터페이스를 구현하는 객체는 현재 기본 경로를 가집니다. 현재 기본 경로는 오직 하나이며, 그리기 상태의 일부가 아닙니다. 현재 기본 경로는 위에서 설명한 것과 같은 경로입니다.

context.beginPath()

CanvasRenderingContext2D/beginPath

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 기본 경로를 재설정합니다.

context.fill([ fillRule ])

CanvasRenderingContext2D/fill

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
context.fill(path [, fillRule ])

현재 기본 경로 또는 주어진 경로의 하위 경로를 현재의 채우기 스타일로, 주어진 채우기 규칙을 준수하여 채웁니다.

context.stroke()

CanvasRenderingContext2D/stroke

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
context.stroke(path)

현재 기본 경로 또는 주어진 경로의 하위 경로를 현재의 선 스타일로 윤곽을 그립니다.

context.clip([ fillRule ])

CanvasRenderingContext2D/clip

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
context.clip(path [, fillRule ])

주어진 채우기 규칙을 사용하여 경로에 어떤 점이 포함되는지 결정하면서 현재 기본 경로 또는 주어진 경로로 클리핑 영역을 추가로 제한합니다.

context.isPointInPath(x, y [, fillRule ])

CanvasRenderingContext2D/isPointInPath

모든 현재 엔진에서 지원.

Firefox2+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
context.isPointInPath(path, x, y [, fillRule ])

지정된 채우기 규칙을 사용하여 지정된 점이 현재 기본 경로 또는 주어진 경로에 포함되는지 여부를 반환합니다.

context.isPointInStroke(x, y)

CanvasRenderingContext2D/isPointInStroke

모든 현재 엔진에서 지원.

Firefox19+Safari7+Chrome26+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
context.isPointInStroke(path, x, y)

지정된 점이 현재 기본 경로 또는 주어진 경로의 스트로크에 의해 덮인 영역에 포함되는지 여부를 반환합니다.

beginPath() 메서드는 this현재 기본 경로에서 하위 경로 목록을 비워 다시 하위 경로가 0이 되도록 하는 단계입니다.

다음 메서드 정의에서 의도된 경로라는 용어를 Path2D-또는-null path에 대해 사용할 때, 이는 path 자체가 Path2D 객체일 경우에는 path를 의미하며, 그렇지 않을 경우 현재 기본 경로를 의미합니다.

의도된 경로Path2D 객체일 때, 이 객체의 하위 경로의 좌표와 선은 이 메서드들을 사용할 때 CanvasTransform 인터페이스를 구현하는 객체에 있는 현재 변환 매트릭스에 따라 변환되어야 합니다(단, Path2D 객체 자체에는 영향을 주지 않습니다). 의도된 경로가 현재 기본 경로일 때는 변환의 영향을 받지 않습니다. (이는 변환이 이미 현재 기본 경로가 구성될 때 영향을 주므로, 그리기 시에도 적용하면 이중 변환이 발생할 수 있기 때문입니다.)

fill(fillRule) 메서드 단계는 채우기 단계this, null, 및 fillRule에 대해 실행하는 것입니다.

fill(path, fillRule) 메서드 단계는 채우기 단계this, path, 및 fillRule에 대해 실행하는 것입니다.

채우기 단계CanvasDrawPath context, Path2D-또는-null path, 및 채우기 규칙 fillRule이 주어졌을 때, path에 대한 의도된 경로의 모든 하위 경로를 context채우기 스타일을 사용하여, fillRule에 의해 표시된 채우기 규칙을 사용하여 채우는 것입니다. 열려 있는 하위 경로는 암묵적으로 닫혀야 합니다(실제 하위 경로에는 영향을 미치지 않습니다).

stroke() 메서드 단계는 선 그리기 단계this와 null을 주어 실행하는 것입니다.

stroke(path) 메서드 단계는 선 그리기 단계thispath에 대해 실행하는 것입니다.

선 그리기 단계CanvasDrawPath contextPath2D-또는-null path이 주어졌을 때, context의 선 스타일을 사용하여 의도된 경로추적한 후, context선 스타일을 사용하여 결과 경로를 채우는 것입니다. 이때 nonzero winding 규칙을 사용합니다.

경로를 추적하는 알고리즘이 정의된 방식으로 인해, 하나의 선 그리기 작업에서 경로의 중첩된 부분은 그들의 합집합이 칠해진 것처럼 처리됩니다.

선 스타일은 현재 기본 경로를 사용하는 경우에도 그리기 중에 변환의 영향을 받습니다.

경로는 채워지거나 그려질 때 현재 기본 경로Path2D 객체에 영향을 주지 않고 그려져야 하며, 그림자 효과, 글로벌 알파, 클리핑 영역, 및 현재 합성 및 혼합 연산자의 영향을 받아야 합니다. (변환의 효과는 위에서 설명한 대로 사용되는 경로에 따라 다릅니다.)


clip(fillRule) 메서드 단계는 클립 단계this, null, 및 fillRule에 대해 실행하는 것입니다.

clip(path, fillRule) 메서드 단계는 클립 단계this, path, 및 fillRule에 대해 실행하는 것입니다.

클립 단계CanvasDrawPath context, Path2D-또는-null path, 및 채우기 규칙 fillRule이 주어졌을 때, 의도된 경로에 의해 설명된 영역과 context의 현재 클리핑 영역의 교차를 계산하여 새로운 클리핑 영역을 만드는 것입니다. 열려 있는 하위 경로는 실제 하위 경로에 영향을 미치지 않고, 클리핑 영역을 계산할 때 암묵적으로 닫혀야 합니다. 새 클리핑 영역은 현재 클리핑 영역을 대체합니다.

컨텍스트가 초기화되면, 현재 클리핑 영역은 가장 큰 무한 표면으로 설정되어야 합니다(즉, 기본적으로 클리핑이 발생하지 않음).


isPointInPath(x, y, fillRule) 메서드 단계는 경로 내 점 확인 단계this, null, x, y, 및 fillRule에 대해 실행한 결과를 반환하는 것입니다.

isPointInPath(path, x, y, fillRule) 메서드 단계는 경로 내 점 확인 단계this, path, x, y, 및 fillRule에 대해 실행한 결과를 반환하는 것입니다.

경로 내 점 확인 단계CanvasDrawPath context, Path2D-또는-null path, 두 숫자 xy, 그리고 채우기 규칙 fillRule이 주어졌을 때, 다음과 같습니다:

  1. x 또는 y가 무한대 또는 NaN이면, false를 반환합니다.

  2. 캔버스 좌표 공간에서 현재 변환에 영향을 받지 않는 좌표로 처리될 때 xy 좌표에 의해 주어진 점이 path에 대한 의도된 경로 내에 있는 경우 fillRule에 의해 표시된 채우기 규칙에 의해 true를 반환합니다. 열린 하위 경로는 실제 하위 경로에 영향을 미치지 않고, 경로 내부의 영역을 계산할 때 암묵적으로 닫혀야 합니다. 경로 자체에 있는 점은 경로 내부로 간주되어야 합니다.

  3. false를 반환합니다.


isPointInStroke(x, y) 메서드 단계는 스트로크 내 점 확인 단계this, null, x, 및 y에 대해 실행한 결과를 반환하는 것입니다.

isPointInStroke(path, x, y) 메서드 단계는 스트로크 내 점 확인 단계this, path, x, 및 y에 대해 실행한 결과를 반환하는 것입니다.

스트로크 내 점 확인 단계CanvasDrawPath context, Path2D-또는-null path, 두 숫자 xy가 주어졌을 때, 다음과 같습니다:

  1. x 또는 y가 무한대 또는 NaN이면, false를 반환합니다.

  2. 캔버스 좌표 공간에서 현재 변환에 영향을 받지 않는 좌표로 처리될 때 xy 좌표에 의해 주어진 점이 path에 대한 의도된 경로추적하여 얻어진 경로 내부에 있는 경우 nonzero winding 규칙을 사용하여 true를 반환하고, contextCanvasPathDrawingStyles 믹스인의 선 스타일을 사용합니다. 결과 경로에 있는 점은 경로 내부로 간주되어야 합니다.

  3. false를 반환합니다.


캔버스 요소에는 두 개의 체크박스가 있습니다. 경로 관련 명령이 강조 표시됩니다:

<canvas height=400 width=750>
 <label><input type=checkbox id=showA> Show As</label>
 <label><input type=checkbox id=showB> Show Bs</label>
 <!-- ... -->
</canvas>
<script>
 function drawCheckbox(context, element, x, y, paint) {
   context.save();
   context.font = '10px sans-serif';
   context.textAlign = 'left';
   context.textBaseline = 'middle';
   var metrics = context.measureText(element.labels[0].textContent);
   if (paint) {
     context.beginPath();
     context.strokeStyle = 'black';
     context.rect(x-5, y-5, 10, 10);
     context.stroke();
     if (element.checked) {
       context.fillStyle = 'black';
       context.fill();
     }
     context.fillText(element.labels[0].textContent, x+5, y);
   }
   context.beginPath();
   context.rect(x-7, y-7, 12 + metrics.width+2, 14);

   context.drawFocusIfNeeded(element);
   context.restore();
 }
 function drawBase() { /* ... */ }
 function drawAs() { /* ... */ }
 function drawBs() { /* ... */ }
 function redraw() {
   var canvas = document.getElementsByTagName('canvas')[0];
   var context = canvas.getContext('2d');
   context.clearRect(0, 0, canvas.width, canvas.height);
   drawCheckbox(context, document.getElementById('showA'), 20, 40, true);
   drawCheckbox(context, document.getElementById('showB'), 20, 60, true);
   drawBase();
   if (document.getElementById('showA').checked)
     drawAs();
   if (document.getElementById('showB').checked)
     drawBs();
 }
 function processClick(event) {
   var canvas = document.getElementsByTagName('canvas')[0];
   var context = canvas.getContext('2d');
   var x = event.clientX;
   var y = event.clientY;
   var node = event.target;
   while (node) {
     x -= node.offsetLeft - node.scrollLeft;
     y -= node.offsetTop - node.scrollTop;
     node = node.offsetParent;
   }
   drawCheckbox(context, document.getElementById('showA'), 20, 40, false);
   if (context.isPointInPath(x, y))
     document.getElementById('showA').checked = !(document.getElementById('showA').checked);
   drawCheckbox(context, document.getElementById('showB'), 20, 60, false);
   if (context.isPointInPath(x, y))
     document.getElementById('showB').checked = !(document.getElementById('showB').checked);
   redraw();
 }
 document.getElementsByTagName('canvas')[0].addEventListener('focus', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('blur', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('change', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('click', processClick, false);
 redraw();
</script>
4.12.5.1.13 포커스 링 그리기
context.drawFocusIfNeeded(element)

CanvasRenderingContext2D/drawFocusIfNeeded

모든 현재 엔진에서 지원.

Firefox32+Safari8+Chrome37+
Opera?Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

element포커스된 경우, 플랫폼의 포커스 링 규칙을 따라 현재 기본 경로 주위에 포커스 링을 그립니다.

context.drawFocusIfNeeded(path, element)

element포커스된 경우, 플랫폼의 포커스 링 규칙을 따라 path 주위에 포커스 링을 그립니다.

CanvasUserInterface 인터페이스를 구현하는 객체는 포커스 링을 그리기 위한 다음 메서드를 제공합니다.

drawFocusIfNeeded(element) 메서드 단계는 필요 시 포커스 그리기 단계를 this, element, 및 this현재 기본 경로를 주어 실행하는 것입니다.

drawFocusIfNeeded(path, element) 메서드 단계는 필요 시 포커스 그리기 단계를 this, element, 및 path를 주어 실행하는 것입니다.

객체가 CanvasUserInterface를 구현할 때, context, 요소 element, 및 경로 path가 주어졌을 때, 필요 시 포커스를 그리기 위한 단계는 다음과 같습니다:

  1. element포커스된 상태가 아니거나, context캔버스 요소의 하위 요소가 아닌 경우, 반환합니다.

  2. 플랫폼 규칙에 따라 path를 따라 적절한 스타일의 포커스 링을 그립니다.

    일부 플랫폼에서는 키보드로 포커스된 요소에만 포커스 링을 그리고, 마우스로 포커스된 요소에는 그리지 않습니다. 다른 플랫폼에서는 관련 접근성 기능이 활성화되지 않으면 특정 요소 주위에 포커스 링을 그리지 않습니다. 이 API는 이러한 규칙을 따르도록 설계되었습니다. 요소가 포커스된 방식에 따라 구분하는 사용자 에이전트는 focus() 메서드를 사용하여 호출된 경우 사용자 상호작용 이벤트의 종류에 따라 포커스를 분류하는 것을 권장합니다(해당 이벤트가 있는 경우).

    포커스 링은 그림자 효과, 글로벌 알파, 현재 합성 및 혼합 연산자, 채우기 스타일, 선 스타일, 또는 CanvasPathDrawingStyles, CanvasTextDrawingStyles 인터페이스의 멤버의 영향을 받지 않아야 하지만, 클리핑 영역의 영향을 받아야 합니다. (변환의 효과는 위에서 설명한 대로 사용되는 경로에 따라 다릅니다.)

  3. 사용자에게 알림은 의도된 경로에 따라 포커스가 위치하는 것을 사용자에게 알립니다. 사용자 에이전트는 다음에 이벤트 루프렌더링 업데이트 단계를 도달할 때까지 기다렸다가 선택적으로 사용자에게 알릴 수 있습니다.

사용자 에이전트는 포커스 링을 그릴 때 의도된 경로에서 열린 하위 경로를 암묵적으로 닫지 않아야 합니다.

그러나 이것은 무의미한 포인트일 수 있습니다. 예를 들어, 포커스 링이 의도된 경로의 점 주위에 축 정렬된 경계 사각형으로 그려지면 하위 경로가 닫혔는지 여부는 아무런 영향을 미치지 않습니다. 이 사양은 포커스 링이 그려지는 방식을 명확히 규정하지 않으며, 사용자 에이전트가 플랫폼의 기본 규칙을 준수할 것으로 기대합니다.

이 섹션에서 사용된 "사용자에게 알림"은 영구적인 상태 변화를 의미하지 않습니다. 예를 들어, 시스템 접근성 API를 호출하여 확대 도구와 같은 보조 기술에 알리고 사용자의 확대기가 캔버스의 해당 영역으로 이동하도록 할 수 있습니다. 그러나 이 경로를 요소와 연관시키거나 촉각 피드백 영역을 제공하지는 않습니다.

4.12.5.1.14 이미지 그리기

CanvasDrawImage 인터페이스를 구현하는 객체는 이미지를 그리기 위한 drawImage() 메서드를 가지고 있습니다.

이 메서드는 세 가지 다른 인수 집합으로 호출될 수 있습니다:

context.drawImage(image, dx, dy)

CanvasRenderingContext2D/drawImage

모든 현재 엔진에서 지원.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
context.drawImage(image, dx, dy, dw, dh)
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

주어진 이미지를 캔버스에 그립니다. 인수는 다음과 같이 해석됩니다:

sx 및 sy 매개변수는 소스 사각형의 x 및 y 좌표를 제공하고, sw 및 sh 인수는 소스 사각형의 너비와 높이를 제공합니다; dx 및 dy는 대상 사각형의 x 및 y 좌표를 제공하며, dw 및 dh 인수는 대상 사각형의 너비와 높이를 제공합니다.

이미지가 아직 완전히 디코딩되지 않은 경우 아무것도 그리지 않습니다. 이미지가 데이터가 없는 캔버스인 경우, "InvalidStateError" DOMException을 던집니다.

drawImage() 메서드가 호출되면, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. 인수 중 하나라도 무한대 또는 NaN인 경우, 반환합니다.

  2. usabilityimage의 사용 가능성 확인 결과로 설정합니다.

  3. usability나쁨인 경우, 아무것도 그리지 않고 반환합니다.

  4. 소스 및 대상 사각형을 다음과 같이 설정합니다:

    명시되지 않은 경우, dwdh 인수는 각각 swsh 값으로 기본 설정되어야 하며, 이미지에서 하나의 CSS 픽셀출력 비트맵의 좌표 공간에서 하나의 단위로 처리됩니다. sx, sy, swsh 인수가 생략된 경우, 이들은 각각 0, 0, 이미지 픽셀 단위의 이미지 자연 너비 및 이미지 자연 높이로 기본 설정되어야 합니다. 이미지에 자연 크기가 없는 경우, 콘크리트 객체 크기 해상도 알고리즘을 사용하여 콘크리트 객체 크기가 대신 사용되어야 합니다. 이때 지정된 크기는 명확한 너비나 높이가 없으며 추가 제약 조건도 없고, 객체의 자연 속성은 image 인수의 속성으로, 기본 객체 크기출력 비트맵의 크기로 간주됩니다. [CSSIMAGES]

    소스 사각형은 네 점 (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh)로 정의된 사각형입니다.

    대상 사각형은 네 점 (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh)로 정의된 사각형입니다.

    소스 사각형이 소스 이미지 밖에 있을 경우, 소스 사각형은 소스 이미지에 맞게 잘려야 하며 대상 사각형도 동일한 비율로 잘려야 합니다.

    대상 사각형이 대상 이미지(출력 비트맵) 밖에 있을 경우, 출력 비트맵 밖에 위치하는 픽셀은 출력 비트맵의 크기에 맞게 렌더링이 잘린 무한 캔버스로 취급되어 삭제됩니다.

  5. sw 또는 sh 인수 중 하나라도 0이면, 반환합니다. 아무것도 그려지지 않습니다.

  6. image 인수로 지정된 영역을 렌더링 컨텍스트의 출력 비트맵의 대상 사각형에 지정된 영역에 현재 변환 매트릭스를 대상 사각형에 적용한 후 그립니다.

    이미지 데이터는 주어진 크기가 음수이더라도 원래 방향으로 처리되어야 합니다.

    imageSmoothingEnabled 속성이 true로 설정된 경우, 이미지를 확대할 때 사용자 에이전트는 이미지 데이터에 스무딩 알고리즘을 적용하려고 시도해야 합니다. 여러 필터링 알고리즘을 지원하는 사용자 에이전트는 imageSmoothingQuality 속성의 값을 사용하여 imageSmoothingEnabled 속성이 true로 설정된 경우 필터링 알고리즘을 선택할 수 있습니다. 그렇지 않은 경우, 이미지는 최근접 이웃 보간을 사용하여 렌더링해야 합니다.

    이 사양은 이미지를 축소할 때 또는 imageSmoothingEnabled 속성이 true로 설정된 경우 이미지를 확대할 때 사용할 정확한 알고리즘을 정의하지 않습니다.

    캔버스 요소가 자체에 그려질 때, 그리기 모델은 이미지가 그려지기 전에 소스를 복사해야 하므로, 캔버스 요소의 일부를 자체의 중첩된 부분에 복사하는 것이 가능합니다.

    원본 이미지 데이터가 비트맵 이미지인 경우, 대상 사각형의 특정 지점에 그려지는 값은 원본 이미지 데이터를 필터링하여 계산됩니다. 사용자 에이전트는 어떤 필터링 알고리즘(예: 이중 선형 보간 또는 최근접 이웃)을 사용할 수 있습니다. 필터링 알고리즘이 원본 이미지 데이터 외부에서 픽셀 값을 필요로 할 때는 대신 가장 가까운 가장자리 픽셀의 값을 사용해야 합니다. (즉, 필터는 '가장자리 고정' 동작을 사용합니다.) 필터링 알고리즘이 소스 사각형 외부이지만 원본 이미지 데이터 내부에서 픽셀 값을 필요로 할 때는 원본 이미지 데이터의 값을 사용해야 합니다.

    따라서 이미지를 부분적으로 또는 전체적으로 확대해도 동일한 효과가 나타납니다. 이는 단일 스프라이트 시트에서 나오는 스프라이트를 확대할 때 인접한 이미지가 간섭할 수 있다는 것을 의미합니다. 이것은 시트의 각 스프라이트 주위에 투명한 검정색 테두리가 있거나, 확대할 스프라이트를 임시 캔버스 요소에 복사한 다음 거기에서 확대된 스프라이트를 그리는 방식으로 해결할 수 있습니다.

    이미지는 현재 경로에 영향을 미치지 않고 그려지며, 그림자 효과, 글로벌 알파, 클리핑 영역, 및 현재 합성 및 혼합 연산자의 영향을 받습니다.

  7. image원본이 깨끗하지 않으면, CanvasRenderingContext2D원본-청결 플래그를 false로 설정합니다.

4.12.5.1.15 픽셀 조작
imagedata = new ImageData(sw, sh [, settings])

ImageData/ImageData

모든 현재 엔진에서 지원.

Firefox29+Safari8+Chrome36+
Opera?Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

지정된 크기와 settings에서 지정된 색상 공간을 가진 ImageData 객체를 반환합니다. 반환된 객체의 모든 픽셀은 투명한 검정색입니다.

너비나 높이 인수가 0인 경우 "IndexSizeError" DOMException을 던집니다.

imagedata = new ImageData(data, sw [, sh [, settings ] ])

지정된 데이터와 크기를 사용하여 settings에서 지정된 색상 공간을 가진 ImageData 객체를 반환합니다.

데이터의 각 픽셀은 네 개의 숫자로 표현되므로, 데이터의 길이는 지정된 너비의 네 배가 되어야 합니다. 높이도 제공되는 경우, 길이는 정확히 너비 곱하기 높이 곱하기 4가 되어야 합니다.

주어진 데이터와 크기를 일관되게 해석할 수 없거나, 두 치수 중 하나가 0이면 "IndexSizeError" DOMException을 던집니다.

imagedata = context.createImageData(imagedata)

인수와 동일한 크기 및 색상 공간을 가진 ImageData 객체를 반환합니다. 반환된 객체의 모든 픽셀은 투명한 검정색입니다.

imagedata = context.createImageData(sw, sh [, settings])

CanvasRenderingContext2D/createImageData

모든 현재 엔진에서 지원.

Firefox3.5+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 크기를 가진 ImageData 객체를 반환합니다. 반환된 객체의 색상 공간은 settings에서 재정의되지 않는 한, context색상 공간입니다. 반환된 객체의 모든 픽셀은 투명한 검정색입니다.

너비나 높이 인수가 0인 경우 "IndexSizeError" DOMException을 던집니다.

imagedata = context.getImageData(sx, sy, sw, sh [, settings])

CanvasRenderingContext2D/getImageData

모든 현재 엔진에서 지원.

Firefox2+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

지정된 비트맵 영역의 이미지 데이터를 포함하는 ImageData 객체를 반환합니다. 반환된 객체의 색상 공간은 settings에서 재정의되지 않는 한, context색상 공간입니다.

너비나 높이 인수가 0인 경우 "IndexSizeError" DOMException을 던집니다.

imagedata.width

ImageData/width

모든 현재 엔진에서 지원.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

ImageData 객체의 데이터에서 행당 픽셀 수를 반환합니다.

imagedata.height

ImageData/height

모든 현재 엔진에서 지원.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

ImageData 객체의 데이터에서 행 수를 반환합니다.

imagedata.data

ImageData/data

모든 현재 엔진에서 지원.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

0부터 255까지의 정수 값으로 RGBA 순서로 데이터를 포함하는 1차원 배열을 반환합니다.

imagedata.colorSpace

픽셀의 색상 공간을 반환합니다.

context.putImageData(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ])

CanvasRenderingContext2D/putImageData

모든 현재 엔진에서 지원.

Firefox2+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 ImageData 객체의 데이터를 비트맵에 그립니다. 더러운 사각형이 제공된 경우, 해당 사각형의 픽셀만 그려집니다.

globalAlphaglobalCompositeOperation 속성, 그리고 그림자 속성은 이 메서드 호출의 목적을 위해 무시됩니다; 캔버스의 픽셀은 합성, 알파 블렌딩, 그림자 등 없이 전면 교체됩니다.

"InvalidStateError" DOMException을 던집니다.

CanvasImageData 인터페이스를 구현하는 객체는 비트맵에 픽셀 데이터를 읽고 쓰기 위한 다음 메서드를 제공합니다.

new ImageData(sw, sh, settings) 생성자의 단계는 다음과 같습니다:

  1. swsh 중 하나 또는 둘 다 0이면 "IndexSizeError" DOMException을(를) 던집니다.

  2. 이 ImageData 객체를 초기화합니다. sw, sh, 및 settings에 설정된 설정을 사용합니다.

  3. 투명한 검정색으로 이 객체의 이미지 데이터를 초기화합니다.

new ImageData(data, sw, sh, settings) 생성자의 단계는 다음과 같습니다:

  1. data의 바이트 수를 length로 설정합니다.

  2. length가 4의 비제로 정수 배수가 아니면, "InvalidStateError" DOMException을(를) 던집니다.

  3. length를 4로 나눈 값을 length로 설정합니다.

  4. lengthsw의 정수 배수가 아니면, "IndexSizeError" DOMException을(를) 던집니다.

    이 단계에서 length는 0보다 크다는 것이 보장되므로(위의 두 번째 단계에서 중지하지 않았을 경우), sw가 0인 경우 이 단계에서 예외를 던지고 반환합니다.

  5. heightlengthsw로 나눈 값으로 설정합니다.

  6. sh가 주어졌고 그 값이 height와 같지 않으면, "IndexSizeError" DOMException을(를) 던집니다.

  7. 이 ImageData 객체를 초기화합니다. sw, sh, 설정settings에 설정하고, 소스data로 설정합니다.

    이 단계에서는 이 객체의 데이터를 data의 복사본으로 설정하지 않습니다. 실제로 data로 전달된 Uint8ClampedArray 객체로 설정합니다.

createImageData(sw, sh, settings) 메서드 단계는 다음과 같습니다:

  1. swsh 중 하나 또는 둘 다 0이면, "IndexSizeError" DOMException을(를) 던집니다.

  2. newImageDatanew ImageData 객체로 설정합니다.

  3. newImageData 객체를 초기화합니다. swsh의 절대 크기, settings에 설정된 설정, 및 이 객체의 색상 공간에 설정된 기본 색상 공간을 사용합니다.

  4. newImageData의 이미지 데이터를 투명한 검정색으로 초기화합니다.

  5. newImageData를 반환합니다.

createImageData(imagedata) 메서드 단계는 다음과 같습니다:

  1. newImageDatanew ImageData 객체로 설정합니다.

  2. newImageData 객체를 초기화합니다. imagedata 속성 값, imagedata높이 속성 값, 및 imagedata색상 공간 속성 값에 설정된 기본 색상 공간을 사용합니다.

  3. newImageData의 이미지 데이터를 투명한 검정색으로 초기화합니다.

  4. newImageData를 반환합니다.

getImageData(sx, sy, sw, sh, settings) 메서드 단계는 다음과 같습니다:

  1. sw 또는 sh 인수가 0이면, "IndexSizeError" DOMException을(를) 던집니다.

  2. CanvasRenderingContext2D원본 무결성 플래그가 false로 설정되어 있으면, "SecurityError" DOMException을(를) 던집니다.

  3. imageDatanew ImageData 객체로 설정합니다.

  4. imageData 객체를 초기화합니다. sw, sh, settings에 설정된 설정, 및 this 객체의 색상 공간에 설정된 기본 색상 공간을 사용합니다.

  5. 소스 직사각형은 네 점 (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh)으로 구성된 직사각형입니다.

  6. 소스 직사각형으로 지정된 영역의 픽셀 값을 imageData의 픽셀 값으로 설정합니다. 비트맵의 좌표 공간 단위로 변환된 소스 직사각형 영역 내의 this 객체의 출력 비트맵의 픽셀 값을 사용합니다. imageData색상 공간this 객체의 색상 공간에서 변환하여 설정합니다. 'relative-colorimetric' 렌더링 의도를 사용합니다.

  7. 소스 직사각형의 영역 중 출력 비트맵 외부에 있는 영역의 픽셀 값을 imageData의 픽셀 값으로 설정합니다. 해당 픽셀 값은 투명한 검정색입니다.

  8. imageData를 반환합니다.

ImageData 객체를 초기화하기 imageData는 주어진 양수의 행 수(rows), 각 행당 양수의 픽셀 수(pixelsPerRow), 선택적 ImageDataSettings settings, 선택적 Uint8ClampedArray source, 그리고 선택적 PredefinedColorSpace defaultColorSpace에 따라 초기화됩니다:

ImageData/colorSpace

Firefox지원 안 함Safari15.2+Chrome92+
Opera?Edge92+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
  1. 만약 source가 주어졌다면, imageDatadata 속성을 source로 초기화합니다.

  2. 그렇지 않다면(source가 주어지지 않았을 때), imageDatadata 속성을 새 Uint8ClampedArray 객체로 초기화합니다. 이 Uint8ClampedArray 객체는 새로운 Canvas Pixel ArrayBuffer을 사용하여 저장소로 사용해야 하며, 시작 오프셋이 0이고 저장소 길이와 동일한 길이를 가져야 합니다(바이트 단위로). Canvas Pixel ArrayBufferrows × pixelsPerRow 픽셀을 저장할 수 있는 올바른 크기를 가져야 합니다.

    만약 Canvas Pixel ArrayBuffer이 할당될 수 없다면, JavaScript에서 던진 RangeError를 다시 던지고 종료합니다.

  3. imageDatawidth 속성을 pixelsPerRow로 초기화합니다.

  4. imageDataheight 속성을 rows로 초기화합니다.

  5. 만약 settings이 주어졌고 settings["colorSpace"]가 존재한다면, imageDatacolorSpace 속성을 settings["colorSpace"]으로 초기화합니다.

  6. 그렇지 않다면, 만약 defaultColorSpace가 주어졌다면, imageDatacolorSpace 속성을 defaultColorSpace로 초기화합니다.

  7. 그렇지 않다면, imageDatacolorSpace 속성을 "srgb"로 초기화합니다.

ImageData 객체는 직렬화할 수 있는 객체입니다. 이 객체의 직렬화 단계valueserialized가 주어졌을 때 다음과 같습니다:

  1. serialized.[[Data]]를 valuedata 속성 값의 부분 직렬화로 설정합니다.

  2. serialized.[[Width]]를 valuewidth 속성 값으로 설정합니다.

  3. serialized.[[Height]]를 valueheight 속성 값으로 설정합니다.

  4. serialized.[[ColorSpace]]를 valuecolorSpace 속성 값으로 설정합니다.

serialized, value, 그리고 targetRealm이 주어졌을 때 이 객체의 역직렬화 단계는 다음과 같습니다:

  1. valuedata 속성을 serialized.[[Data]]의 부분 역직렬화로 초기화합니다.

  2. valuewidth 속성을 serialized.[[Width]]로 초기화합니다.

  3. valueheight 속성을 serialized.[[Height]]로 초기화합니다.

  4. valuecolorSpace 속성을 serialized.[[ColorSpace]]로 초기화합니다.

Canvas Pixel ArrayBuffer는 각 픽셀의 빨강, 녹색, 파랑, 알파 구성 요소가 각 픽셀에 대해 이 순서로 주어지는 왼쪽에서 오른쪽으로, 위에서 아래로 순차적으로 데이터를 표현하는 ArrayBuffer입니다. 이 배열에 표현된 각 픽셀의 각 구성 요소는 해당 구성 요소의 8비트 값을 나타내는 0..255 범위 내에 있어야 합니다. 구성 요소는 상단 왼쪽 픽셀의 빨강 구성 요소부터 시작하여 연속된 인덱스를 가져야 합니다.

putImageData() 메서드는 ImageData 구조체의 데이터를 렌더링 컨텍스트의 출력 비트맵에 다시 씁니다. 이 메서드의 인자는 imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight입니다.

이 메서드의 마지막 네 개의 인자가 생략되었을 때, 이 값들은 각각 0, 0, imagedata 구조체의 width 멤버, 그리고 imagedata 구조체의 height 멤버로 가정해야 합니다.

이 메서드가 호출되었을 때는 다음과 같이 작동해야 합니다:

  1. imagedatadata 속성 값의 [[ViewedArrayBuffer]] 내부 슬롯을 buffer로 설정합니다.

  2. 만약 IsDetachedBuffer(buffer)가 참이라면, "InvalidStateError" DOMException을 던집니다.

  3. 만약 dirtyWidth가 음수라면, dirtyXdirtyX+dirtyWidth로 설정하고, dirtyWidthdirtyWidth의 절대값으로 설정합니다.

    만약 dirtyHeight가 음수라면, dirtyYdirtyY+dirtyHeight로 설정하고, dirtyHeightdirtyHeight의 절대값으로 설정합니다.

  4. 만약 dirtyX가 음수라면, dirtyWidthdirtyWidth+dirtyX로 설정하고, dirtyX를 0으로 설정합니다.

    만약 dirtyY가 음수라면, dirtyHeightdirtyHeight+dirtyY로 설정하고, dirtyY를 0으로 설정합니다.

  5. 만약 dirtyX+dirtyWidthimagedata 인자의 width 속성보다 크다면, dirtyWidth를 해당 width 속성 값에서 dirtyX를 뺀 값으로 설정합니다.

    만약 dirtyY+dirtyHeightimagedata 인자의 height 속성보다 크다면, dirtyHeight를 해당 height 속성 값에서 dirtyY를 뺀 값으로 설정합니다.

  6. 그러한 변경 후에도 dirtyWidth 또는 dirtyHeight가 음수이거나 0인 경우, 비트맵에 아무런 영향을 주지 않고 종료합니다.

  7. dirtyXx < dirtyX+dirtyWidthdirtyYy < dirtyY+dirtyHeight인 모든 정수 xy에 대해, imagedata 데이터 구조의 Canvas Pixel ArrayBuffer에서 (x, y) 좌표를 가진 픽셀의 네 채널을 렌더링 컨텍스트의 (dx+x, dy+y) 좌표를 가진 픽셀에 복사합니다.

색 공간 간의 변환과 프리멀티플라이드 알파 색 값으로의 변환 간의 손실적 특성으로 인해, putImageData()를 사용하여 방금 설정된 픽셀 중 완전히 불투명하지 않은 픽셀은 getImageData()로 동등한 값을 반환할 때 서로 다른 값으로 반환될 수 있습니다.

현재의 경로, 변환 행렬, 그림자 속성, 전역 알파, 클리핑 영역, 현재 합성 및 블렌딩 연산자는 이 섹션에 설명된 메서드에 영향을 미치지 않아야 합니다.

다음 예에서는 스크립트가 그리기 위해 ImageData 객체를 생성하는 과정을 보여줍니다.

// canvas는 <canvas> 요소에 대한 참조입니다
var context = canvas.getContext('2d');

// 빈 캔버스를 만듭니다
var data = context.createImageData(canvas.width, canvas.height);

// 플라즈마를 만듭니다
FillPlasma(data, 'green'); // 초록색 플라즈마

// 플라즈마에 구름을 추가합니다
AddCloud(data, data.width/2, data.height/2); // 가운데에 구름을 추가합니다

// 캔버스에 플라즈마+구름을 그립니다 
context.putImageData(data, 0, 0);

// 지원 메서드 
function FillPlasma(data, color) { ... }
function AddCloud(data, x, y) { ... }

여기에서는 getImageData()putImageData()를 사용하여 에지 검출 필터를 구현하는 예시가 있습니다.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>에지 검출 데모</title>
  <script>
   var image = new Image();
   function init() {
     image.onload = demo;
     image.src = "image.jpeg";
   }
   function demo() {
     var canvas = document.getElementsByTagName('canvas')[0];
     var context = canvas.getContext('2d');

     // 이미지를 캔버스에 그립니다
     context.drawImage(image, 0, 0);

     // 조작할 이미지 데이터를 가져옵니다
     var input = context.getImageData(0, 0, canvas.width, canvas.height);

     // 데이터를 넣을 빈 캔버스를 가져옵니다
     var output = context.createImageData(canvas.width, canvas.height);

     // 편의를 위해 몇 가지 변수를 별칭으로 설정합니다
     // 이 경우 input.width 및 input.height는 canvas.width 및 canvas.height와 일치하지만, 코드를 일반적으로 유지하기 위해 전자를 사용하겠습니다.
     var w = input.width, h = input.height;
     var inputData = input.data;
     var outputData = output.data;

     // 에지 검출 
     for (var y = 1; y < h-1; y += 1) {
       for (var x = 1; x < w-1; x += 1) {
         for (var c = 0; c < 3; c += 1) {
           var i = (y*w + x)*4 + c; 
           outputData[i] = 127 + -inputData[i - w*4 - 4] -   inputData[i - w*4] - inputData[i - w*4 + 4] + 
                                 -inputData[i - 4]       + 8*inputData[i]       - inputData[i + 4] + 
                                 -inputData[i + w*4 - 4] -   inputData[i + w*4] - inputData[i + w*4 + 4]; 
         } 
         outputData[(y*w + x)*4 + 3] = 255; // 알파 
       } 
     }

     // 조작 후 이미지 데이터를 다시 넣습니다 
     context.putImageData(output, 0, 0); 
   } 
  </script>
 </head>
 <body onload="init()"> 
  <canvas></canvas> 
 </body> 
</html>

다음은 단색을 그릴 때와 getImageData()를 사용하여 결과를 다시 읽을 때 적용되는 색 공간 변환의 예시입니다.

<!DOCTYPE HTML>
<html lang="en"> 
<title>색 공간 이미지 데이터 데모</title>

<canvas></canvas>

<script> 
const canvas = document.querySelector('canvas'); 
const context = canvas.getContext('2d', {colorSpace:'display-p3'}); 

// 빨간색 사각형을 그립니다. 이때 16진수 색상 표기법은 sRGB 색상을 지정합니다. 
context.fillStyle = "#FF0000"; 
context.fillRect(0, 0, 64, 64); 

// 이미지 데이터를 가져옵니다. 
const pixels = context.getImageData(0, 0, 1, 1); 

// 이 코드는 'display-p3'를 출력하며, 캔버스의 색 공간에서 이미지 데이터를 반환하는 기본 동작을 반영합니다. 
console.log(pixels.colorSpace); 

// 이 코드는 234, 51, 35 값을 출력하며, 빨간색 채우기가 'display-p3'로 변환된 것을 반영합니다. 
console.log(pixels.data[0]); 
console.log(pixels.data[1]); 
console.log(pixels.data[2]); 
</script>
4.12.5.1.16 합성
context.globalAlpha [ = value ]

CanvasRenderingContext2D/globalAlpha

현재 모든 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

렌더링 작업에 적용되는 현재의 글로벌 알파 값을 반환합니다.

설정할 수 있으며, 글로벌 알파 값을 변경합니다. 0.0에서 1.0 범위를 벗어나는 값은 무시됩니다.

context.globalCompositeOperation [ = value ]

CanvasRenderingContext2D/globalCompositeOperation

현재 모든 엔진에서 지원됩니다.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

현재 합성 및 블렌딩 연산자를 반환합니다. Compositing and Blending에 정의된 값에서 가져옵니다. [COMPOSITE]

설정할 수 있으며, 현재 합성 및 블렌딩 연산자를 변경합니다. 알 수 없는 값은 무시됩니다.

CanvasCompositing 인터페이스를 구현하는 객체는 글로벌 알파 값과 현재 합성 및 블렌딩 연산자 값을 가지며, 이 둘은 이 객체에 대한 모든 그리기 작업에 영향을 미칩니다.

글로벌 알파 값은 도형과 이미지가 출력 비트맵에 합성되기 전에 적용되는 알파 값을 제공합니다. 이 값은 0.0(완전 투명)에서 1.0(추가 투명도 없음)까지 범위에 있으며, 초기값은 1.0이어야 합니다.

globalAlpha getter의 단계는 this글로벌 알파 값을 반환하는 것입니다.

globalAlpha setter의 단계는 다음과 같습니다:

  1. 지정된 값이 무한대, NaN이거나 0.0에서 1.0 범위에 있지 않으면, 아무 작업도 하지 않고 반환합니다.

  2. 그렇지 않으면, this글로벌 알파를 지정된 값으로 설정합니다.

현재 합성 및 블렌딩 연산자 값은 도형과 이미지가 출력 비트맵에 그려지는 방식을 제어합니다. 이 값은 글로벌 알파현재 변환 행렬이 적용된 후에 사용됩니다. 초기값은 "source-over"로 설정해야 합니다.

globalCompositeOperation getter의 단계는 this현재 합성 및 블렌딩 연산자를 반환하는 것입니다.

globalCompositeOperation setter의 단계는 다음과 같습니다:

  1. 지정된 값이 일치하지 않으면 <blend-mode> 또는 <composite-mode> 속성이 정의한 값 중 하나와, 아무 작업도 하지 않고 반환합니다. [COMPOSITE]

  2. 그렇지 않으면, this현재 합성 및 블렌딩 연산자를 지정된 값으로 설정합니다.

4.12.5.1.17 이미지 스무딩
context.imageSmoothingEnabled [ = value ]

CanvasRenderingContext2D/imageSmoothingEnabled

현재 모든 엔진에서 지원됩니다.

Firefox51+Safari9.1+Chrome30+
Opera?Edge79+
Edge (Legacy)15+Internet Explorer🔰 11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

패턴 채우기 및 drawImage() 메서드가 이미지의 픽셀이 정확하게 디스플레이와 정렬되지 않을 때, 스케일링 시 이미지를 스무딩할지 여부를 반환합니다.

설정할 수 있으며, 이미지가 스무딩될지(true) 또는 스무딩되지 않을지(false)를 변경합니다.

context.imageSmoothingQuality [ = value ]

CanvasRenderingContext2D/imageSmoothingQuality

FirefoxNoSafari9.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 이미지 스무딩 품질 설정을 반환합니다.

설정할 수 있으며, 이미지 스무딩의 선호 품질을 변경할 수 있습니다. 가능한 값은 "low", "medium" 및 "high"입니다. 알 수 없는 값은 무시됩니다.

CanvasImageSmoothing 인터페이스를 구현하는 객체는 이미지 스무딩이 수행되는 방식을 제어하는 속성을 가지고 있습니다.

imageSmoothingEnabled 속성은 가져올 때 마지막으로 설정된 값을 반환해야 합니다. 설정할 때는 새 값으로 설정해야 합니다. CanvasImageSmoothing 인터페이스를 구현하는 객체가 생성될 때, 이 속성은 true로 설정되어야 합니다.

imageSmoothingQuality 속성은 가져올 때 마지막으로 설정된 값을 반환해야 합니다. 설정할 때는 새 값으로 설정해야 합니다. CanvasImageSmoothing 인터페이스를 구현하는 객체가 생성될 때, 이 속성은 "low"로 설정되어야 합니다.

4.12.5.1.18 그림자

CanvasShadowStyles 인터페이스를 구현하는 객체에서의 모든 그리기 작업은 네 가지 전역 그림자 속성에 의해 영향을 받습니다.

context.shadowColor [ = value ]

CanvasRenderingContext2D/shadowColor

모든 최신 엔진에서 지원됨.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 그림자 색상을 반환합니다.

그림자 색상을 변경하려면 설정할 수 있습니다. CSS 색상으로 파싱할 수 없는 값은 무시됩니다.

context.shadowOffsetX [ = value ]

CanvasRenderingContext2D/shadowOffsetX

모든 최신 엔진에서 지원됨.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 그림자 오프셋을 반환합니다.

그림자 오프셋을 변경하려면 설정할 수 있습니다. 유한한 숫자가 아닌 값은 무시됩니다.

context.shadowOffsetY [ = value ]

CanvasRenderingContext2D/shadowOffsetY

모든 최신 엔진에서 지원됨.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 그림자 오프셋을 반환합니다.

그림자 오프셋을 변경하려면 설정할 수 있습니다. 유한한 숫자가 아닌 값은 무시됩니다.

context.shadowBlur [ = value ]

CanvasRenderingContext2D/shadowBlur

모든 최신 엔진에서 지원됨.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 그림자에 적용된 흐림 수준을 반환합니다.

흐림 수준을 변경하려면 설정할 수 있습니다. 유한한 숫자가 아니거나 0보다 작은 값은 무시됩니다.

CanvasShadowStyles 인터페이스를 구현하는 객체에는 CSS 색상으로 된 그림자 색상이 있습니다. 처음에는 이 값이 투명한 검정으로 설정됩니다.

shadowColor getter 단계에서는 이 색상의 직렬화된 값을 반환합니다.

shadowColor setter 단계는 다음과 같습니다:

  1. contextthiscanvas 속성 값으로 설정합니다. 해당 값이 요소일 경우에만 해당하며, 그렇지 않으면 null로 설정됩니다.

  2. parsedValue를 주어진 값을 context로 파싱한 결과로 설정합니다.

  3. parsedValue가 실패한 경우, 반환합니다.

  4. this그림자 색상parsedValue로 설정합니다.

shadowOffsetXshadowOffsetY 속성은 각각 양의 수평 및 수직 거리로 그림자가 이동할 거리를 지정합니다. 이 값들은 좌표 공간 단위로 표현되며, 현재 변환 행렬에 영향을 받지 않습니다.

컨텍스트가 생성될 때, 그림자 오프셋 속성은 처음에 0으로 설정되어야 합니다.

이 속성을 가져올 때, 현재 값을 반환해야 합니다. 설정할 때, 설정된 속성은 새 값으로 설정되어야 하며, 그 값이 무한대이거나 NaN인 경우 새 값은 무시되어야 합니다.

shadowBlur 속성은 흐림 효과의 수준을 지정합니다. (이 단위는 좌표 공간 단위와 매핑되지 않으며, 현재 변환 행렬에 영향을 받지 않습니다.)

컨텍스트가 생성될 때, shadowBlur 속성은 처음에 0으로 설정되어야 합니다.

이 속성을 가져올 때, 속성은 현재 값을 반환해야 합니다. 속성을 설정할 때, 속성은 새 값으로 설정되어야 하며, 값이 음수이거나 무한대이거나 NaN인 경우 새 값은 무시되어야 합니다.

그림자는 다음의 경우에만 그려집니다: 그림자 색상의 알파 구성 요소의 불투명도 요소가 0이 아니고 shadowBlur 가 0이 아니거나, shadowOffsetX 가 0이 아니거나, shadowOffsetY 가 0이 아닌 경우에만 그려집니다.

그림자가 그려질 때, 그림자는 다음과 같이 렌더링됩니다:

  1. A를 그림자가 생성되는 원본 이미지가 렌더링된 무한한 투명한 검정 비트맵으로 설정합니다.

  2. BA와 동일한 좌표 공간과 원점을 가진 무한한 투명한 검정 비트맵으로 설정합니다.

  3. A의 알파 채널을 B에 복사하되, shadowOffsetX 에 의해 양의 x 방향으로, shadowOffsetY 에 의해 양의 y 방향으로 오프셋합니다.

  4. shadowBlur 가 0보다 큰 경우:

    1. σshadowBlur 값의 절반으로 설정합니다.

    2. B에 대해 σ를 표준 편차로 사용하는 2D 가우시안 블러를 수행합니다.

    사용자 에이전트는 가우시안 블러 작업 중 하드웨어 제한을 초과하지 않도록 하기 위해 σ 값을 구현별로 특정 최대값으로 제한할 수 있습니다.

  5. B의 모든 픽셀에서 빨강, 초록, 파랑 구성 요소를 그림자 색상의 빨강, 초록, 파랑 구성 요소(각각)로 설정합니다.

  6. B의 모든 픽셀의 알파 구성 요소에 그림자 색상의 알파 구성 요소를 곱합니다.

  7. 그림자는 비트맵 B에 있으며, 아래에 설명된 그리기 모델의 일부로 렌더링됩니다.

현재 합성 및 블렌딩 연산자 가 "copy" 인 경우, 그림자는 실질적으로 렌더링되지 않습니다(모양이 그림자를 덮어쓰기 때문에).

4.12.5.1.19 필터

CanvasFilters 인터페이스를 구현하는 객체의 모든 드로잉 작업은 전역 filter 속성의 영향을 받습니다.

context.filter [ = value ]

CanvasRenderingContext2D/filter

Firefox49+SafariNoChrome52+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 필터를 반환합니다.

설정할 수 있으며, 필터를 변경합니다. 값은 "none" 문자열이거나 <filter-value-list>로 파싱 가능한 문자열이어야 합니다. 다른 값은 무시됩니다.

이러한 객체에는 문자열인 관련 현재 필터가 있습니다. 처음에는 현재 필터가 "none" 문자열로 설정됩니다. 현재 필터 값이 "none" 문자열일 때, 필터는 컨텍스트에 대해 비활성화됩니다.

filter 게터 단계는 this현재 필터를 반환하는 것입니다.

filter 세터 단계는 다음과 같습니다:

  1. 주어진 값이 "none"인 경우, this현재 필터를 "none"으로 설정하고 반환합니다.

  2. parsedValue를 주어진 값을 CSS 구문에 따라 파싱한 결과로 설정합니다. 'inherit' 또는 'initial'과 같은 속성 독립적인 스타일 시트 구문이 존재하는 경우, 이 파싱은 실패를 반환해야 합니다.

  3. parsedValue가 실패인 경우, 반환합니다.

  4. this현재 필터를 주어진 값으로 설정합니다.

context.filter = "none"은 컨텍스트에 대한 필터를 비활성화하지만, context.filter = "", context.filter = nullcontext.filter = undefined는 모두 파싱 불가능한 입력으로 처리되며 현재 필터의 값은 변경되지 않습니다.

현재 필터 값에서 사용된 좌표는 한 픽셀이 하나의 SVG 사용자 공간 단위 및 하나의 캔버스 좌표 공간 단위에 해당하는 것으로 해석됩니다. 필터 좌표는 현재 변환 행렬에 영향을 받지 않습니다. 현재 변환 행렬은 필터의 입력에만 영향을 미칩니다. 필터는 출력 비트맵의 좌표 공간에서 적용됩니다.

현재 필터 값이 백분율 또는 'em' 또는 'ex' 단위를 사용하여 길이를 정의하는 <filter-value-list>로 파싱 가능한 문자열인 경우, 이는 속성이 설정될 때 계산된 값을 기준으로 해석되어야 합니다. 특정 사례에 대해 계산된 값이 정의되지 않은 경우(예: 폰트 스타일 소스 객체가 요소가 아니거나 렌더링되고 있지 않음 때문에), 상대적 키워드는 폰트 속성의 기본값을 기준으로 해석되어야 합니다. 'larger' 및 'smaller' 키워드는 지원되지 않습니다.

현재 필터 값이 동일한 문서의 SVG 필터에 대한 참조를 포함하는 <filter-value-list>로 파싱 가능한 문자열인 경우, 이 SVG 필터가 변경되면 다음 드로잉 작업에서 변경된 필터가 사용됩니다.

현재 필터 값이 외부 리소스 문서의 SVG 필터에 대한 참조를 포함하는 <filter-value-list>로 파싱 가능한 문자열인 경우, 드로잉 작업이 호출될 때 해당 문서가 로드되지 않은 경우, 필터링 없이 드로잉 작업이 진행되어야 합니다.

4.12.5.1.20 외부에서 정의된 SVG 필터 작업

이 섹션은 규범적이지 않습니다.

외부에서 정의된 필터가 로드될 때까지 필터 값 "none"을 사용하여 그리기 작업이 수행되므로, 작성자는 그리기 작업을 진행하기 전에 해당 필터가 로드되었는지 확인하고자 할 수 있습니다. 이를 달성하는 한 가지 방법은 동일한 페이지 내의 다른 요소에서 외부에서 정의된 필터를 로드하고 load 이벤트를 전송하는 요소(예: SVG use 요소)에서 load 이벤트가 발생할 때까지 기다리는 것입니다.

4.12.5.1.21 그리기 모델

도형이나 이미지를 그릴 때, 사용자 에이전트는 다음 순서에 따라 단계를 따르거나 그렇게 하는 것처럼 행동해야 합니다:

  1. 이전 섹션에서 설명한 대로, 무한한 투명한 검정색 비트맵에 도형이나 이미지를 렌더링하여 이미지 A를 생성합니다. 도형의 경우, 현재의 채우기, 획 및 선 스타일이 적용되어야 하며, 획 자체도 현재의 변환 행렬을 적용받아야 합니다.

  2. 현재 필터가 "none"이 아닌 값으로 설정되고, 참조하는 모든 외부에서 정의된 필터가 현재 로드된 문서에 있을 때, 이미지 A현재 필터의 입력으로 사용하여 이미지 B를 생성합니다. 현재 필터<filter-value-list>로 파싱 가능한 문자열인 경우, SVG와 동일한 방식으로 현재 필터를 사용하여 그립니다.

    그렇지 않으면, BA의 별칭으로 사용합니다.

  3. 그림자가 그려질 때, 현재의 그림자 스타일을 사용하여 이미지 B에서 그림자를 렌더링하여 이미지 C를 생성합니다.

  4. 그림자가 그려질 때, C의 모든 픽셀의 알파 성분을 전역 알파로 곱합니다.

  5. 그림자가 그려질 때, 클리핑 영역 내에서 C를 현재의 출력 비트맵 위에 현재의 합성 및 블렌딩 연산자를 사용하여 합성합니다.

  6. B의 모든 픽셀의 알파 성분을 전역 알파로 곱합니다.

  7. B클리핑 영역 내에서 현재의 출력 비트맵 위에 현재의 합성 및 블렌딩 연산자를 사용하여 합성합니다.

출력 비트맵에 합성할 때, 출력 비트맵 외부에 속할 픽셀은 버려야 합니다.

4.12.5.1.22 모범 사례

캔버스가 상호작용할 수 있을 때, 작성자는 각 포커스 가능한 캔버스의 부분에 해당하는 포커스 가능한 요소를 요소의 대체 콘텐츠에 포함해야 합니다. 위의 예제에서와 같이.

포커스 링을 렌더링할 때, 포커스 링이 네이티브 포커스 링처럼 보이도록 하기 위해 작성자는 포커스 링을 그릴 요소를 전달하여 drawFocusIfNeeded() 메서드를 사용해야 합니다. 이 메서드는 요소가 포커스된 경우에만 포커스 링을 그리므로, 요소를 그릴 때마다 먼저 요소가 포커스되었는지 여부를 확인하지 않고도 이 메서드를 호출할 수 있습니다.

작성자는 캔버스 요소를 사용하여 텍스트 편집 컨트롤을 구현하는 것을 피해야 합니다. 이렇게 하는 것은 다음과 같은 많은 단점이 있습니다:

이 작업은 엄청난 양의 작업이므로, 작성자는 대신 입력 요소, 텍스트 영역 요소 또는 contenteditable 속성을 사용하여 이 작업을 피할 것을 강력히 권장합니다.

4.12.5.1.23 예제

이 섹션은 비규범적입니다.

다음은 캔버스를 사용하여 예쁜 빛나는 선을 그리는 스크립트의 예제입니다.

<canvas width="800" height="450"></canvas>
<script>

 var context = document.getElementsByTagName('canvas')[0].getContext('2d');

 var lastX = context.canvas.width * Math.random();
 var lastY = context.canvas.height * Math.random();
 var hue = 0;
 function line() {
   context.save();
   context.translate(context.canvas.width/2, context.canvas.height/2);
   context.scale(0.9, 0.9);
   context.translate(-context.canvas.width/2, -context.canvas.height/2);
   context.beginPath();
   context.lineWidth = 5 + Math.random() * 10;
   context.moveTo(lastX, lastY);
   lastX = context.canvas.width * Math.random();
   lastY = context.canvas.height * Math.random();
   context.bezierCurveTo(context.canvas.width * Math.random(),
                         context.canvas.height * Math.random(),
                         context.canvas.width * Math.random(),
                         context.canvas.height * Math.random(),
                         lastX, lastY);

   hue = hue + 10 * Math.random();
   context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';
   context.shadowColor = 'white';
   context.shadowBlur = 10;
   context.stroke();
   context.restore();
 }
 setInterval(line, 50);

 function blank() {
   context.fillStyle = 'rgba(0,0,0,0.1)';
   context.fillRect(0, 0, context.canvas.width, context.canvas.height);
 }
 setInterval(blank, 40);

</script>

캔버스의 2D 렌더링 컨텍스트는 종종 스프라이트 기반 게임에 사용됩니다. 다음 예제는 이를 보여줍니다:

다음은 이 예제의 소스입니다:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Blue Robot Demo</title>
<style>
  html { overflow: hidden; min-height: 200px; min-width: 380px; }
  body { height: 200px; position: relative; margin: 8px; }
  .buttons { position: absolute; bottom: 0px; left: 0px; margin: 4px; }
</style>
<canvas width="380" height="200"></canvas>
<script>
 var Landscape = function (context, width, height) {
   this.offset = 0;
   this.width = width;
   this.advance = function (dx) {
     this.offset += dx;
   };
   this.horizon = height * 0.7;
   // This creates the sky gradient (from a darker blue to white at the bottom)
   this.sky = context.createLinearGradient(0, 0, 0, this.horizon);
   this.sky.addColorStop(0.0, 'rgb(55,121,179)');
   this.sky.addColorStop(0.7, 'rgb(121,194,245)');
   this.sky.addColorStop(1.0, 'rgb(164,200,214)');
   // this creates the grass gradient (from a darker green to a lighter green)
   this.earth = context.createLinearGradient(0, this.horizon, 0, height);
   this.earth.addColorStop(0.0, 'rgb(81,140,20)');
   this.earth.addColorStop(1.0, 'rgb(123,177,57)');
   this.paintBackground = function (context, width, height) {
     // first, paint the sky and grass rectangles
     context.fillStyle = this.sky;
     context.fillRect(0, 0, width, this.horizon);
     context.fillStyle = this.earth;
     context.fillRect(0, this.horizon, width, height-this.horizon);
     // then, draw the cloudy banner
     // we make it cloudy by having the draw text off the top of the
     // canvas, and just having the blurred shadow shown on the canvas
     context.save();
     context.translate(width-((this.offset+(this.width*3.2)) % (this.width*4.0))+0, 0);
     context.shadowColor = 'white';
     context.shadowOffsetY = 30+this.horizon/3; // offset down on canvas
     context.shadowBlur = '5';
     context.fillStyle = 'white';
     context.textAlign = 'left';
     context.textBaseline = 'top';
     context.font = '20px sans-serif';
     context.fillText('WHATWG ROCKS', 10, -30); // text up above canvas
     context.restore();
     // then, draw the background tree
     context.save();
     context.translate(width-((this.offset+(this.width*0.2)) % (this.width*1.5))+30, 0);
     context.beginPath();
     context.fillStyle = 'rgb(143,89,2)';
     context.lineStyle = 'rgb(10,10,10)';
     context.lineWidth = 2;
     context.rect(0, this.horizon+5, 10, -50); // trunk
     context.fill();
     context.stroke();
     context.beginPath();
     context.fillStyle = 'rgb(78,154,6)';
     context.arc(5, this.horizon-60, 30, 0, Math.PI*2); // leaves
     context.fill();
     context.stroke();
     context.restore();
   };
   this.paintForeground = function (context, width, height) {
     // draw the box that goes in front
     context.save();
     context.translate(width-((this.offset+(this.width*0.7)) % (this.width*1.1))+0, 0);
     context.beginPath();
     context.rect(0, this.horizon - 5, 25, 25);
     context.fillStyle = 'rgb(220,154,94)';
     context.lineStyle = 'rgb(10,10,10)';
     context.lineWidth = 2;
     context.fill();
     context.stroke();
     context.restore();
   };
 };
</script>
</script>
<script>
 var canvas = document.getElementsByTagName('canvas')[0];
 var context = canvas.getContext('2d');
 var landscape = new Landscape(context, canvas.width, canvas.height);
 var blueRobot = new BlueRobot();
 // paint when the browser wants us to, using requestAnimationFrame()
 function paint() {
   context.clearRect(0, 0, canvas.width, canvas.height);
   landscape.paintBackground(context, canvas.width, canvas.height);
   blueRobot.paint(context, canvas.width/2, landscape.horizon*1.1);
   landscape.paintForeground(context, canvas.width, canvas.height);
   requestAnimationFrame(paint);
 }
 paint();
 // but tick every 100ms, so that we don't slow down when we don't paint
 setInterval(function () {
   var dx = blueRobot.tick();
   landscape.advance(dx);
 }, 100);
</script>
<p class="buttons">
 <input type=button value="Walk" onclick="blueRobot.walk()">
 <input type=button value="Stop" onclick="blueRobot.stop()">
</footer>
 <small> Blue Robot Player Sprite by <a href="https://johncolburn.deviantart.com/">JohnColburn</a>.
 Licensed under the terms of the Creative Commons Attribution Share-Alike 3.0 Unported license.</small>
 <small> This work is itself licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/3.0/">Creative
 Commons Attribution-ShareAlike 3.0 Unported License</a>.</small>
</footer>
4.12.5.2 ImageBitmap 렌더링 컨텍스트
4.12.5.2.1 소개

ImageBitmapRenderingContextdrawImage() 메서드와 달리 중간 합성을 피함으로써 성능을 향상시키는 저비용 방법으로 ImageBitmap 객체의 내용을 표시할 수 있는 성능 지향 인터페이스입니다. 전송 의미를 사용하여 전체 메모리 소비를 줄이며 성능을 최적화합니다.

예를 들어, 이미지를 캔버스에 가져오기 위한 중간 단계로 img 요소를 사용하는 경우, 메모리에 디코딩된 이미지의 두 개의 복사본이 동시에 존재하게 됩니다: img 요소의 복사본과 캔버스의 백업 저장소에 있는 복사본입니다. 이러한 메모리 비용은 매우 큰 이미지 작업 시 부담이 될 수 있습니다. ImageBitmapRenderingContext를 사용하여 이를 피할 수 있습니다.

ImageBitmapRenderingContext를 사용하여 메모리와 CPU를 효율적으로 사용하는 방식으로 이미지를 JPEG 형식으로 트랜스코딩하는 예제는 다음과 같습니다:

createImageBitmap(inputImageBlob).then(image => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('bitmaprenderer');
  context.transferFromImageBitmap(image);

  canvas.toBlob(outputJPEGBlob => {
    // outputJPEGBlob으로 작업을 수행합니다.
  }, 'image/jpeg');
});
4.12.5.2.2 ImageBitmapRenderingContext 인터페이스

ImageBitmapRenderingContext

모든 최신 엔진에서 지원됩니다.

Firefox46+Safari11.1+Chrome66+
Opera?Edge79+
Edge (레거시)?Internet Explorer미지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=(Window,Worker)]
interface ImageBitmapRenderingContext {
  readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;
  undefined transferFromImageBitmap(ImageBitmap? bitmap);
};

dictionary ImageBitmapRenderingContextSettings {
  boolean alpha = true;
};
context = canvas.getContext('bitmaprenderer' [, { [ alpha: false ] } ])

ImageBitmapRenderingContext 객체를 반환하며, 이 객체는 특정 캔버스 요소에 영구적으로 바인딩됩니다.

만약 alpha 설정이 제공되고 false로 설정된 경우, 캔버스는 항상 불투명하도록 강제됩니다.

context.canvas

컨텍스트가 바인딩된 캔버스 요소를 반환합니다.

context.transferFromImageBitmap(imageBitmap)

ImageBitmapRenderingContext/transferFromImageBitmap

모든 최신 엔진에서 지원됩니다.

Firefox50+Safari11.1+Chrome66+
Opera?Edge79+
Edge (레거시)?Internet Explorer미지원
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

imageBitmap의 기저 비트맵 데이터context로 이전하며, 비트맵이 캔버스 요소의 내용이 됩니다.

context.transferFromImageBitmap(null)

context가 바인딩된 캔버스 요소의 내용을 투명한 검정 비트맵으로 교체하며, 해당 비트맵의 크기는 widthheight 콘텐츠 속성과 동일합니다.

canvas 속성은 객체가 생성될 때 초기화된 값을 반환해야 합니다.

ImageBitmapRenderingContext 객체는 출력 비트맵을 가지고 있으며, 이는 비트맵 데이터에 대한 참조입니다.

ImageBitmapRenderingContext 객체는 또한 비트맵 모드를 가지고 있으며, 이는 유효 또는 공백으로 설정될 수 있습니다. 유효 상태는 컨텍스트의 출력 비트맵transferFromImageBitmap()을 통해 획득된 비트맵 데이터에 해당함을 나타냅니다. 공백 상태는 컨텍스트의 출력 비트맵이 기본 투명 비트맵임을 나타냅니다.

ImageBitmapRenderingContext 객체는 또한 알파 플래그를 가지고 있으며, 이는 true 또는 false로 설정될 수 있습니다. ImageBitmapRenderingContext 객체의 알파 플래그가 false로 설정되면, 컨텍스트에 바인딩된 캔버스 요소의 내용은 동일한 크기의 불투명한 검정 비트맵에 컨텍스트의 출력 비트맵을 합성하여 얻습니다. [COMPOSITE]

동등한 결과를 더 효율적으로 얻을 수 있는 경우, 불투명한 검정 비트맵에 합성하는 단계는 생략되어야 합니다.


사용자 에이전트가 ImageBitmapRenderingContext의 출력 비트맵을 설정해야 하는 경우, context 인수로 ImageBitmapRenderingContext 객체를 전달하고, 선택적 인수로 bitmap비트맵 데이터를 참조하는 경우, 다음 단계를 실행해야 합니다:

  1. 만약 bitmap 인수가 제공되지 않은 경우:

    1. context비트맵 모드공백으로 설정합니다.

    2. canvascontext에 바인딩된 캔버스 요소로 설정합니다.

    3. context출력 비트맵투명 검정으로 설정하고, 자연 너비숫자 값으로, canvas너비 속성과 동일하게 설정하고, 자연 높이숫자 값으로, canvas높이 속성과 동일하게 설정합니다. 이 값들은 CSS 픽셀로 해석됩니다.

    4. context출력 비트맵원산지-청정 플래그를 true로 설정합니다.

  2. 만약 bitmap 인수가 제공된 경우:

    1. context비트맵 모드유효로 설정합니다.

    2. context출력 비트맵bitmap과 동일한 기저 비트맵 데이터를 참조하도록 설정하며, 복사를 수행하지 않습니다.

      bitmap원산지-청정 플래그는 context출력 비트맵이 참조할 비트맵 데이터에 포함됩니다.


ImageBitmapRenderingContext 생성 알고리즘targetoptions을 전달받으며, 다음 단계를 실행합니다:

  1. settingsImageBitmapRenderingContextSettings 딕셔너리 타입으로 변환한 결과로 설정합니다.

  2. context를 새로운 ImageBitmapRenderingContext 객체로 설정합니다.

  3. contextcanvas 속성을 target으로 초기화합니다.

  4. context출력 비트맵target의 비트맵과 동일하게 설정합니다 (따라서 공유됨).

  5. context를 인수로 하여 ImageBitmapRenderingContext의 출력 비트맵을 설정하는 단계를 실행합니다.

  6. context알파 플래그를 true로 초기화합니다.

  7. settings의 각 구성원을 다음과 같이 처리합니다:

    alpha
    만약 false인 경우, context알파 플래그를 false로 설정합니다.
  8. context를 반환합니다.


transferFromImageBitmap(bitmap) 메서드가 호출되면, 다음 단계를 실행해야 합니다:

  1. bitmapContextImageBitmapRenderingContext 객체로 설정합니다.

  2. 만약 bitmap이 null인 경우, ImageBitmapRenderingContext의 출력 비트맵을 설정하는 단계를 bitmapContextcontext 인수로 하고, bitmap 인수를 제공하지 않고 실행한 후, 반환합니다.

  3. 만약 bitmap[[Detached]] 내부 슬롯이 true로 설정된 경우, "InvalidStateError" DOMException을 발생시킵니다.

  4. context 인수를 bitmapContext로 하고, bitmap 인수가 bitmap의 기저 비트맵 데이터를 참조하도록 하여 ImageBitmapRenderingContext의 출력 비트맵을 설정하는 단계를 실행합니다.

  5. bitmap[[Detached]] 내부 슬롯을 true로 설정합니다.

  6. bitmap비트맵 데이터를 해제합니다.

4.12.5.3 OffscreenCanvas 인터페이스

OffscreenCanvas

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
typedef (OffscreenCanvasRenderingContext2D 또는 ImageBitmapRenderingContext 또는 WebGLRenderingContext 또는 WebGL2RenderingContext 또는 GPUCanvasContext) OffscreenRenderingContext;

dictionary ImageEncodeOptions {
  DOMString type = "image/png";
  unrestricted double quality;
};

enum OffscreenRenderingContextId { "2d", "bitmaprenderer", "webgl", "webgl2", "webgpu" };

[Exposed=(Window,Worker), Transferable]
interface OffscreenCanvas : EventTarget {
  constructor([EnforceRange] unsigned long long width, [EnforceRange] unsigned long long height);

  attribute [EnforceRange] unsigned long long width;
  attribute [EnforceRange] unsigned long long height;

  OffscreenRenderingContext? getContext(OffscreenRenderingContextId contextId, optional any options = null);
  ImageBitmap transferToImageBitmap();
  Promise<Blob> convertToBlob(optional ImageEncodeOptions options = {});

  attribute EventHandler oncontextlost;
  attribute EventHandler oncontextrestored;
};

OffscreenCanvasEventTarget 이므로, OffscreenCanvasRenderingContext2D 및 WebGL이 이벤트를 발생시킬 수 있습니다. OffscreenCanvasRenderingContext2Dcontextlostcontextrestored 를 발생시킬 수 있으며, WebGL은 webglcontextlostwebglcontextrestored를 발생시킬 수 있습니다. [WEBGL]

OffscreenCanvas 객체는 HTMLCanvasElement 와 유사하게 렌더링 컨텍스트를 생성하는 데 사용되지만, DOM과 연결되지 않습니다. 이를 통해 workers에서 캔버스 렌더링 컨텍스트를 사용할 수 있습니다.

OffscreenCanvas 객체는 플레이스홀더 canvas 요소에 대한 약한 참조를 보유할 수 있으며, 이는 일반적으로 DOM에 있으며, 포함된 콘텐츠는 OffscreenCanvas 객체에서 제공합니다. OffscreenCanvas 객체의 비트맵은 플레이스홀더 canvas 요소로 푸시되며, OffscreenCanvas관련 에이전트이벤트 루프렌더링 업데이트 단계에서 이루어집니다.

offscreenCanvas = new OffscreenCanvas(width, height)

OffscreenCanvas/OffscreenCanvas

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

새로운 OffscreenCanvas 객체를 반환하며, 이는 플레이스홀더 canvas 요소와 연결되어 있지 않으며, 비트맵의 크기는 widthheight 인수에 따라 결정됩니다.

context = offscreenCanvas.getContext(contextId [, options ])

OffscreenCanvas/getContext

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

OffscreenCanvas 객체에서 드로잉할 수 있는 API를 노출하는 객체를 반환합니다. contextId는 원하는 API를 지정합니다: "2d", "bitmaprenderer", "webgl", "webgl2", 또는 "webgpu". options는 해당 API에서 처리됩니다.

캔버스가 이미 다른 컨텍스트 유형으로 초기화된 경우(예: "2d" 컨텍스트를 가져온 후에 "webgl" 컨텍스트를 가져오려는 경우) null을 반환합니다.

OffscreenCanvas 객체는 비트맵을 내부적으로 가지고 있으며, 객체가 생성될 때 초기화됩니다. 비트맵의 너비와 높이는 widthheight 속성의 값과 동일합니다. 초기에는 비트맵의 모든 픽셀이 투명한 검정색입니다.

OffscreenCanvas 객체는 렌더링 컨텍스트가 바인딩될 수 있습니다. 초기에는 바인딩된 렌더링 컨텍스트가 없습니다. 렌더링 컨텍스트가 있는지 여부와 어떤 유형의 렌더링 컨텍스트인지 추적하기 위해 OffscreenCanvas 객체는 컨텍스트 모드도 가지고 있으며, 초기에는 none이지만, 이 사양에 정의된 알고리즘에 따라 2d, bitmaprenderer, webgl, webgl2, webgpu, 또는 detached 로 변경될 수 있습니다.

생성자 OffscreenCanvas(width, height)가 호출될 때, OffscreenCanvas 객체를 새로 생성하며, 비트맵widthheight로 지정된 크기의 투명한 검정색 픽셀의 직사각형 배열로 초기화되며, widthheight 속성도 각각 widthheight로 초기화됩니다.


OffscreenCanvas 객체는 전송 가능합니다. 전송 단계valuedataHolder에 대해 다음과 같이 진행됩니다:

  1. 만약 value컨텍스트 모드none과 같지 않다면, "InvalidStateError" DOMException을 발생시킵니다.

  2. value컨텍스트 모드detached로 설정합니다.

  3. widthheightvalue비트맵의 크기로 설정합니다.

  4. value비트맵을 해제합니다.

  5. dataHolder의 [[Width]]를 width로, [[Height]]를 height로 설정합니다.

  6. 만약 value가 하나 가지고 있다면, dataHolder의 [[PlaceholderCanvas]]를 value플레이스홀더 캔버스 요소에 대한 약한 참조로 설정하거나, 그렇지 않다면 null로 설정합니다.

전송 수신 단계dataHoldervalue에 대해 다음과 같이 진행됩니다:

  1. value비트맵dataHolder의 [[Width]] 및 [[Height]]에 의해 지정된 크기의 투명한 검정색 픽셀의 직사각형 배열로 초기화합니다.

  2. 만약 dataHolder의 [[PlaceholderCanvas]]가 null이 아니면, value플레이스홀더 canvas 요소dataHolder의 [[PlaceholderCanvas]]로 설정합니다(약한 참조 의미를 유지하면서).


getContext(contextId, options) 메서드는 OffscreenCanvas 객체에서 호출될 때, 다음 단계들을 실행해야 합니다:

  1. options객체가 아니라면, options을 null로 설정합니다.

  2. options변환하여 JavaScript 값으로 설정합니다.

  3. OffscreenCanvas 객체의 컨텍스트 모드contextId가 일치하는 다음 표의 셀에 있는 단계를 실행합니다:

    none 2d bitmaprenderer webgl 또는 webgl2 webgpu detached
    "2d"
    1. context오프스크린 2D 컨텍스트 생성 알고리즘을 사용하여 thisoptions으로 설정합니다.

    2. this컨텍스트 모드2d로 설정합니다.

    3. context를 반환합니다.

    이 메서드가 동일한 첫 번째 인수로 호출되었을 때 마지막으로 반환된 동일한 객체를 반환합니다. null을 반환합니다. null을 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 던집니다.
    "bitmaprenderer"
    1. contextImageBitmapRenderingContext 생성 알고리즘을 사용하여 thisoptions으로 설정합니다.

    2. this컨텍스트 모드bitmaprenderer로 설정합니다.

    3. context를 반환합니다.

    null을 반환합니다. 이 메서드가 동일한 첫 번째 인수로 호출되었을 때 마지막으로 반환된 동일한 객체를 반환합니다. null을 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 던집니다.
    "webgl" 또는 "webgl2"
    1. context를 WebGL 사양의 컨텍스트 생성 섹션에 제공된 지침에 따라 설정합니다. [WEBGL]

    2. context가 null이면 null을 반환하고, 그렇지 않으면 this컨텍스트 모드webgl 또는 webgl2로 설정합니다.

    3. context를 반환합니다.

    null을 반환합니다. null을 반환합니다. 이 메서드가 동일한 첫 번째 인수로 호출되었을 때 마지막으로 반환된 동일한 값을 반환합니다. null을 반환합니다. "InvalidStateError" DOMException을 던집니다.
    "webgpu"
    1. contextWebGPU캔버스 렌더링 섹션에서 제공된 지침에 따라 설정합니다. [WEBGPU]

    2. context가 null이면 null을 반환하고, 그렇지 않으면 this컨텍스트 모드webgpu로 설정합니다.

    3. context를 반환합니다.

    null을 반환합니다. null을 반환합니다. null을 반환합니다. 이 메서드가 동일한 첫 번째 인수로 호출되었을 때 마지막으로 반환된 동일한 값을 반환합니다. "InvalidStateError" DOMException을 던집니다.

offscreenCanvas.width [ = value ]

OffscreenCanvas/width

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
offscreenCanvas.height [ = value ]

OffscreenCanvas/height

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

이 속성들은 OffscreenCanvas 객체의 비트맵의 크기를 반환합니다.

이 속성들은 설정할 수 있으며, 지정된 크기의 새로운 투명한 검은색 비트맵으로 비트맵을 대체합니다 (실제로 크기를 조정합니다).

만약 OffscreenCanvas 객체의 width 또는 height 속성 중 하나라도 설정되면(새 값으로 또는 이전과 동일한 값으로) OffscreenCanvas 객체의 context mode2d이면, 렌더링 컨텍스트를 기본 상태로 재설정하고 OffscreenCanvas 객체의 비트맵을 width와 height 속성의 새 값으로 크기 조정합니다.

"webgl" 및 "webgl2" 컨텍스트의 크기 조정 동작은 WebGL 명세에서 정의되어 있습니다. [WEBGL]

"webgpu" 컨텍스트의 크기 조정 동작은 WebGPU에서 정의되어 있습니다. [WEBGPU]

크기가 변경된 OffscreenCanvas 객체에 플레이스홀더 canvas 요소가 있는 경우, 그 플레이스홀더 canvas 요소의 자연 크기는 해당 OffscreenCanvas관련 에이전트이벤트 루프렌더링 업데이트 단계에서만 업데이트됩니다.

promise = offscreenCanvas.convertToBlob([options])

OffscreenCanvas/convertToBlob

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

이 메서드는 Blob 객체로 이루어진 파일을 생성하며, OffscreenCanvas 객체에 포함된 이미지를 담고 있습니다.

인자로 전달된 객체는 생성될 이미지 파일의 인코딩 옵션을 제어하는 사전(dictionary)입니다. type 필드는 파일 형식을 지정하며 기본값은 "image/png"입니다. 요청된 형식이 지원되지 않으면 이 형식이 사용됩니다. 이미지 형식이 가변 품질을 지원하는 경우(예: "image/jpeg"), quality 필드는 0.0에서 1.0까지의 범위 내에서 결과 이미지의 품질 수준을 나타내는 숫자입니다.

canvas.transferToImageBitmap()

OffscreenCanvas/transferToImageBitmap

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

이 메서드는 ImageBitmap 객체를 새로 생성하여 OffscreenCanvas 객체에 저장된 이미지를 사용합니다. OffscreenCanvas 객체에 저장된 이미지는 새로운 빈 이미지로 대체됩니다.

convertToBlob(options) 메서드는 호출될 때 다음 단계를 실행해야 합니다:

  1. OffscreenCanvas 객체의 [[Detached]] 내부 슬롯 값이 true로 설정되어 있으면, 거부된 약속(promise)을 반환하고, "InvalidStateError" DOMException을 반환합니다.

  2. OffscreenCanvas 객체의 컨텍스트 모드2d 이고, 렌더링 컨텍스트의 비트맵(bitmap)원점 클린(origin-clean) 플래그가 false로 설정되어 있으면, 거부된 약속(promise)을 반환하고 "SecurityError" DOMException을 반환합니다.

  3. OffscreenCanvas 객체의 비트맵(bitmap)에 픽셀이 없으면 (즉, 가로 또는 세로 차원이 0이면), 거부된 약속(promise)을 반환하고, "IndexSizeError" DOMException을 반환합니다.

  4. bitmap을 이 OffscreenCanvas 객체의 비트맵(bitmap)의 복사본으로 만듭니다.

  5. result를 새로운 약속(promise) 객체로 만듭니다.

  6. 이 단계를 병렬로 실행합니다:

    1. file비트맵의 파일로의 직렬화(serialization)로 설정하고, optionstypequality가 있으면 사용합니다.

    2. 요소 작업을 큐(queue)에 추가하고, 캔버스 블롭 직렬화 작업 소스에서 캔버스(canvas) 요소를 대상으로 이 단계를 실행합니다:

      1. 만약 file이 null이면, result"EncodingError" DOMException로 거부합니다.

      2. 그렇지 않으면, 이 OffscreenCanvas 객체의 관련 영역(relevant realm)에서 file을 나타내는 새로운 Blob 객체로 result를 해결(resolve)합니다. [FILEAPI]

  7. result를 반환합니다.

transferToImageBitmap() 메서드는 호출될 때 다음 단계를 실행해야 합니다:

  1. OffscreenCanvas 객체의 [[Detached]] 내부 슬롯 값이 true로 설정되어 있으면, "InvalidStateError" DOMException을 발생시킵니다.

  2. OffscreenCanvas 객체의 컨텍스트 모드none으로 설정되어 있으면, "InvalidStateError" DOMException을 발생시킵니다.

  3. image를 새로 생성된 ImageBitmap 객체로 설정하고, 이 OffscreenCanvas 객체의 비트맵과 동일한 기본 비트맵 데이터를 참조하도록 합니다.

  4. OffscreenCanvas 객체의 비트맵을 새로 생성된 동일한 차원 및 색상 공간의 비트맵을 참조하도록 설정하고, 픽셀은 투명한 검정색 또는 렌더링 컨텍스트의 알파 플래그가 false로 설정되어 있으면 불투명한 검정색으로 초기화합니다.

    이것은 이 OffscreenCanvas 의 렌더링 컨텍스트가 WebGLRenderingContext인 경우, preserveDrawingBuffer의 값이 영향을 미치지 않음을 의미합니다. [WEBGL]

  5. image를 반환합니다.

다음은 이벤트 핸들러 (및 해당 이벤트 핸들러 이벤트 유형) 이며, 이벤트 핸들러 IDL 속성으로 지원되어야 하는 모든 객체는 OffscreenCanvas 인터페이스를 구현해야 합니다:

이벤트 핸들러 이벤트 핸들러 이벤트 유형
oncontextlost contextlost
oncontextrestored contextrestored
4.12.5.3.1 오프스크린 2D 렌더링 컨텍스트

OffscreenCanvasRenderingContext2D

모든 현재 엔진에서 지원됩니다.

Firefox105+Safari16.4+Chrome69+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=(Window,Worker)]
interface OffscreenCanvasRenderingContext2D {
  readonly attribute OffscreenCanvas canvas;
};

OffscreenCanvasRenderingContext2D includes CanvasState;
OffscreenCanvasRenderingContext2D includes CanvasTransform;
OffscreenCanvasRenderingContext2D includes CanvasCompositing;
OffscreenCanvasRenderingContext2D includes CanvasImageSmoothing;
OffscreenCanvasRenderingContext2D includes CanvasFillStrokeStyles;
OffscreenCanvasRenderingContext2D includes CanvasShadowStyles;
OffscreenCanvasRenderingContext2D includes CanvasFilters;
OffscreenCanvasRenderingContext2D includes CanvasRect;
OffscreenCanvasRenderingContext2D includes CanvasDrawPath;
OffscreenCanvasRenderingContext2D includes CanvasText;
OffscreenCanvasRenderingContext2D includes CanvasDrawImage;
OffscreenCanvasRenderingContext2D includes CanvasImageData;
OffscreenCanvasRenderingContext2D includes CanvasPathDrawingStyles;
OffscreenCanvasRenderingContext2D includes CanvasTextDrawingStyles;
OffscreenCanvasRenderingContext2D includes CanvasPath;

OffscreenCanvasRenderingContext2D 객체는 비트맵에 그림을 그리기 위한 렌더링 컨텍스트로서 OffscreenCanvas 객체의 비트맵에 그립니다. 이는 CanvasRenderingContext2D 객체와 유사하지만, 다음과 같은 차이점이 있습니다:

OffscreenCanvasRenderingContext2D 객체에는 객체가 생성될 때 초기화되는 비트맵이 있습니다.

비트맵에는 true 또는 false로 설정할 수 있는 원점 클린 플래그가 있습니다. 이러한 비트맵 중 하나가 생성될 때, 그 원점 클린 플래그는 true로 설정되어야 합니다.

OffscreenCanvasRenderingContext2D 객체에는 true 또는 false로 설정할 수 있는 알파 플래그도 있습니다. 처음에는 컨텍스트가 생성될 때 알파 플래그가 true로 설정되어야 합니다. OffscreenCanvasRenderingContext2D 객체의 알파 플래그가 false로 설정되면, 알파 채널은 모든 픽셀에 대해 1.0(완전히 불투명)으로 고정되어야 하며, 모든 픽셀의 알파 구성 요소를 변경하려는 시도는 조용히 무시되어야 합니다.

OffscreenCanvasRenderingContext2D 객체에는 색상 공간 설정이 있으며, 이는 사전 정의된 색상 공간 유형입니다. 컨텍스트의 비트맵의 색상 공간은 컨텍스트의 색상 공간으로 설정됩니다.

OffscreenCanvasRenderingContext2D 객체에는 관련된 OffscreenCanvas 객체도 있으며, 이는 OffscreenCanvas 객체로부터 OffscreenCanvasRenderingContext2D 객체가 생성되었습니다.

offscreenCanvas = offscreenCanvasRenderingContext2D.canvas

관련된 OffscreenCanvas 객체를 반환합니다.

오프스크린 2D 컨텍스트 생성 알고리즘은, target ( OffscreenCanvas 객체)과 선택적으로 몇 가지 인수를 전달받고, 다음 단계를 실행합니다:

  1. 알고리즘이 몇 가지 인수를 전달받은 경우, arg를 첫 번째 인수로 설정합니다. 그렇지 않으면 arg를 undefined로 설정합니다.

  2. settingsarg를 사전으로 변환한 결과로 설정합니다. (이 작업은 예외를 발생시킬 수 있습니다).

  3. context를 새 OffscreenCanvasRenderingContext2D 객체로 설정합니다.

  4. context관련된 OffscreenCanvas 객체target으로 설정합니다.

  5. 만약 settings["alpha"]가 false인 경우, context알파 플래그를 false로 설정합니다.

  6. context색상 공간settings["colorSpace"]로 설정합니다.

  7. context비트맵을 새로 생성된 비트맵으로 설정하고, 그 비트맵의 차원은 widthheight 속성에 지정된 대로 target에 설정합니다. 그런 다음 target의 비트맵을 동일한 비트맵으로 설정합니다(이들이 공유되도록 설정).

  8. 만약 context알파 플래그가 true로 설정된 경우, context비트맵의 모든 픽셀을 투명한 검정색으로 초기화합니다. 그렇지 않으면 픽셀을 불투명한 검정색으로 초기화합니다.

  9. context를 반환합니다.

구현은 플레이스홀더 캔버스 요소의 내용을 디스플레이에 업데이트하는 목적으로 창 이벤트 루프의 그래픽 업데이트 단계를 단축하도록 권장됩니다. 예를 들어, 비트맵 내용이 플레이스홀더 캔버스 요소의 물리적 디스플레이 위치에 매핑된 그래픽 버퍼로 직접 복사될 수 있습니다. 이와 같은 단축 방법은 특히 워커 이벤트 루프에서 OffscreenCanvas가 업데이트되고, 창 이벤트 루프플레이스홀더 캔버스 요소에서 바쁠 때 디스플레이 지연 시간을 크게 줄일 수 있습니다. 그러나 그러한 단축 방법은 스크립트에 의해 관찰 가능한 부작용이 없어야 합니다. 즉, 커밋된 비트맵은 여전히 플레이스홀더 캔버스 요소로 전송되어야 하며, 해당 요소가 CanvasImageSource, ImageBitmapSource, 또는 toDataURL() 또는 toBlob()이 호출될 경우에 사용될 수 있습니다.

canvas 속성은 이 OffscreenCanvasRenderingContext2D관련된 OffscreenCanvas 객체를 반환해야 합니다.

4.12.5.4 색상 공간과 색상 공간 변환

캔버스 API는 캔버스의 백업 저장소의 색상 공간을 지정하는 메커니즘을 제공합니다. 모든 캔버스 API의 기본 백업 저장소 색상 공간은 'srgb'입니다.

캔버스를 출력 장치에 렌더링할 때, 색상 공간 변환이 캔버스의 백업 저장소에 적용되어야 합니다. 이 색상 공간 변환은 색상 프로필이 동일한 색상 공간을 지정하는 img 요소에 적용되는 색상 공간 변환과 동일해야 합니다.

2D 컨텍스트에 콘텐츠를 그릴 때, 모든 입력은 그리기 전에 컨텍스트의 색상 공간으로 변환되어야 합니다. 그라디언트 색상 중지점의 보간은 컨텍스트의 색상 공간으로 변환된 후의 색상 값에 대해 수행되어야 합니다. 알파 블렌딩은 컨텍스트의 색상 공간으로 변환된 후의 값에 대해 수행되어야 합니다.

2D 컨텍스트에 대한 입력 중에서 색상 공간이 정의되지 않은 것은 존재하지 않습니다. CSS 색상의 색상 공간은 CSS Color에서 정의됩니다. 색상 프로필 정보를 지정하지 않는 이미지의 색상 공간은 'srgb'로 간주되며, 이는 CSS Color태그되지 않은 색상의 색상 공간 섹션에 명시되어 있습니다. [CSSCOLOR]

4.12.5.5 비트맵을 파일로 직렬화

사용자 에이전트가 주어진 type과 선택적 quality에 따라 비트맵을 파일로 직렬화할 때, type에 지정된 형식으로 이미지 파일을 생성해야 합니다. 이미지 파일 생성 중 오류가 발생하면 (예: 내부 인코더 오류), 직렬화 결과는 null이 됩니다. [PNG]

이미지 파일의 픽셀 데이터는 좌표 공간 단위당 하나의 이미지 픽셀로 비트맵의 픽셀 데이터를 스케일링한 것이어야 하며, 사용된 파일 형식이 해상도 메타데이터 인코딩을 지원하는 경우 해상도는 96dpi(CSS 픽셀당 하나의 이미지 픽셀)로 지정되어야 합니다.

만약 type이 제공되면, 그것은 사용할 형식을 나타내는 MIME 타입으로 해석되어야 합니다. type에 매개변수가 있는 경우 지원되지 않는 것으로 처리되어야 합니다.

예를 들어, 값 "image/png"은 PNG 이미지를 생성함을 의미하고, 값 "image/jpeg"은 JPEG 이미지를 생성함을 의미하며, 값 "image/svg+xml"은 SVG 이미지를 생성함을 의미합니다(이는 사용자 에이전트가 비트맵이 생성된 방법을 추적해야 하므로 가능성은 낮지만, 잠재적으로 놀라운 기능이 될 수 있습니다).

사용자 에이전트는 PNG ("image/png")를 지원해야 합니다. 사용자 에이전트는 다른 유형을 지원할 수 있습니다. 사용자 에이전트가 요청된 형식을 지원하지 않으면 PNG 형식을 사용하여 파일을 생성해야 합니다. [PNG]

사용자 에이전트는 지원 여부를 확인하기 전에 제공된 typeASCII 소문자로 변환해야 합니다.

알파 채널을 지원하지 않는 이미지 유형의 경우, 직렬화된 이미지는 비트맵 이미지를 불투명한 검정색 배경에 합성한 후 source-over 합성 연산자를 사용해야 합니다.

색상 프로필을 지원하는 이미지 유형의 경우, 직렬화된 이미지는 기본 비트맵의 색상 공간을 나타내는 색상 프로필을 포함해야 합니다. 색상 프로필을 지원하지 않는 이미지 유형의 경우, 직렬화된 이미지는 'srgb' 색상 공간으로 'relative-colorimetric' 렌더링 의도를 사용하여 변환되어야 합니다.

따라서, 2D 컨텍스트에서 drawImage() 메서드를 호출하여 toDataURL() 또는 toBlob() 메서드의 출력을 캔버스에 렌더링할 때, 적절한 크기를 제공한다면, 캔버스의 색상을 더 좁은 색 영역으로 클리핑하는 것 이외에는 눈에 보이는 효과가 없습니다.

만약 type이 "image/jpeg"와 같이 가변 품질을 지원하는 이미지 형식이고, quality가 제공되었으며, type이 "image/png"이 아닌 경우, Type(quality)이 Number이고, quality가 0.0에서 1.0 범위 내에 있으면, 사용자 에이전트는 quality를 원하는 품질 수준으로 처리해야 합니다. 그렇지 않으면, 사용자 에이전트는 quality 인수가 제공되지 않은 것처럼 기본 품질 값을 사용해야 합니다.

여기서 단순히 quality를 Web IDL double로 선언하는 대신, 유형 검사를 사용하는 것은 역사적인 유물입니다.

다른 구현은 "품질"에 대해 약간 다른 해석을 가질 수 있습니다. 품질이 지정되지 않은 경우, 구현별 기본값이 사용되며, 이는 압축 비율, 이미지 품질, 인코딩 시간 사이의 합리적인 타협을 나타냅니다.

4.12.5.6 캔버스 요소의 보안

이 섹션은 규범적이지 않습니다.

정보 유출은 하나의 기원의 스크립트가 다른 기원(동일한 기원이 아닌)의 이미지에서 정보를 액세스할 수 있는 경우(예: 픽셀 읽기) 발생할 수 있습니다.

이를 완화하기 위해, 캔버스 요소, OffscreenCanvas 객체 및 ImageBitmap 객체와 함께 사용되는 비트맵은 origin-clean을 나타내는 플래그를 가지도록 정의됩니다. 모든 비트맵은 처음에는 origin-clean이 true로 설정되어 시작합니다. 교차 기원 이미지가 사용될 때 플래그는 false로 설정됩니다.

toDataURL(), toBlob(), 및 getImageData() 메서드는 이 플래그를 확인하며, 교차 기원 데이터를 유출하지 않도록 "SecurityError" DOMException을 발생시킵니다.

origin-clean 플래그의 값은 소스 비트맵에서 새 ImageBitmap 객체로 createImageBitmap()에 의해 전파됩니다. 반대로, 만약 소스 이미지가 origin-clean 플래그가 false로 설정된 ImageBitmap 객체인 경우, 대상 캔버스 요소의 비트맵은 drawImage에 의해 origin-clean 플래그가 false로 설정됩니다.

이 플래그는 특정 상황에서 재설정될 수 있습니다. 예를 들어, width 또는 height 콘텐츠 속성을 캔버스 요소에 변경하면, 이 요소에 바인딩된 CanvasRenderingContext2D의 비트맵이 지워지고 origin-clean 플래그가 재설정됩니다.

ImageBitmapRenderingContext를 사용할 때, origin-clean 플래그의 값은 ImageBitmap 객체가 transferFromImageBitmap()를 통해 캔버스로 전송될 때 전파됩니다.

4.12.5.7 프리멀티플라이드 알파와 2D 렌더링 컨텍스트

프리멀티플라이드 알파는 이미지에서 투명성을 표현하는 한 가지 방법을 나타내며, 다른 방법은 논-프리멀티플라이드 알파입니다.

논-프리멀티플라이드 알파에서는 픽셀의 빨강, 초록, 파랑 채널이 해당 픽셀의 색상을 나타내고, 알파 채널이 해당 픽셀의 불투명도를 나타냅니다.

그러나 프리멀티플라이드 알파에서는 픽셀의 빨강, 초록, 파랑 채널이 픽셀이 이미지에 추가하는 색상의 양을 나타내고, 알파 채널이 픽셀이 뒤에 있는 것을 가리는 양을 나타냅니다.

예를 들어, 색상 채널이 0(꺼짐)에서 255(완전한 강도)까지 범위를 가진다고 가정할 때, 다음의 예제 색상은 다음과 같은 방식으로 표현됩니다:

CSS 색상 표현 프리멀티플라이드 표현 논-프리멀티플라이드 표현 색상 설명 다른 콘텐츠 위에 블렌딩된 색상 이미지
rgba(255, 127, 0, 1) 255, 127, 0, 255 255, 127, 0, 255 완전히 불투명한 주황색 불투명한 주황색 원이 배경 위에 위치함
rgba(255, 255, 0, 0.5) 127, 127, 0, 127 255, 255, 0, 127 반투명한 노란색 반투명한 노란색 원이 배경 위에 위치함
표현 불가 255, 127, 0, 127 표현 불가 첨가된 반투명한 주황색 주황색 원이 배경을 약간 밝게 함
표현 불가 255, 127, 0, 0 표현 불가 첨가된 완전히 투명한 주황색 주황색 원이 배경을 완전히 밝게 함
rgba(255, 127, 0, 0) 0, 0, 0, 0 255, 127, 0, 0 완전히 투명한 ("보이지 않는") 주황색 위에 아무것도 없는 빈 배경
rgba(0, 127, 255, 0) 0, 0, 0, 0 255, 127, 0, 0 완전히 투명한 ("보이지 않는") 터키석색 위에 아무것도 없는 빈 배경

비프리멀티플라이드 표현에서 프리멀티플라이드 표현으로 색상 값을 변환하는 것은 색상의 빨강, 초록, 파랑 채널을 알파 채널로 곱하는 것을 포함하며(알파 채널의 범위를 "완전히 투명함"은 0이고 "완전히 불투명함"은 1로 재매핑함),

프리멀티플라이드 표현에서 비프리멀티플라이드 표현으로 색상 값을 변환하는 것은 그 반대입니다: 색상의 빨강, 초록, 파랑 채널을 알파 채널로 나누는 것입니다.

일부 색상은 프리멀티플라이드 알파에서만 표현될 수 있으며(예: 첨가 색상), 다른 색상은 비프리멀티플라이드 알파에서만 표현될 수 있습니다(예: 불투명도 없이 특정 빨강, 초록, 파랑 값을 유지하는 "보이지 않는" 색상); 8비트 정수(현재 캔버스의 색상이 저장되는 방식)에서의 나눗셈 및 곱셈은 정밀도 손실을 수반하므로, 프리멀티플라이드 알파와 비프리멀티플라이드 알파 간의 변환은 완전히 불투명하지 않은 색상에 대해 손실이 발생하는 작업입니다.

CanvasRenderingContext2D출력 비트맵OffscreenCanvasRenderingContext2D비트맵은 투명한 색상을 표현하기 위해 프리멀티플라이드 알파를 사용해야 합니다.

캔버스 비트맵이 프리멀티플라이드 알파를 사용하여 색상을 표현하는 것은 표현 가능한 색상 범위에 영향을 미치기 때문에 중요합니다. 첨가 색상은 현재 CSS 색상이 비프리멀티플라이드 상태이므로 캔버스에 직접 그릴 수 없지만, 여전히 예를 들어 WebGL 캔버스에 첨가 색상을 그린 다음 drawImage()를 통해 해당 WebGL 캔버스를 2D 캔버스에 그릴 수 있습니다.

4.13 커스텀 요소

Using_custom_elements

모든 최신 엔진에서 지원됩니다.

Firefox63+Safari10.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

4.13.1 소개

이 섹션은 규범적이지 않습니다.

커스텀 요소는 작성자가 고유의 완전한 기능을 갖춘 DOM 요소를 구축할 수 있는 방법을 제공합니다. 작성자는 항상 비표준 요소를 문서에 사용할 수 있었고, 이후 스크립팅이나 유사한 방식으로 애플리케이션 전용 동작을 추가할 수 있었지만, 이러한 요소는 역사적으로 비표준적이며 기능적이지 않았습니다. 커스텀 요소 정의를 통해 작성자는 파서에게 요소를 올바르게 구성하는 방법과 해당 클래스의 요소가 변경 사항에 어떻게 반응해야 하는지를 알려줄 수 있습니다.

커스텀 요소는 기존 플랫폼 기능(예: HTML 요소)을 하위 수준의 작성자 노출 확장성 포인트(예: 커스텀 요소 정의)로 설명하여 "플랫폼을 합리화"하려는 더 큰 노력의 일부입니다. 오늘날 커스텀 요소의 기능적 및 의미적 한계로 인해 HTML의 기존 요소의 동작을 완전히 설명하지 못하지만, 시간이 지남에 따라 이 격차를 줄이기를 희망합니다.

4.13.1.1 자율 커스텀 요소 생성

이 섹션은 규범적이지 않습니다.

자율 커스텀 요소를 만드는 방법을 설명하기 위해, 국가 깃발의 작은 아이콘을 렌더링하는 커스텀 요소를 정의해보겠습니다. 우리의 목표는 다음과 같이 사용할 수 있도록 하는 것입니다:

<flag-icon country="nl"></flag-icon>

이를 위해 먼저 HTMLElement를 확장하여 커스텀 요소의 클래스를 선언합니다:

class FlagIcon extends HTMLElement {
  constructor() {
    super();
    this._countryCode = null;
  }

  static observedAttributes = ["country"];

  attributeChangedCallback(name, oldValue, newValue) {
    // name은 항상 observedAttributes에 따라 "country"가 됩니다.
    this._countryCode = newValue;
    this._updateRendering();
  }
  connectedCallback() {
    this._updateRendering();
  }

  get country() {
    return this._countryCode;
  }
  set country(v) {
    this.setAttribute("country", v);
  }

  _updateRendering() {
    // 독자가 스스로 시도해볼 수 있습니다. 하지만, 아마도
    // this.ownerDocument.defaultView를 확인하여
    // 탐색 컨텍스트가 있는 문서에 삽입되었는지 확인하고,
    // 그렇지 않은 경우 작업을 피하고자 할 것입니다.
  }
}

그런 다음 이 클래스를 사용하여 요소를 정의해야 합니다:

customElements.define("flag-icon", FlagIcon);

이 시점에서 위의 코드가 작동합니다! 파서는 flag-icon 태그를 볼 때마다 새로운 FlagIcon 클래스 인스턴스를 생성하고, 코드에 새로운 country 속성에 대해 알려줍니다. 이 속성을 사용하여 요소의 내부 상태를 설정하고 렌더링을 업데이트합니다(적절할 때).

또한 DOM API를 사용하여 flag-icon 요소를 생성할 수도 있습니다:

const flagIcon = document.createElement("flag-icon")
flagIcon.country = "jp"
document.body.appendChild(flagIcon)

마지막으로, 커스텀 요소 생성자 자체를 사용할 수도 있습니다. 즉, 위의 코드는 다음과 같습니다:

const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon)
4.13.1.2 폼 연관 커스텀 요소 생성

이 섹션은 규범적이지 않습니다.

정적 formAssociated 속성에 true 값을 추가하면, 자율 커스텀 요소폼 연관 커스텀 요소가 됩니다. ElementInternals 인터페이스는 폼 컨트롤 요소에 공통된 기능과 속성을 구현하는 데 도움이 됩니다.

class MyCheckbox extends HTMLElement {
  static formAssociated = true;
  static observedAttributes = ['checked'];

  constructor() {
    super();
    this._internals = this.attachInternals();
    this.addEventListener('click', this._onClick.bind(this));
  }

  get form() { return this._internals.form; }
  get name() { return this.getAttribute('name'); }
  get type() { return this.localName; }

  get checked() { return this.hasAttribute('checked'); }
  set checked(flag) { this.toggleAttribute('checked', Boolean(flag)); }

  attributeChangedCallback(name, oldValue, newValue) {
    // observedAttributes에 따라 name은 항상 "checked"가 됩니다.
    this._internals.setFormValue(this.checked ? 'on' : null);
  }

  _onClick(event) {
    this.checked = !this.checked;
  }
}
customElements.define('my-checkbox', MyCheckbox);

커스텀 요소 my-checkbox를 기본 제공 폼 연관 요소처럼 사용할 수 있습니다. 예를 들어, form이나 label에 넣으면 my-checkbox 요소와 연관되며, form을 제출할 때 my-checkbox 구현에서 제공된 데이터를 전송합니다.

<form action="..." method="...">
  <label><my-checkbox name="agreed"></my-checkbox> 동의서 내용을 읽었습니다.</label>
  <input type="submit">
</form>
4.13.1.3 기본 접근성 역할, 상태 및 속성이 있는 커스텀 요소 생성

이 섹션은 규범적이지 않습니다.

ElementInternals의 적절한 속성을 사용하여 커스텀 요소에 기본 접근성 의미를 부여할 수 있습니다. 다음 코드는 이전 섹션의 폼 연관 체크박스를 확장하여 접근성 기술에서 볼 수 있는 기본 역할과 체크 상태를 올바르게 설정합니다:

class MyCheckbox extends HTMLElement {
  static formAssociated = true;
  static observedAttributes = ['checked'];

  constructor() {
    super();
    this._internals = this.attachInternals();
    this.addEventListener('click', this._onClick.bind(this));

    this._internals.role = 'checkbox';
    this._internals.ariaChecked = 'false';
  }

  get form() { return this._internals.form; }
  get name() { return this.getAttribute('name'); }
  get type() { return this.localName; }

  get checked() { return this.hasAttribute('checked'); }
  set checked(flag) { this.toggleAttribute('checked', Boolean(flag)); }

  attributeChangedCallback(name, oldValue, newValue) {
    // observedAttributes에 따라 name은 항상 "checked"가 됩니다.
    this._internals.setFormValue(this.checked ? 'on' : null);
    this._internals.ariaChecked = this.checked; 
  }

  _onClick(event) {
    this.checked = !this.checked;
  }
}
customElements.define('my-checkbox', MyCheckbox);

기본 제공 요소와 마찬가지로, 이러한 속성들은 기본값일 뿐이며, 페이지 작성자가 rolearia-* 속성을 사용하여 재정의할 수 있습니다:

<!-- 이 마크업은 비표준입니다 -->
<input type="checkbox" checked role="button" aria-checked="false">
<!-- 이 마크업은 커스텀 요소 작성자가 의도한 것이 아닐 수 있습니다 -->
<my-checkbox role="button" checked aria-checked="false">

커스텀 요소 작성자는 접근성 의미에서 어떤 측면이 강력한 기본 의미인지, 즉 커스텀 요소 사용자가 재정의해서는 안 되는지를 명시하는 것이 좋습니다. 예를 들어, my-checkbox 요소의 작성자는 rolearia-checked 값이 강력한 기본 의미임을 명시하여 위와 같은 코드를 지양하도록 합니다.

4.13.1.4 맞춤형 내장 요소 생성

이 섹션은 규범적이지 않습니다.

맞춤형 내장 요소커스텀 요소의 독특한 종류로, 자율 커스텀 요소와 비교하여 약간 다르게 정의되고 매우 다르게 사용됩니다. 이들은 기존 HTML 요소의 동작을 새 커스텀 기능으로 확장하여 재사용할 수 있도록 존재합니다. 이는 HTML 요소의 기존 동작 중 많은 부분이 단순히 자율 커스텀 요소를 사용하여 복제될 수 없는 경우가 많기 때문에 중요합니다. 대신, 맞춤형 내장 요소는 기존 요소 위에 커스텀 생성 동작, 생명 주기 후크 및 프로토타입 체인을 설치할 수 있게 하여, 기본 요소에 이러한 기능을 "혼합"할 수 있습니다.

맞춤형 내장 요소자율 커스텀 요소와 다른 문법이 필요합니다. 그 이유는 사용자 에이전트와 기타 소프트웨어가 요소의 로컬 이름을 기준으로 해당 요소의 의미와 동작을 식별하기 때문입니다. 즉, 맞춤형 내장 요소가 기존 동작을 기반으로 하는 개념은 확장된 요소가 원래의 로컬 이름을 유지하는 것에 크게 의존합니다.

이 예제에서는 맞춤형 내장 요소plastic-button이라고 명명하여 만들 것입니다. 이 요소는 일반 버튼처럼 동작하지만 클릭할 때마다 화려한 애니메이션 효과가 추가됩니다. 이전과 마찬가지로 클래스를 정의하는 것으로 시작하지만, 이번에는 HTMLButtonElement를 확장합니다:

class PlasticButton extends HTMLButtonElement {
  constructor() {
    super();

    this.addEventListener("click", () => {
      // 화려한 애니메이션 효과 그리기!
    });
  } 
}

커스텀 요소를 정의할 때, extends 옵션도 지정해야 합니다:

customElements.define("plastic-button", PlasticButton, { extends: "button" });

일반적으로, 확장된 요소의 이름은 어떤 요소 인터페이스를 확장하는지 보기만으로는 결정할 수 없습니다. 많은 요소가 동일한 인터페이스를 공유하기 때문입니다(예: qblockquote는 둘 다 HTMLQuoteElement를 공유합니다).

분석된 HTML 소스 텍스트에서 맞춤형 내장 요소를 생성하기 위해, is 속성을 button 요소에 사용합니다:

<button is="plastic-button">Click Me!</button>

맞춤형 내장 요소자율 커스텀 요소처럼 사용하려고 하면 작동하지 않습니다. 즉, <plastic-button>Click me?</plastic-button>은 아무 특별한 동작이 없는 HTMLElement를 생성할 뿐입니다.

맞춤형 내장 요소를 프로그래밍 방식으로 생성해야 하는 경우, createElement()의 다음 형식을 사용할 수 있습니다:

const plasticButton = document.createElement("button", { is: "plastic-button" });
plasticButton.textContent = "Click me!";

앞서 언급한 것처럼 생성자도 작동합니다:

const plasticButton2 = new PlasticButton();
console.log(plasticButton2.localName);  // "button"을 출력합니다.
console.assert(plasticButton2 instanceof PlasticButton);
console.assert(plasticButton2 instanceof HTMLButtonElement);

맞춤형 내장 요소를 프로그래밍 방식으로 생성할 때, is 속성은 DOM에 존재하지 않으며, 명시적으로 설정되지 않았기 때문입니다. 그러나 직렬화할 때 출력에 추가됩니다:

console.assert(!plasticButton.hasAttribute("is"));
console.log(plasticButton.outerHTML); // '<button is="plastic-button"></button>'을 출력합니다.

어떻게 생성되었든 간에, button이 특별한 이유는 "플라스틱 버튼"에도 모두 적용됩니다. 이들은 포커스 동작, 폼 제출에 참여하는 능력, disabled 속성 등과 관련된 기능을 가집니다.

맞춤형 내장 요소는 유용한 사용자 에이전트 제공 동작이나 API를 가진 기존 HTML 요소를 확장할 수 있도록 설계되었습니다. 따라서 이들은 이 사양에서 정의된 기존 HTML 요소만 확장할 수 있으며, bgsound, blink, isindex, keygen, multicol, nextid 또는 spacer와 같은 레거시 요소를 확장할 수 없습니다. 이러한 요소들은 요소 인터페이스HTMLUnknownElement를 사용하도록 정의되었습니다.

이 요구 사항의 한 가지 이유는 미래 호환성입니다. 예를 들어, 현재는 알려지지 않은 요소를 확장하는 맞춤형 내장 요소combobox와 같은 요소로 정의되었다면, 이 사양이 향후 combobox 요소를 정의하는 것을 방해할 수 있습니다. 이는 파생된 맞춤형 내장 요소의 소비자들이 그들의 기본 요소가 흥미로운 사용자 에이전트 제공 동작이 없는 것에 의존하게 되었을 것이기 때문입니다.

4.13.1.5 자율 커스텀 요소의 단점

이 섹션은 규범적이지 않습니다.

아래에 명시된 것처럼, 그리고 앞서 언급된 바와 같이, taco-button이라는 요소를 단순히 정의하고 사용하는 것이 그러한 요소가 버튼을 표현한다는 것을 의미하지는 않습니다. 즉, 웹 브라우저, 검색 엔진 또는 접근성 기술과 같은 도구들은 정의된 이름만으로 결과 요소를 자동으로 버튼으로 인식하지 않습니다.

여전히 자율 커스텀 요소를 사용하면서 다양한 사용자에게 원하는 버튼 의미를 전달하려면, 여러 가지 기술을 사용해야 합니다:

이러한 점들을 고려할 때, 버튼 의미를 전달하는 책임을 맡는(비활성화될 수 있는 능력을 포함하여) 전체 기능을 갖춘 taco-button은 다음과 같을 수 있습니다:

class TacoButton extends HTMLElement {
  static observedAttributes = ["disabled"];

  constructor() {
    super(); 
    this._internals = this.attachInternals(); 
    this._internals.role = "button"; 

    this.addEventListener("keydown", e => { 
      if (e.code === "Enter" || e.code === "Space") { 
        this.dispatchEvent(new PointerEvent("click", { 
          bubbles: true, 
          cancelable: true
        })); 
      } 
    }); 

    this.addEventListener("click", e => { 
      if (this.disabled) { 
        e.preventDefault(); 
        e.stopImmediatePropagation(); 
      } 
    }); 

    this._observer = new MutationObserver(() => { 
      this._internals.ariaLabel = this.textContent; 
    }); 
  }

  connectedCallback() { 
    this.setAttribute("tabindex", "0"); 

    this._observer.observe(this, { 
      childList: true, 
      characterData: true, 
      subtree: true 
    }); 
  }

  disconnectedCallback() { 
    this._observer.disconnect(); 
  } 

  get disabled() { 
    return this.hasAttribute("disabled"); 
  } 
  set disabled(flag) { 
    this.toggleAttribute("disabled", Boolean(flag)); 
  } 

  attributeChangedCallback(name, oldValue, newValue) {
    // observedAttributes에 따라 name은 항상 "disabled"가 됩니다.
    if (this.disabled) { 
      this.removeAttribute("tabindex"); 
      this._internals.ariaDisabled = "true"; 
    } else { 
      this.setAttribute("tabindex", "0"); 
      this._internals.ariaDisabled = "false"; 
    } 
  } 
}

이러한 다소 복잡한 요소 정의에도 불구하고, 소비자에게 이 요소를 사용하는 것은 쉽지 않습니다. 이 요소는 계속해서 자체적으로 tabindex 속성을 생성할 것이며, tabindex="0" 포커스 가능 동작의 선택이 현재 플랫폼의 button 동작과 일치하지 않을 수 있습니다. 이는 현재 커스텀 요소의 기본 포커스 동작을 지정하는 방법이 없기 때문에 tabindex 속성을 사용하도록 강제하기 때문입니다(이는 일반적으로 소비자가 기본 동작을 재정의할 수 있도록 허용하기 위해 예약되어 있습니다).

반면에, 이전 섹션에서 보여준 것처럼, 간단한 맞춤형 내장 요소button 요소의 의미와 동작을 자동으로 상속받아 이러한 동작을 수동으로 구현할 필요가 없습니다. 일반적으로, HTML의 기존 요소를 기반으로 하는 비트리비얼한 동작과 의미를 가진 요소의 경우, 맞춤형 내장 요소가 개발, 유지 보수 및 사용하기 더 쉬울 것입니다.

4.13.1.6 요소 생성 후 업그레이드

이 섹션은 규범적이지 않습니다.

요소 정의는 언제든지 발생할 수 있기 때문에, 커스텀 요소가 아닌 요소가 생성된 후에 적절한 정의가 등록되면 커스텀 요소로 변환될 수 있습니다. 이 과정을 일반 요소에서 커스텀 요소로 "업그레이드"한다고 합니다.

업그레이드커스텀 요소 정의가 처음에 관련 요소가 생성된 후, 예를 들어 파서에 의해 등록되는 것이 바람직할 수 있는 시나리오를 가능하게 합니다. 이러한 방법은 커스텀 요소의 콘텐츠를 점진적으로 향상시키는 것을 허용합니다. 예를 들어, 다음 HTML 문서에서는 img-viewer 요소의 정의가 비동기적으로 로드됩니다:

<!DOCTYPE html>
<html lang="en">
<title>이미지 뷰어 예제</title>

<img-viewer filter="Kelvin">
  <img src="images/tree.jpg" alt="비어있는 사바나 위로 우뚝 솟은 아름다운 나무">
</img-viewer>

<script src="js/elements/img-viewer.js" async></script>

여기서 img-viewer 요소의 정의는 마크업에서 <img-viewer> 태그 뒤에 배치된 script 요소에 async 속성을 사용하여 로드됩니다. 스크립트가 로드되는 동안 img-viewer 요소는 span과 유사한 정의되지 않은 요소로 처리됩니다. 스크립트가 로드되면 img-viewer 요소가 정의되고, 페이지의 기존 img-viewer 요소가 업그레이드되어 커스텀 요소의 정의가 적용됩니다(아마도 "Kelvin"이라는 문자열로 식별된 이미지 필터를 적용하여 이미지의 시각적 표현을 향상시킬 것입니다).


업그레이드는 문서 트리에 있는 요소들에만 적용된다는 점에 유의해야 합니다. (공식적으로 연결된 요소들입니다.) 문서에 삽입되지 않은 요소는 업그레이드되지 않은 상태로 유지됩니다. 다음 예제가 이를 설명합니다:

<!DOCTYPE html>
<html lang="en">
<title>업그레이드 엣지 케이스 예제</title>

<example-element></example-element>

<script>
  "use strict";

  const inDocument = document.querySelector("example-element"); 
  const outOfDocument = document.createElement("example-element");

  // 요소 정의 전에, 둘 다 HTMLElement입니다:
  console.assert(inDocument instanceof HTMLElement); 
  console.assert(outOfDocument instanceof HTMLElement); 

  class ExampleElement extends HTMLElement {} 
  customElements.define("example-element", ExampleElement);

  // 요소 정의 후, 문서 내의 요소는 업그레이드되었습니다:
  console.assert(inDocument instanceof ExampleElement); 
  console.assert(!(outOfDocument instanceof ExampleElement));

  document.body.appendChild(outOfDocument);

  // 이제 요소를 문서로 이동시켰으므로, 이 요소도 업그레이드되었습니다:
  console.assert(outOfDocument instanceof ExampleElement); 
</script>
4.13.1.7 커스텀 요소 상태 노출

사용자 에이전트에 의해 제공되는 기본 요소들은 사용자 상호작용 및 기타 요인에 따라 시간이 지남에 따라 변경될 수 있는 특정 상태를 가지고 있으며, 이는 웹 작성자에게 의사 클래스를 통해 노출됩니다. 예를 들어, 일부 폼 컨트롤은 "유효하지 않은" 상태를 가지고 있으며, 이는 :invalid 의사 클래스를 통해 노출됩니다.

기본 요소들처럼, 커스텀 요소도 다양한 상태를 가질 수 있으며, 커스텀 요소 작성자들은 이러한 상태를 기본 요소와 유사한 방식으로 노출하고자 합니다.

이는 :state() 의사 클래스를 통해 수행됩니다. 커스텀 요소 작성자는 states 속성을 사용하여 이러한 커스텀 상태를 추가 및 제거할 수 있으며, 이는 :state() 의사 클래스의 인수로 노출됩니다.

다음은 :state()를 사용하여 커스텀 체크박스 요소를 스타일링하는 방법을 보여줍니다. LabeledCheckbox가 "checked" 상태를 콘텐츠 속성을 통해 노출하지 않는다고 가정합니다.

<script>
class LabeledCheckbox extends HTMLElement {
  constructor() {
    super(); 
    this._internals = this.attachInternals(); 
    this.addEventListener('click', this._onClick.bind(this));

    const shadowRoot = this.attachShadow({mode: 'closed'}); 
    shadowRoot.innerHTML =
      `<style>
       :host::before {content: '[ ]';white-space: pre;font-family: monospace;} 
       :host(:state(checked))::before { content: '[x]' }
       </style><slot>Label</slot>`; 
  }

  get checked() { return this._internals.states.has('checked'); }

  set checked(flag) { 
    if (flag) 
      this._internals.states.add('checked'); 
    else
      this._internals.states.delete('checked'); 
  }

  _onClick(event) { 
    this.checked = !this.checked; 
  } 
}

customElements.define('labeled-checkbox', LabeledCheckbox); 
</script>

<style> 
labeled-checkbox { border: dashed red; } 
labeled-checkbox:state(checked) { border: solid; } 
</style>

<labeled-checkbox>이것을 확인해야 합니다</labeled-checkbox>

커스텀 의사 클래스는 섀도우 파트를 대상으로 할 수도 있습니다. 위 예제의 확장된 버전이 이를 보여줍니다:

<script> 
class QuestionBox extends HTMLElement { 
  constructor() { 
    super(); 
    const shadowRoot = this.attachShadow({mode: 'closed'}); 
    shadowRoot.innerHTML = 
      `<div><slot>Question</slot></div> 
       <labeled-checkbox part='checkbox'>Yes</labeled-checkbox>`; 
  } 
} 
customElements.define('question-box', QuestionBox); 
</script>

<style> 
question-box::part(checkbox) { color: red; } 
question-box::part(checkbox):state(checked) { color: green; } 
</style>

<question-box>계속하시겠습니까?</question-box>

4.13.2 커스텀 요소 생성자 및 반응을 위한 요구 사항

커스텀 요소 생성자를 작성할 때, 작성자는 다음의 적합성 요구 사항을 준수해야 합니다:

이 요구 사항 중 일부는 요소 생성 중에 직접 또는 간접적으로 확인되며, 이를 따르지 않으면 파서나 DOM API가 인스턴스화할 수 없는 커스텀 요소가 됩니다. 이는 작업이 생성자에 의해 시작된 마이크로태스크 내부에서 수행되더라도 마찬가지입니다. 마이크로태스크 체크포인트가 생성 직후 발생할 수 있기 때문입니다.

커스텀 요소 반응을 작성할 때, 작성자는 노드 트리를 조작하는 것을 피해야 합니다. 이는 예기치 않은 결과를 초래할 수 있습니다.

요소의 connectedCallback이 요소가 연결 해제되기 전에 큐에 넣어질 수 있지만, 콜백 큐가 여전히 처리되므로 더 이상 연결되지 않은 요소에 대해 connectedCallback이 실행되는 결과를 초래합니다:

class CParent extends HTMLElement { 
  connectedCallback() { 
    this.firstChild.remove(); 
  } 
} 
customElements.define("c-parent", CParent);

class CChild extends HTMLElement { 
  connectedCallback() { 
    console.log("CChild connectedCallback: isConnected =", this.isConnected); 
  } 
} 
customElements.define("c-child", CChild);

const parent = new CParent(), 
      child = new CChild(); 
parent.append(child); 
document.body.append(parent);

// 출력 내용: 
// CChild connectedCallback: isConnected = false

4.13.3 핵심 개념

커스텀 요소커스텀된 요소입니다. 비공식적으로, 이는 생성자와 프로토타입이 사용자 에이전트가 아닌 작성자에 의해 정의된다는 것을 의미합니다. 이 작성자가 제공한 생성자 함수는 커스텀 요소 생성자라고 합니다.

두 가지 유형의 커스텀 요소를 정의할 수 있습니다:

Global_attributes/is

Firefox63+SafariNoChrome67+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
  1. 자율 커스텀 요소extends 옵션 없이 정의된 요소입니다. 이 유형의 커스텀 요소는 정의된 이름과 동일한 로컬 이름을 가집니다.

  2. 맞춤형 내장 요소extends 옵션과 함께 정의된 요소입니다. 이 유형의 커스텀 요소는 extends 옵션에 전달된 값과 동일한 로컬 이름을 가지며, 정의된 이름is 속성의 값으로 사용됩니다. 이 값은 유효한 커스텀 요소 이름이어야 합니다.

커스텀 요소생성된 후, is 속성의 값을 변경해도 요소의 동작이 변경되지 않습니다. 이는 해당 값이 요소에 is으로 저장되기 때문입니다.

자율 커스텀 요소는 다음과 같은 요소 정의를 가집니다:

카테고리:
흐름 콘텐츠
구문 콘텐츠
감지 가능한 콘텐츠
양식 관련 커스텀 요소의 경우: 리스트된, 레이블 가능한, 제출 가능한, 재설정 가능한 양식 관련 요소
이 요소를 사용할 수 있는 문맥:
구문 콘텐츠가 예상되는 곳
콘텐츠 모델:
투명
콘텐츠 속성:
전역 속성 (is 속성 제외)
form ( 양식 관련 커스텀 요소의 경우) — 요소를 양식 요소와 연결합니다.
disabled ( 양식 관련 커스텀 요소의 경우) — 양식 컨트롤이 비활성화되었는지 여부를 나타냅니다.
readonly ( 양식 관련 커스텀 요소의 경우) — willValidate에 영향을 미치며, 커스텀 요소 작성자가 추가한 모든 동작을 포함합니다.
name ( 양식 관련 커스텀 요소의 경우) — 양식 제출form.elements API에서 사용할 요소의 이름입니다.
네임스페이스가 없는 다른 모든 속성 (설명 참조)
접근성 고려 사항:
양식 관련 커스텀 요소의 경우: 작성자를 위한 문서, 구현자를 위한 문서
그 외의 경우: 작성자를 위한 문서, 구현자를 위한 문서
DOM 인터페이스:
요소의 작성자가 제공한 DOM 인터페이스 ( HTMLElement에서 상속됨)

자율 커스텀 요소는 특별한 의미를 가지지 않습니다. 자식 요소들을 대표합니다. 맞춤형 내장 요소는 확장하는 요소의 의미론을 상속받습니다.

네임스페이스가 없는 속성 중에서 요소의 작동과 관련된 속성은, 요소 작성자가 결정한 경우, 자율 커스텀 요소에 지정될 수 있습니다. 단, 속성 이름은 XML 호환이어야 하며 ASCII 대문자를 포함하지 않아야 합니다. 예외는 is 속성으로, 이는 자율 커스텀 요소에 지정할 수 없으며, 지정해도 아무런 효과가 없습니다.

맞춤형 내장 요소는 확장하는 요소에 따라 일반적인 속성 요구 사항을 따릅니다. 커스텀 속성 기반 동작을 추가하려면 data-* 속성을 사용하세요.


자율 커스텀 요소는 요소가 커스텀 요소 정의와 연결되어 있고, 해당 정의의 양식 관련 필드가 true로 설정된 경우 양식 관련 커스텀 요소라고 합니다.

name 속성은 양식 관련 커스텀 요소의 이름을 나타냅니다. disabled 속성은 양식 관련 커스텀 요소를 비활성화하고, 제출 값이 제출되지 않도록 하는 데 사용됩니다. form 속성은 양식 관련 커스텀 요소양식 소유자와 명시적으로 연결하는 데 사용됩니다.

readonly 속성은 양식 관련 커스텀 요소제약 조건 유효성 검사에서 제외되도록 지정합니다. 사용자 에이전트는 이 속성에 대해 추가적인 동작을 제공하지 않지만, 커스텀 요소 작성자는 가능한 경우 이 속성의 존재를 사용하여 해당 컨트롤이 내장된 양식 컨트롤의 readonly 속성과 유사한 방식으로 편집 불가능하도록 해야 합니다.

제약 조건 유효성 검사: readonly 속성이 양식 관련 커스텀 요소에 지정된 경우, 해당 요소는 제약 조건 유효성 검사에서 제외됩니다.

양식 재설정 알고리즘양식 관련 커스텀 요소에 대해 요소, 콜백 이름 "formResetCallback", 그리고 빈 인수 목록을 사용하여 커스텀 요소 콜백 반응을 대기열에 추가합니다.


유효한 커스텀 요소 이름은 다음 요구 사항을 모두 충족하는 문자 name 시퀀스입니다:

이 요구 사항은 유효한 커스텀 요소 이름을 위한 여러 목표를 보장합니다:

이러한 제한 외에도 <math-α> 또는 <emotion-😍>와 같은 사용 사례에 최대한의 유연성을 제공하기 위해 다양한 이름이 허용됩니다.

커스텀 요소 정의커스텀 요소를 설명하며 다음으로 구성됩니다:

이름
유효한 커스텀 요소 이름
로컬 이름
로컬 이름
생성자
Web IDL CustomElementConstructor 콜백 함수 유형 값이며, 커스텀 요소 생성자를 래핑합니다.
관찰된 속성
sequence<DOMString>
라이프사이클 콜백
맵으로, 키는 "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback", "formAssociatedCallback", "formDisabledCallback", "formResetCallback", "formStateRestoreCallback" 문자열입니다. 해당 값은 Web IDL Function 콜백 함수 유형 값이거나 null입니다. 기본적으로 각 항목의 값은 null입니다.
생성 스택
초기에는 비어 있는 목록으로, 요소 업그레이드 알고리즘과 HTML 요소 생성자에 의해 조작됩니다. 목록의 각 항목은 요소 또는 이미 생성된 마커 중 하나입니다.
양식 관련 불리언
이 값이 true인 경우, 사용자 에이전트는 이 커스텀 요소 정의와 연결된 요소를 양식 관련 커스텀 요소로 처리합니다.
내부 비활성화 불리언
attachInternals()를 제어합니다.
그림자 비활성화 불리언
attachShadow()를 제어합니다.

커스텀 요소 정의 조회를 수행하려면, document, namespace, localName, is를 기준으로 다음 단계를 수행합니다. 이 단계는 커스텀 요소 정의 또는 null을 반환합니다:

  1. namespaceHTML 네임스페이스가 아니라면 null을 반환합니다.

  2. document브라우징 컨텍스트가 null인 경우, null을 반환합니다.

  3. document관련 글로벌 객체CustomElementRegistry 객체를 registry로 설정합니다.

  4. registry이름로컬 이름localName과 모두 동일한 커스텀 요소 정의가 있으면, 해당 커스텀 요소 정의를 반환합니다.

  5. 만약 registryis와 동일한 이름localName과 동일한 로컬 이름을 가진 커스텀 엘리먼트 정의가 있다면, 그 커스텀 엘리먼트 정의를 반환합니다.

  6. null을 반환합니다.

4.13.4 CustomElementRegistry 인터페이스

CustomElementRegistry

모든 현재 엔진에서 지원됩니다.

Firefox63+Safari10.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Window 객체는 해당 객체가 생성될 때 고유한 CustomElementRegistry 객체와 연결됩니다.

커스텀 엘리먼트 레지스트리는 Window 객체와 연관되며, Document 객체와는 연관되지 않습니다. 이는 각 커스텀 엘리먼트 생성자HTMLElement 인터페이스를 상속받기 때문이며, Window 객체마다 하나의 HTMLElement 인터페이스가 존재하기 때문입니다.

Window/customElements

모든 현재 엔진에서 지원됩니다.

Firefox63+Safari10.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Window 인터페이스의 customElements 속성은 해당 Window 객체의 CustomElementRegistry 객체를 반환해야 합니다.

[Exposed=Window]
interface CustomElementRegistry {
  [CEReactions] undefined define(DOMString name, CustomElementConstructor constructor, optional ElementDefinitionOptions options = {});
  (CustomElementConstructor or undefined) get(DOMString name);
  DOMString? getName(CustomElementConstructor constructor);
  Promise<CustomElementConstructor> whenDefined(DOMString name);
  [CEReactions] undefined upgrade(Node root);
};

callback CustomElementConstructor = HTMLElement ();

dictionary ElementDefinitionOptions {
  DOMString extends;
};

모든 CustomElementRegistry에는 처음에 비어 있는 커스텀 요소 정의 집합이 있습니다. 일반적으로 이 사양의 알고리즘은 이름, 로컬 이름 또는 생성자로 레지스트리에서 요소를 조회합니다.

모든 CustomElementRegistry에는 요소 정의의 재진입 호출을 방지하기 위해 사용되는 요소 정의 실행 중 플래그가 있습니다. 이 플래그는 처음에 설정되지 않습니다.

모든 CustomElementRegistry에는 유효한 커스텀 요소 이름을 프라미스에 매핑하는 정의 시 프라미스 맵도 있습니다. 이는 whenDefined() 메서드를 구현하는 데 사용됩니다.

window.customElements.define(name, constructor)

CustomElementRegistry/define

모든 현재 엔진에서 지원.

Firefox63+Safari10.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
새로운 커스텀 요소를 정의하며, 주어진 이름을 주어진 생성자와 매핑하여 독립형 커스텀 요소로 만듭니다.
window.customElements.define(name, constructor, { extends: baseLocalName })
새로운 커스텀 요소를 정의하며, 주어진 이름을 주어진 생성자와 매핑하여, baseLocalName으로 식별된 요소 유형에 대한 커스텀 내장 요소로 만듭니다. "NotSupportedError" DOMException이 커스텀 요소나 알 수 없는 요소를 확장하려고 할 때 발생합니다.
window.customElements.get(name)

CustomElementRegistry/get

모든 현재 엔진에서 지원.

Firefox63+Safari10.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
주어진 이름으로 정의된 커스텀 요소 생성자를 가져옵니다. 주어진 이름으로 커스텀 요소 정의가 없는 경우 undefined를 반환합니다.
window.customElements.getName(constructor)
주어진 생성자로 정의된 커스텀 요소의 이름을 가져옵니다. 주어진 생성자커스텀 요소 정의가 없는 경우 null을 반환합니다.
window.customElements.whenDefined(name)

CustomElementRegistry/whenDefined

모든 현재 엔진에서 지원.

Firefox63+Safari10.1+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
지정된 이름으로 커스텀 요소가 정의될 때 생성자를 포함하여 해결되는 프라미스를 반환합니다. (지정된 커스텀 요소가 이미 정의되어 있는 경우, 반환된 프라미스는 즉시 해결됩니다.) 유효한 커스텀 요소 이름을 제공하지 않은 경우 프라미스는 "SyntaxError" DOMException을 포함하여 거부됩니다.
window.customElements.upgrade(root)

CustomElementRegistry/upgrade

모든 현재 엔진에서 지원.

Firefox63+Safari12.1+Chrome68+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
업그레이드를 시도하며, root섀도우를 포함한 모든 하위 요소에 대해 연결되지 않은 상태에서도 작동합니다.

요소 정의커스텀 요소 정의CustomElementRegistry에 추가하는 과정입니다. 이것은 define() 메서드로 수행됩니다. 호출되면, define(name, constructor, options) 메서드는 다음 단계를 실행해야 합니다:

  1. IsConstructor(constructor)가 false인 경우, TypeError를 발생시킵니다.

  2. name유효한 커스텀 요소 이름이 아닌 경우, "SyntaxError" DOMException를 발생시킵니다.

  3. CustomElementRegistryname 이름을 가진 항목이 포함되어 있는 경우, "NotSupportedError" DOMException를 발생시킵니다.

  4. CustomElementRegistryconstructor 생성자를 가진 항목이 포함되어 있는 경우, "NotSupportedError" DOMException를 발생시킵니다.

  5. localNamename으로 설정합니다.

  6. extendsoptionsextends 멤버의 값으로 설정하거나, 해당 멤버가 존재하지 않으면 null로 설정합니다.

  7. extends가 null이 아닌 경우 다음을 수행합니다:

    1. extends유효한 커스텀 요소 이름인 경우, "NotSupportedError" DOMException를 발생시킵니다.

    2. extends에 대한 요소 인터페이스HTML 네임스페이스HTMLUnknownElement(예: extends가 이 명세서에 요소 정의를 포함하지 않는 경우)인 경우, "NotSupportedError" DOMException를 발생시킵니다.

    3. localNameextends로 설정합니다.

  8. CustomElementRegistry요소 정의 실행 중 플래그가 설정되어 있으면, "NotSupportedError" DOMException를 발생시킵니다.

  9. CustomElementRegistry요소 정의 실행 중 플래그를 설정합니다.

  10. formAssociated를 false로 설정합니다.

  11. disableInternals를 false로 설정합니다.

  12. disableShadow를 false로 설정합니다.

  13. observedAttributes를 빈 sequence<DOMString>으로 설정합니다.

  14. 예외를 잡으면서 다음 하위 단계를 실행합니다:

    1. prototype을 ? Get(constructor, "prototype")로 설정합니다.

    2. Type(prototype)이 Object가 아닌 경우, TypeError 예외를 발생시킵니다.

    3. "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback" 키를 가진 lifecycleCallbacks라는 맵을 만들고, 각 항목의 값을 null로 설정합니다.

    4. 이전 단계에 나열된 순서대로 lifecycleCallbacks의 각 키 callbackName에 대해:

      1. callbackValue를 ? Get(prototype, callbackName)로 설정합니다.

      2. callbackValue가 undefined가 아닌 경우, callbackName 키와 함께 lifecycleCallbacks의 항목 값에 callbackValue를 Web IDL Function 콜백 유형으로 변환한 결과를 설정합니다. 변환 중 발생한 예외는 다시 던집니다.

    5. "attributeChangedCallback" 키의 값이 null이 아닌 경우:

      1. observedAttributesIterable를 ? Get(constructor, "observedAttributes")로 설정합니다.

      2. observedAttributesIterable이 undefined가 아닌 경우, observedAttributesobservedAttributesIterablesequence<DOMString>으로 변환한 결과로 설정합니다. 변환 중 발생한 예외는 다시 던집니다.

    6. disabledFeatures를 빈 sequence<DOMString>으로 설정합니다.

    7. disabledFeaturesIterable를 ? Get(constructor, "disabledFeatures")로 설정합니다.

    8. disabledFeaturesIterable이 undefined가 아닌 경우, disabledFeaturesdisabledFeaturesIterablesequence<DOMString>으로 변환한 결과로 설정합니다. 변환 중 발생한 예외는 다시 던집니다.

    9. disabledFeatures가 "internals"를 포함하는 경우 disableInternals를 true로 설정합니다.

    10. disabledFeatures가 "shadow"를 포함하는 경우 disableShadow를 true로 설정합니다.

    11. formAssociatedValue를 ? Get(constructor, "formAssociated")로 설정합니다.

    12. formAssociatedformAssociatedValueboolean으로 변환한 결과로 설정합니다. 변환 중 발생한 예외는 다시 던집니다.

    13. formAssociated가 true인 경우, "formAssociatedCallback", "formResetCallback", "formDisabledCallback", "formStateRestoreCallback"에 대해 callbackName을 설정합니다:

      1. callbackValue를 ? Get(prototype, callbackName)로 설정합니다.

      2. callbackValue가 undefined가 아닌 경우, callbackName 키와 함께 lifecycleCallbacks의 항목 값에 callbackValue를 Web IDL Function 콜백 유형으로 변환한 결과를 설정합니다. 변환 중 발생한 예외는 다시 던집니다.

    그런 다음, 위의 단계가 예외를 발생시키든 말든 다음 하위 단계를 수행합니다:

    1. CustomElementRegistry요소 정의 실행 중 플래그를 해제합니다.

    마지막으로, 첫 번째 하위 단계 세트가 예외를 발생시킨 경우, 해당 예외를 다시 던져 이 알고리즘을 종료합니다. 그렇지 않으면 계속 진행합니다.

  15. definition커스텀 요소 정의의 새로운 항목으로 설정하고, name 이름, localName 로컬 이름, constructor 생성자, observedAttributes 관찰된 속성, lifecycleCallbacks 생명 주기 콜백, formAssociated 양식 연관, disableInternals 비활성화 내부, disableShadow 비활성화 섀도우로 설정합니다.

  16. definition을 이 CustomElementRegistry에 추가합니다.

  17. document를 이 CustomElementRegistry관련 글로벌 객체연관된 Document로 설정합니다.

  18. upgrade candidates섀도우 포함 후손document의 HTML 네임스페이스에 있는 모든 요소로 설정하고, 로컬 이름이 localName인 요소를 포함합니다. 또한, extends가 null이 아닌 경우, nameis과 일치하는 요소만 포함합니다.

  19. upgrade candidates에 있는 각 요소 element에 대해 커스텀 요소 업그레이드 반응을 대기열에 추가합니다, 주어진 elementdefinition을 사용합니다.

  20. CustomElementRegistry정의된 시점 약속 맵name 키가 포함된 항목이 있는 경우:

    1. promise를 해당 항목의 값으로 설정합니다.

    2. promiseconstructor로 해결합니다.

    3. CustomElementRegistry정의된 시점 약속 맵에서 name 키가 있는 항목을 삭제합니다.

호출되면, get(name) 메서드는 다음 단계를 수행해야 합니다:

  1. CustomElementRegistryname name에 대한 항목이 포함된 경우, 해당 항목의 constructor를 반환합니다.

  2. 그렇지 않으면, undefined를 반환합니다.

CustomElementRegistry/getName

Firefox116+🔰 preview+Chrome117+
Opera?Edge117+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

getName(constructor) 메서드의 단계는 다음과 같습니다:

  1. CustomElementRegistryconstructor constructor에 대한 항목이 포함된 경우, 해당 항목의 name을 반환합니다.

  2. null을 반환합니다.

호출되면, whenDefined(name) 메서드는 다음 단계를 수행해야 합니다:

  1. name유효한 커스텀 요소 이름이 아닌 경우, promise가 "SyntaxError" DOMException으로 거부됩니다.

  2. CustomElementRegistryname name에 대한 항목이 포함된 경우, promise가 해당 항목의 constructor로 해결됩니다.

  3. map을 이 CustomElementRegistrywhen-defined promise map으로 설정합니다.

  4. mapname 키를 가진 항목이 포함되지 않은 경우, mapname 키와 새로운 promise를 값으로 하는 항목을 만듭니다.

  5. promisemap에서 name 키를 가진 항목의 값으로 설정합니다.

  6. promise를 반환합니다.

whenDefined() 메서드는 모든 적절한 커스텀 요소정의될 때까지 작업을 수행하지 않도록 할 수 있습니다. 이 예에서 우리는 :defined 가상 클래스와 결합하여 동적으로 로드된 기사 내용이 해당 콘텐츠에 사용되는 모든 자율 커스텀 요소가 정의될 때까지 숨겨지도록 합니다.

articleContainer.hidden = true;

fetch(articleURL)
  .then(response => response.text())
  .then(text => {
    articleContainer.innerHTML = text;

    return Promise.all(
      [...articleContainer.querySelectorAll(":not(:defined)")]
        .map(el => customElements.whenDefined(el.localName))
    );
  })
  .then(() => {
    articleContainer.hidden = false;
  });

호출되면, upgrade(root) 메서드는 다음 단계를 수행해야 합니다:

  1. candidates목록으로 설정합니다. 이 목록은 root섀도우 포함 후손 요소들로 구성되며, 섀도우 포함 트리 순서에 따라 정렬됩니다.

  2. candidate에 대해, 업그레이드를 시도합니다 candidate.

upgrade() 메서드를 사용하면 원하는 시점에 요소를 업그레이드할 수 있습니다. 일반적으로 요소는 연결되었을 때 자동으로 업그레이드되지만, 이 메서드는 요소를 연결하기 전에 업그레이드가 필요할 경우 사용할 수 있습니다.

const el = document.createElement("spider-man");

class SpiderMan extends HTMLElement {}
customElements.define("spider-man", SpiderMan);

console.assert(!(el instanceof SpiderMan)); // 아직 업그레이드되지 않음

customElements.upgrade(el);
console.assert(el instanceof SpiderMan);    // 업그레이드됨!

4.13.5 업그레이드

요소를 업그레이드하려면, 커스텀 요소 정의 definition과 요소 element를 입력으로 받아 다음 단계를 수행하세요:

  1. element커스텀 요소 상태가 "undefined" 또는 "uncustomized"가 아닌 경우, 이 작업을 종료하세요.

    다음 예제와 같이 이 알고리즘의 재진입 호출로 인해 이러한 상황이 발생할 수 있습니다:

    <!DOCTYPE html>
    <x-foo id="a"></x-foo>
    <x-foo id="b"></x-foo>
    
    <script>
    // "a"와 "b" 모두에 대해 업그레이드 반응을 큐에 추가합니다
    customElements.define("x-foo", class extends HTMLElement {
      constructor() {
        super();
    
        const b = document.querySelector("#b");
        b.remove();
    
        // 이 생성자가 "a"에 대해 실행되는 동안, "b"는 아직
        // 정의되지 않았기 때문에 문서에 삽입하면 "b"에 대한 두 번째
        // 업그레이드 반응이 큐에 추가됩니다.
    
        document.body.appendChild(b);
    
      }
    })
    </script>

    따라서 이 단계는 "b"에 대해 요소 업그레이드가 두 번째로 호출될 때 알고리즘을 조기에 종료합니다.

  2. element커스텀 요소 정의definition으로 설정합니다.

  3. element커스텀 요소 상태를 "failed"로 설정합니다.

    업그레이드가 성공한 후에 "custom"으로 설정됩니다. 지금은 "failed"로 설정하여 모든 재진입 호출이 위의 조기 종료 단계에 도달하게 됩니다.

  4. attribute에 대해 element속성 목록에서 순서대로 커스텀 요소 콜백 반응을 큐에 추가하고, element, 콜백 이름 "attributeChangedCallback", 및 attribute의 로컬 이름, null, attribute의 값 및 attribute의 네임스페이스를 포함하는 인수 목록을 전달합니다.

  5. element연결된 상태인 경우, 커스텀 요소 콜백 반응을 큐에 추가하고, element, 콜백 이름 "connectedCallback", 및 빈 인수 목록을 전달합니다.

  6. definition구성 스택의 끝에 element를 추가합니다.

  7. definition생성자C로 설정합니다.

  8. 다음 하위 단계를 예외를 처리하며 실행하세요:

    1. definition섀도우 비활성화가 true이고 element섀도우 루트가 null이 아닌 경우, "NotSupportedError" DOMException을 발생시킵니다.

      이것은 attachShadow()커스텀 요소 정의 조회를 사용하지 않는 반면, attachInternals()는 사용하는 것과 같은 상황을 처리하기 위해 필요합니다.

    2. element커스텀 요소 상태를 "precustomized"로 설정합니다.

    3. C생성하는 결과를 constructResult로 설정하고, 인수는 없습니다.

      C비표준적으로 [CEReactions] 확장된 속성으로 표시된 API를 사용하는 경우, 이 알고리즘의 시작에서 큐에 추가된 반응은 이 단계에서 C가 완료되고 이 알고리즘으로 제어가 반환되기 전에 실행됩니다. 그렇지 않으면, C와 업그레이드 과정의 나머지 부분이 완료된 후에 실행됩니다.

    4. SameValue(constructResult, element)가 false이면 TypeError를 발생시킵니다.

      이 상황은 Csuper()를 호출하기 전에 동일한 커스텀 요소의 다른 인스턴스를 생성하거나, C가 JavaScript의 return-재정의 기능을 사용하여 생성자에서 임의의 HTMLElement 객체를 반환하는 경우 발생할 수 있습니다.

    그런 다음, 위의 단계에서 예외가 발생했는지 여부에 관계없이 다음 하위 단계를 수행하세요:

    1. definition구성 스택에서 마지막 항목을 제거합니다.

      Csuper()를 호출하고 (표준적이라면), 이 호출이 성공하면, 이 항목은 이 알고리즘의 시작에서 푸시된 element를 대체한 이미 생성됨 표시자가 됩니다. (이 교체 작업은 HTML 요소 생성자가 수행합니다.)

      Csuper()를 호출하지 않거나 (즉, 비표준적), 또는 HTML 요소 생성자의 모든 단계에서 예외가 발생한 경우, 이 항목은 여전히 element일 것입니다.

    마지막으로, 위의 단계에서 예외가 발생한 경우:

    1. element커스텀 요소 정의를 null로 설정합니다.

    2. element커스텀 요소 반응 큐를 비웁니다.

    3. 예외를 재발생시켜 이 알고리즘을 종료합니다.

    위의 단계에서 예외가 발생한 경우, element커스텀 요소 상태는 "failed" 또는 "precustomized"로 남아 있을 것입니다.

  9. element폼 연관 커스텀 요소인 경우:

    1. element폼 소유자를 재설정합니다. element 요소와 연관되어 있으면, 커스텀 요소 콜백 반응을 큐에 추가하고, element, 콜백 이름 "formAssociatedCallback", 및 « 연관된 »을 전달합니다.

    2. element비활성화 상태인 경우, 커스텀 요소 콜백 반응을 큐에 추가하고, element, 콜백 이름 "formDisabledCallback" 및 « true »를 전달합니다.

  10. element커스텀 요소 상태를 "custom"으로 설정합니다.

요소 업그레이드를 시도하려면, 요소 element를 입력으로 받아 다음 단계를 수행하세요:

  1. element노드 문서, element의 네임스페이스, element의 로컬 이름, 및 elementis을 입력으로 받아 커스텀 요소 정의를 조회한 결과를 definition으로 설정합니다.

  2. definition이 null이 아닌 경우, elementdefinition을 입력으로 받아 커스텀 요소 업그레이드 반응을 큐에 추가합니다.

4.13.6 커스텀 요소 반응

커스텀 요소는 특정 상황에 반응하여 작성자 코드를 실행할 수 있는 능력을 가지고 있습니다:

우리는 이러한 반응들을 커스텀 요소 반응이라고 부릅니다.

커스텀 요소 반응을 호출하는 방법은 신중하게 처리됩니다. 이는 민감한 작업 중에 작성자 코드를 실행하지 않도록 하기 위함입니다. 효과적으로, 이러한 반응들은 "사용자 스크립트로 돌아가기 직전"까지 지연됩니다. 이는 대부분의 경우 이러한 반응들이 동기적으로 실행되는 것처럼 보이지만, 복잡한 복합 작업(예: 복제 또는 범위 조작)의 경우에는 관련된 사용자 에이전트 처리 단계가 모두 완료된 후에 일괄 처리로 실행됩니다.

또한, 이러한 반응들의 정확한 순서는 아래에 설명된 다소 복잡한 스택-큐 시스템을 통해 관리됩니다. 이 시스템의 목적은 커스텀 요소 반응이 항상 단일 커스텀 요소의 로컬 컨텍스트 내에서 적어도 트리거링된 동작과 같은 순서로 호출되도록 보장하는 것입니다. (커스텀 요소 반응 코드가 자체적으로 변형을 수행할 수 있기 때문에 여러 요소에 걸쳐 전역 순서를 보장할 수는 없습니다.)


모든 유사 출처 윈도우 에이전트커스텀 요소 반응 스택을 가지고 있으며, 이는 초기에는 비어 있습니다. 유사 출처 윈도우 에이전트현재 요소 큐요소 큐의 최상위에 있는 커스텀 요소 반응 스택입니다. 스택의 각 항목은 초기에는 비어 있는 요소 큐입니다. 커스텀 요소는 아니지만, 이 큐는 업그레이드에도 사용됩니다.

모든 커스텀 요소 반응 스택은 초기에는 비어 있는 백업 요소 큐를 가지고 있습니다. 요소들은 백업 요소 큐에 푸시됩니다. 이는 [CEReactions]으로 표시된 API를 통해 처리되지 않는 DOM 작업 또는 파서의 토큰에 대한 요소 생성 알고리즘을 수행할 때 발생합니다. 예를 들어, 사용자가 시작한 편집 작업이 편집 가능 요소의 자식 요소 또는 속성을 수정할 때 발생할 수 있습니다. 백업 요소 큐를 처리할 때 재진입을 방지하기 위해 각 커스텀 요소 반응 스택에는 초기에는 설정되지 않은 백업 요소 큐 처리 플래그도 있습니다.

모든 요소는 초기에는 비어 있는 커스텀 요소 반응 큐를 가지고 있습니다. 커스텀 요소 반응 큐의 각 항목은 다음 두 가지 유형 중 하나입니다:

이 모든 것은 아래의 도식에서 요약됩니다:

커스텀 요소 반응 스택은 요소 큐의 스택으로 구성됩니다. 특정 큐를 확대해보면 <x-a>, <x-b>, <x-c>와 같은 여러 요소가 포함되어 있는 것을 볼 수 있습니다. 큐 내의 특정 요소는 커스텀 요소 반응 큐를 가지고 있으며, 반응 큐에는 업그레이드, 속성 변경, 또 다른 속성 변경, 연결과 같은 다양한 반응이 포함되어 있습니다.

적절한 요소 큐에 요소를 큐에 추가하려면, 요소 element를 받아 다음 단계를 수행하세요:

  1. reactionsStackelement관련 에이전트커스텀 요소 반응 스택으로 설정합니다.

  2. reactionsStack이 비어 있으면:

    1. elementreactionsStack백업 요소 큐에 추가합니다.

    2. reactionsStack백업 요소 큐 처리 플래그가 설정되어 있으면 반환합니다.

    3. reactionsStack백업 요소 큐 처리 플래그를 설정합니다.

    4. 마이크로태스크를 큐에 추가하여 다음 단계를 수행합니다:

      1. reactionsStack백업 요소 큐에서 커스텀 요소 반응을 호출합니다.

      2. reactionsStack백업 요소 큐 처리 플래그를 해제합니다.

  3. 그렇지 않으면, elementelement관련 에이전트현재 요소 큐에 추가합니다.

커스텀 요소 콜백 반응을 큐에 추가하려면, 커스텀 요소 element, 콜백 이름 callbackName, 및 인수 목록 args를 받아 다음 단계를 수행하세요:

  1. definitionelement커스텀 요소 정의로 설정합니다.

  2. callbackdefinition라이프사이클 콜백callbackName 키에 해당하는 값으로 설정합니다.

  3. callback이 null이면 반환합니다.

  4. callbackName이 "attributeChangedCallback"이면:

    1. attributeNameargs의 첫 번째 요소로 설정합니다.

    2. definition관찰된 속성attributeName을 포함하지 않으면 반환합니다.

  5. 콜백 함수 callback과 인수 args를 포함하는 새 콜백 반응element커스텀 요소 반응 큐에 추가합니다.

  6. element적절한 요소 큐에 큐에 추가합니다.

커스텀 요소 업그레이드 반응을 큐에 추가하려면, 요소 element커스텀 요소 정의 definition을 받아 다음 단계를 수행하세요:

  1. 커스텀 요소 반응 큐업그레이드 반응을 추가하고, 커스텀 요소 정의 definition을 설정합니다.

  2. element적절한 요소 큐에 큐에 추가합니다.

커스텀 요소 반응을 호출하려면 요소 큐 queue에서 다음 단계를 수행하세요:

  1. queue비어 있지 않을 동안:

    1. 큐에서 추출하여 element를 얻습니다.

    2. reactionselement커스텀 요소 반응 큐로 설정합니다.

    3. reactions이 비어 있을 때까지 반복합니다:

      1. reactions의 첫 번째 요소를 제거하고, reaction을 그 요소로 설정합니다. reaction의 유형에 따라 다음을 수행합니다:

        업그레이드 반응

        커스텀 요소 업그레이드reaction커스텀 요소 정의를 사용하여 element에 수행합니다.

        이 과정에서 예외가 발생하면, 이를 캐치하고, reaction커스텀 요소 정의의 대응하는 JavaScript 객체의 연결된 영역전역 객체보고합니다.

        콜백 반응

        콜백 함수reaction의 인수와 "보고"와 함께 element콜백 this 값을 설정하여 호출합니다.


커스텀 엘리먼트 반응이 적절하게 트리거되도록 하기 위해, 우리는 [CEReactions] IDL 확장 속성을 도입했습니다. 이 속성은 관련된 알고리즘이 추가 단계로 보완되어 커스텀 엘리먼트 반응을 적절하게 추적하고 호출할 수 있도록 합니다.

[CEReactions] 확장 속성은 인수를 취하지 않으며, 작업, 속성, 세터 또는 딜리터 외의 항목에 나타나서는 안 됩니다. 또한, 읽기 전용 속성에서는 나타나서는 안 됩니다.

[CEReactions] 확장 속성으로 주석이 달린 작업, 속성, 세터 또는 딜리터는 설명서에 명시된 단계 대신 다음 단계를 실행해야 합니다:

  1. 이 객체의 관련 에이전트커스텀 엘리먼트 반응 스택에 새 엘리먼트 큐푸시합니다.

  2. 이 구조체에 대해 원래 지정된 단계를 실행하고, 발생하는 예외를 잡습니다. 단계가 값을 반환하면, value를 반환된 값으로 설정합니다. 예외가 발생하면, exception을 발생한 예외로 설정합니다.

  3. 이 객체의 관련 에이전트커스텀 엘리먼트 반응 스택에서 팝핑한 결과를 queue로 설정합니다.

  4. queue에서 커스텀 엘리먼트 반응을 호출합니다.

  5. 원래 단계에서 exception 예외가 발생한 경우, exception을 다시 발생시킵니다.

  6. 원래 단계에서 value 값이 반환된 경우, value를 반환합니다.

이 확장 속성의 의도는 다소 미묘합니다. 이 목표를 달성하는 한 가지 방법은 모든 작업, 속성, 세터 및 딜리터에 이러한 단계를 삽입하고, 구현자가 불필요한 경우(예: DOM 변경이 발생하지 않아 커스텀 엘리먼트 반응이 발생할 가능성이 없는 경우)를 최적화할 수 있도록 허용하는 것입니다.

그러나 실제로 이러한 부정확성은 커스텀 엘리먼트 반응의 상호 운용 가능한 구현을 방해할 수 있습니다. 일부 구현은 이러한 단계를 호출하는 것을 잊을 수 있기 때문입니다. 대신, 우리는 관련된 모든 IDL 구조에 명시적으로 주석을 달아 상호 운용 가능한 동작을 보장하고, 구현자가 이러한 단계가 필요한 모든 경우를 쉽게 식별할 수 있도록 하는 접근 방식을 선택했습니다.

사용자 에이전트에 의해 도입된 비표준 API가 커스텀 엘리먼트 콜백 반응을 등록하거나 커스텀 엘리먼트 업그레이드 반응을 등록하는 등, 예를 들어 어떤 속성이나 자식 요소를 수정하여 DOM을 변경할 수 있는 경우, 이러한 API도 [CEReactions] 속성으로 꾸며야 합니다.

이 글을 쓰는 시점에서, 다음과 같은 비표준 또는 아직 표준화되지 않은 API가 이 범주에 속하는 것으로 알려져 있습니다:

4.13.7 엘리먼트 내부

특정 기능은 커스텀 엘리먼트 소비자가 아닌 커스텀 엘리먼트 작성자가 사용할 수 있도록 설계되었습니다. 이러한 기능은 element.attachInternals() 메서드를 통해 제공되며, 이 메서드는 ElementInternals의 인스턴스를 반환합니다. ElementInternals의 속성과 메서드는 사용자 에이전트가 모든 엘리먼트에 제공하는 내부 기능을 제어할 수 있게 해줍니다.

element.attachInternals()

커스텀 엘리먼트 element를 대상으로 하는 ElementInternals 객체를 반환합니다. element커스텀 엘리먼트가 아니거나, 엘리먼트 정의의 일부로 "internals" 기능이 비활성화된 경우 또는 동일한 엘리먼트에서 두 번 호출된 경우 예외를 발생시킵니다.

모든 HTMLElement부착된 내부 (null 또는 ElementInternals 객체)을 가지며, 초기값은 null입니다.

HTMLElement/attachInternals

모든 현재 엔진에서 지원됨.

Firefox93+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

attachInternals() 메서드 단계는 다음과 같습니다:

  1. thisis이 null이 아니면 "NotSupportedError" DOMException을 발생시킵니다.

  2. 커스텀 엘리먼트 정의를 조회한 결과를 definition으로 설정합니다. 조회는 this노드 문서, 네임스페이스, 로컬 이름, 및 is을 null로 주어 수행됩니다.

  3. definition이 null이면 "NotSupportedError" DOMException을 발생시킵니다.

  4. definition내부 기능 비활성화가 true이면 "NotSupportedError" DOMException을 발생시킵니다.

  5. this부착된 내부가 null이 아니면 "NotSupportedError" DOMException을 발생시킵니다.

  6. this커스텀 엘리먼트 상태가 "precustomized" 또는 "custom"이 아니면 "NotSupportedError" DOMException을 발생시킵니다.

  7. this부착된 내부this대상 엘리먼트로 하는 새로운 ElementInternals 인스턴스로 설정합니다.

  8. this부착된 내부를 반환합니다.

4.13.7.1 ElementInternals 인터페이스

ElementInternals

모든 현재 엔진에서 지원됨.

Firefox93+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

ElementInternals 인터페이스의 IDL은 다음과 같으며, 다양한 연산과 속성은 다음 섹션에서 정의됩니다:

[Exposed=Window]
interface ElementInternals {
  // Shadow root 접근
  readonly attribute ShadowRoot? shadowRoot;

  // 폼과 연관된 커스텀 엘리먼트
  undefined setFormValue((File or USVString or FormData)? value,
                         optional (File or USVString or FormData)? state);

  readonly attribute HTMLFormElement? form;

  undefined setValidity(optional ValidityStateFlags flags = {},
                        optional DOMString message,
                        optional HTMLElement anchor);
  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();

  readonly attribute NodeList labels;

  // 커스텀 상태 의사 클래스
  [SameObject] readonly attribute CustomStateSet states;
};

// 접근성 의미 체계
ElementInternals 포함함 ARIAMixin;

dictionary ValidityStateFlags {
  boolean valueMissing = false;
  boolean typeMismatch = false;
  boolean patternMismatch = false;
  boolean tooLong = false;
  boolean tooShort = false;
  boolean rangeUnderflow = false;
  boolean rangeOverflow = false;
  boolean stepMismatch = false;
  boolean badInput = false;
  boolean customError = false;
};

ElementInternals대상 엘리먼트를 가지며, 이는 커스텀 엘리먼트입니다.

4.13.7.2 Shadow root 접근
internals.shadowRoot

Returns the ShadowRoot for internals대상 엘리먼트shadow 호스트인 경우, 그렇지 않으면 null을 반환합니다.

ElementInternals/shadowRoot

모든 현재 엔진에서 지원됨.

Firefox93+Safari16.4+Chrome88+
Opera?Edge88+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

shadowRoot getter 단계는 다음과 같습니다:

  1. targetthis대상 엘리먼트로 설정합니다.

  2. targetshadow 호스트가 아니라면, null을 반환합니다.

  3. shadowtargetshadow root로 설정합니다.

  4. 만약 shadow엘리먼트 internals에 사용할 수 없음으로 설정되어 있다면, null을 반환합니다.

  5. shadow를 반환합니다.

4.13.7.3 양식 관련 커스텀 요소
internals.setFormValue(value)

internals대상 요소상태제출 값value로 설정합니다.

만약 value가 null이면, 해당 요소는 양식 제출에 참여하지 않습니다.

internals.setFormValue(value, state)

internals대상 요소제출 값value로 설정하고, 상태state로 설정합니다.

만약 value가 null이면, 해당 요소는 양식 제출에 참여하지 않습니다.

internals.form

internals대상 요소양식 소유자를 반환합니다.

internals.setValidity(flags, message [, anchor ])

internals대상 요소flags 인수로 지정된 제약 조건이 있는 상태로 표시하고, 요소의 유효성 메시지를 message로 설정합니다. anchor가 지정된 경우, 사용자 에이전트는 internals대상 요소의 제약 조건 문제를 표시할 때 이를 사용할 수 있습니다.

internals.setValidity({})

internals대상 요소제약 조건을 만족하는 상태로 표시합니다.

internals.willValidate

internals대상 요소가 양식 제출 시 유효성 검사를 받을지 여부를 반환합니다.

internals.validity

internals대상 요소에 대한 ValidityState 객체를 반환합니다.

internals.validationMessage

만약 internals대상 요소가 유효성 검사를 받는다면 사용자에게 표시될 오류 메시지를 반환합니다.

valid = internals.checkValidity()

internals대상 요소에 유효성 문제가 없으면 true를 반환하고, 그렇지 않으면 false를 반환하며 invalid 이벤트를 해당 요소에 발송합니다.

valid = internals.reportValidity()

internals대상 요소에 유효성 문제가 없으면 true를 반환하고, 그렇지 않으면 false를 반환하며 invalid 이벤트를 해당 요소에 발송하고(이벤트가 취소되지 않은 경우), 문제를 사용자에게 보고합니다.

internals.labels

internals대상 요소와 연결된 모든 NodeList를 반환합니다.

양식 관련 커스텀 요소제출 값을 가지고 있습니다. 이는 양식 제출 시 하나 이상의 항목을 제공하는 데 사용됩니다. 제출 값의 초기 값은 null이며, 제출 값은 null, 문자열, 파일 또는 목록일 수 있습니다.

양식 관련 커스텀 요소상태를 가지고 있습니다. 이는 사용자 에이전트가 요소의 사용자 입력을 복원하는 데 사용할 수 있는 정보입니다. 상태의 초기 값은 null이며, 상태는 null, 문자열, 파일, 또는 목록일 수 있습니다.

setFormValue() 메서드는 커스텀 요소 작성자가 요소의 제출 값상태를 설정하여 사용자 에이전트에 이를 전달하는 데 사용됩니다.

사용자 에이전트가 양식 관련 커스텀 요소의 상태를 복원하는 것이 좋다고 판단될 때, 예를 들어 탐색 후 또는 사용자 에이전트를 다시 시작한 후, 해당 요소와 "formStateRestoreCallback" 콜백 이름 및 복원할 상태를 포함하는 인수 목록과 "restore"를 사용하여 커스텀 요소 콜백 반응을 대기열에 추가할 수 있습니다.

만약 사용자 에이전트에 양식 작성 지원 기능이 있는 경우, 해당 기능이 호출될 때 양식 관련 커스텀 요소와 함께, "formStateRestoreCallback" 콜백 이름과 상태 값 및 "자동 완성"을 포함하는 인수 목록을 사용하여 커스텀 요소 콜백 반응을 대기열에 추가할 수 있습니다.

일반적으로 상태는 사용자가 지정한 정보이며, 제출 값은 서버에 제출하기 적합한 캐노니컬화 또는 정리된 값입니다. 다음 예제는 이를 구체화합니다:

예를 들어, 사용자가 날짜를 지정하도록 요구하는 양식 관련 커스텀 요소가 있다고 가정합니다. 사용자가 "3/15/2019"을 지정했지만, 컨트롤은 서버에 "2019-03-15"를 제출하고자 합니다. "3/15/2019"은 요소의 상태가 되고, "2019-03-15"제출 값이 됩니다.

기존의 체크박스 input 유형의 동작을 모방하는 커스텀 요소를 개발한다고 가정합니다. 제출 값value 콘텐츠 속성의 값 또는 문자열 "on"이 됩니다. 상태"checked", "unchecked", "checked/indeterminate", 또는 "unchecked/indeterminate" 중 하나가 됩니다.

ElementInternals/setFormValue

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

setFormValue(value, state) 메서드 단계는 다음과 같습니다:

  1. elementthis대상 요소로 설정합니다.

  2. element양식 관련 커스텀 요소가 아닌 경우, "NotSupportedError" DOMException을 던집니다.

  3. 대상 요소제출 값value로 설정합니다. 만약 valueFormData 객체가 아닌 경우, 또는 그렇지 않으면 value항목 목록복제본으로 설정합니다.

  4. 만약 함수의 state 인수가 생략된 경우, element상태제출 값으로 설정합니다.

  5. 그렇지 않고, stateFormData 객체인 경우, element상태state항목 목록복제본으로 설정합니다.

  6. 그렇지 않으면, element상태state로 설정합니다.


양식 관련 커스텀 요소valueMissing, typeMismatch, patternMismatch, tooLong, tooShort, rangeUnderflow, rangeOverflow, stepMismatch, 그리고 customError라는 유효성 플래그를 가지고 있습니다. 이 플래그들은 처음에는 모두 false로 설정됩니다.

양식 관련 커스텀 요소유효성 메시지 문자열을 가집니다. 처음에는 빈 문자열로 설정됩니다.

양식 관련 커스텀 요소유효성 앵커 요소를 가집니다. 처음에는 null로 설정됩니다.

ElementInternals/setValidity

모든 현재 엔진에서 지원됨.

Firefox98+Safari16.4+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

setValidity(flags, message, anchor) 메서드 단계는 다음과 같습니다:

  1. elementthis대상 요소로 설정합니다.

  2. element양식 관련 커스텀 요소가 아닌 경우, "NotSupportedError" DOMException을 던집니다.

  3. 만약 flags에 하나 이상의 true 값이 포함되어 있고 message가 주어지지 않았거나 빈 문자열인 경우, TypeError를 던집니다.

  4. flagvalue 항목에 대해 element의 해당 이름을 가진 유효성 플래그를 value로 설정합니다.

  5. 만약 message가 주어지지 않았거나 element의 모든 유효성 플래그가 false인 경우, element유효성 메시지를 빈 문자열로 설정하고, 그렇지 않으면 message로 설정합니다.

  6. 만약 elementcustomError 유효성 플래그가 true인 경우, element커스텀 유효성 오류 메시지element유효성 메시지로 설정합니다. 그렇지 않은 경우, element커스텀 유효성 오류 메시지를 빈 문자열로 설정합니다.

  7. 만약 anchor가 주어지지 않은 경우, element유효성 앵커를 null로 설정합니다. 그렇지 않으면, 만약 anchorelement그림자 포함 자손이 아닌 경우, "NotFoundError" DOMException을 던집니다. 그렇지 않으면, element유효성 앵커anchor로 설정합니다.

4.13.7.4 접근성 의미
internals.role [ = value ]

internals대상 요소에 대한 기본 ARIA 역할을 설정하거나 검색합니다. 이 역할은 페이지 작성자가 role 속성을 사용하여 이를 덮어쓰지 않는 한 사용됩니다.

internals.aria* [ = value ]

internals대상 요소에 대한 기본 ARIA 상태 또는 속성 값을 설정하거나 검색합니다. 이는 페이지 작성자가 aria-* 속성을 사용하여 이를 덮어쓰지 않는 한 사용됩니다.

커스텀 요소에는 내부 콘텐츠 속성 맵이 있으며, 이는 초기에는 비어 있는 정렬된 맵입니다. 이 맵이 플랫폼 접근성 API에 어떤 영향을 미치는지에 대한 정보는 ARIA 및 플랫폼 접근성 API 관련 요구 사항 섹션을 참조하세요.

4.13.7.5 사용자 상태 의사 클래스
internals.states.add(value)

value 문자열을 요소의 상태 집합에 추가하여 의사 클래스로 노출합니다.

internals.states.has(value)

value가 요소의 상태 집합에 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

internals.states.delete(value)

요소의 상태 집합value가 있으면 이를 제거하고 true를 반환합니다. 그렇지 않으면 false를 반환합니다.

internals.states.clear()

요소의 상태 집합에서 모든 값을 제거합니다.

for (const stateName of internals.states)
for (const stateName of internals.states.entries())
for (const stateName of internals.states.keys())
for (const stateName of internals.states.values())

요소의 상태 집합에 있는 모든 값을 순회합니다.

internals.states.forEach(callback)

요소의 상태 집합에 있는 모든 값을 순회하며, 각 값에 대해 callback을 한 번씩 호출합니다.

internals.states.size

요소의 상태 집합에 있는 값의 수를 반환합니다.

커스텀 요소상태 집합을 가지며, 이는 초기에는 비어 있는 CustomStateSet입니다.

[Exposed=Window]
interface CustomStateSet {
  setlike<DOMString>;
};

states getter 단계는 this대상 요소상태 집합을 반환하는 것입니다.

상태 집합은 문자열 값의 존재/부재로 나타나는 부울 상태를 노출할 수 있습니다. 작성자가 세 가지 값을 가질 수 있는 상태를 노출하려는 경우, 이를 세 개의 독립적인 부울 상태로 변환할 수 있습니다. 예를 들어, readyState라는 상태가 "loading", "interactive", "complete" 값을 가지는 경우, 이를 세 개의 독립적인 부울 상태 "loading", "interactive", "complete"로 매핑할 수 있습니다.

// readyState를 어느 상태에서든 "complete"로 변경합니다.
this._readyState = "complete";
this._internals.states.delete("loading");
this._internals.states.delete("interactive");
this._internals.states.add("complete");

4.14 전용 요소가 없는 일반적인 관용구

4.14.1 브레드크럼 내비게이션

이 명세는 브레드크럼 내비게이션 메뉴를 설명하는 기계 가독성 방식은 제공하지 않습니다. 작성자는 단락 안에 일련의 링크를 사용하는 것이 권장됩니다. nav 요소는 이러한 단락이 내비게이션 블록임을 표시하기 위해 사용할 수 있습니다.

다음 예에서 현재 페이지는 두 경로를 통해 도달할 수 있습니다.

<nav>
<p>
 <a href="/">Main</a><a href="/products/">Products</a><a href="/products/dishwashers/">Dishwashers</a><a>Second hand</a>
</p>
<p>
 <a href="/">Main</a><a href="/second-hand/">Second hand</a><a>Dishwashers</a>
</p>
</nav>

4.14.2 태그 클라우드

이 명세는 페이지 그룹에 적용되는 키워드 목록(태그 클라우드라고도 함)을 마크업하기 위한 구체적인 마크업을 정의하지 않습니다. 일반적으로 작성자는 스타일 시트를 사용하여 숨기고 프레젠테이션 효과로 변환된 명시적인 인라인 카운트가 있는 ul 요소를 사용하거나 SVG를 사용하는 것이 권장됩니다.

여기, 짧은 태그 클라우드에 세 개의 태그가 포함되어 있습니다:

<style>
.tag-cloud > li > span { display: none; }
.tag-cloud > li { display: inline; }
.tag-cloud-1 { font-size: 0.7em; }
.tag-cloud-2 { font-size: 0.9em; }
.tag-cloud-3 { font-size: 1.1em; }
.tag-cloud-4 { font-size: 1.3em; }
.tag-cloud-5 { font-size: 1.5em; }

@media speech {
  .tag-cloud > li > span { display:inline }
}
</style>
...
<ul class="tag-cloud">
 <li class="tag-cloud-4"><a title="28 instances" href="/t/apple">apple</a> <span>(popular)</span>
 <li class="tag-cloud-2"><a title="6 instances"  href="/t/kiwi">kiwi</a> <span>(rare)</span>
 <li class="tag-cloud-5"><a title="41 instances" href="/t/pear">pear</a> <span>(very popular)</span>
</ul>

각 태그의 실제 빈도는 title 속성을 사용하여 제공합니다. CSS 스타일 시트는 마크업을 서로 다른 크기의 단어 클라우드로 변환하기 위해 제공되지만, CSS를 지원하지 않거나 시각적이지 않은 사용자 에이전트의 경우 마크업에는 태그의 빈도를 기준으로 "popular" 또는 "rare"와 같은 범주로 태그를 분류하는 주석이 포함되어 있어 모든 사용자가 이러한 정보를 활용할 수 있습니다.

ul 요소를 사용( ol 대신) 하는 이유는 순서가 그다지 중요하지 않기 때문입니다. 목록이 실제로는 알파벳순으로 정렬되어 있지만, 태그의 길이로 정렬되더라도 동일한 정보를 전달할 수 있습니다.

tag rel-키워드는 사용되지 않습니다. 이 a 요소들은 페이지 자체에 적용되는 태그를 나타내지 않기 때문입니다. 단지 태그 자체를 나열하는 인덱스의 일부일 뿐입니다.

4.14.3 대화

이 사양에서는 대화, 회의록, 채팅 기록, 대본의 대화, 인스턴트 메시지 로그, 그리고 여러 사람이 차례로 발언하는 기타 상황을 마크업할 특정 요소를 정의하지 않습니다.

대신, 작성자는 p 요소와 구두점을 사용하여 대화를 마크업하는 것이 권장됩니다. 스타일링 목적으로 발언자를 표시해야 하는 작성자는 span 또는 b를 사용하는 것이 좋습니다. 텍스트를 i 요소로 감싸서 무대 지시를 표시할 수 있습니다.

다음 예제는 Abbott와 Costello의 유명한 스케치 누가 1루에 있어에서 발췌한 부분을 사용하여 이를 설명합니다:

<p> Costello: 이봐, 1루수가 있어?
<p> Abbott: 물론이지.
<p> Costello: 누가 1루를 봐?
<p> Abbott: 맞아.
<p> Costello가 화가 난다.
<p> Costello: 매달 1루수에게 월급을 줄 때, 누가 그 돈을 받아?
<p> Abbott: 그 돈 전부.

다음 발췌 부분은 IM 대화 로그를 마크업하는 방법을 보여주며, 각 줄에 대한 유닉스 타임스탬프를 제공하기 위해 data 요소를 사용합니다. time 요소가 지원하지 않는 형식으로 타임스탬프가 제공됩니다. 따라서 data 요소가 대신 사용됩니다(유닉스 time_t 타임스탬프). 작성자가 time 요소에서 지원하는 날짜 및 시간 형식을 사용하여 데이터를 마크업하기를 원했다면, 이 요소를 data 대신 사용할 수 있었습니다. 이렇게 하면 데이터 분석 도구가 페이지 작성자와의 조정 없이도 타임스탬프를 명확하게 감지할 수 있어 유리할 수 있습니다.

<p> <data value="1319898155">14:22</data> <b>egof</b> 나는 그렇게 덕후가 아니야, 스타 트렉 에피소드의 30%만 봤어
<p> <data value="1319898192">14:23</data> <b>kaj</b> 스타 트렉 에피소드에서 얼마나 많은 것을 봤는지 알고 있다면, 당신은 논쟁할 수 없을 정도로 덕후야
<p> <data value="1319898200">14:23</data> <b>egof</b> 그것은 반박할 수 없어
<p> <data value="1319898228">14:23</data> <i>* kaj 눈을 깜빡임</i>
<p> <data value="1319898260">14:24</data> <b>kaj</b> 네가 도움을 주지 않아

HTML은 그래프를 마크업할 좋은 방법을 제공하지 않기 때문에 게임에서의 인터랙티브한 대화 설명을 마크업하기가 더 어렵습니다. 이 예제는 대화의 각 지점에서 가능한 응답을 나열하기 위해 dl 요소를 사용하는 하나의 가능성을 보여줍니다. 다른 옵션으로는 대화를 DOT 파일 형식으로 설명하고, 결과를 SVG 이미지로 출력하여 문서에 배치하는 방법이 있습니다. [DOT]

<p> 다음으로, 어부를 만나게 됩니다. 여러 가지 인사말 중 하나를 선택할 수 있습니다:
<dl>
 <dt> "안녕하세요!"
 <dd>
  <p> 그녀가 "안녕하세요, 어떻게 도와드릴까요?"라고 대답합니다; 당신은 다음과 같은 대답을 할 수 있습니다:
  <dl>
   <dt> "물고기를 사고 싶습니다."
   <dd> <p> 그녀가 물고기를 팔고 대화가 끝납니다.
   <dt> "배를 빌릴 수 있을까요?"
   <dd>
    <p> 그녀가 놀라서 "대가로 무엇을 제공하시겠습니까?"라고 묻습니다.
    <dl>
     <dt> "금화 다섯 개." (충분한 금화가 있다면)
     <dt> "금화 열 개." (충분한 금화가 있다면)
     <dt> "금화 열다섯 개." (충분한 금화가 있다면)
     <dd> <p> 그녀가 배를 빌려줍니다. 대화가 끝납니다.
     <dt> "물고기 하나." (하나 가지고 있다면)
     <dt> "신문 한 부." (하나 가지고 있다면)
     <dt> "조약돌 하나." (하나 가지고 있다면)
     <dd> <p> 그녀가 "사양할게요"라고 대답합니다. 이 시점에서 당신의 대화 선택지는 배를 빌려달라고 요청한 후와 동일하지만, 이전에 제안한 선택지는 제외됩니다.
    </dl>
   </dd>
  </dl>
 </dd>
 <dt> "다음 선거에서 저를 뽑아주세요!"
 <dd> <p> 그녀가 돌아섭니다. 대화가 끝납니다.
 <dt> "부인, 물고기가 도망가고 있는 거 아세요?"
 <dd>
  <p> 그녀가 회의적으로 바라보며 "물고기는 달릴 수 없어요, 아가씨"라고 말합니다.
  <dl>
   <dt> "당신이 맞았어요!"
   <dd> <p> 어부가 한숨을 쉬며 대화가 끝납니다.
   <dt> "농담이에요."
   <dd> <p> 그녀가 "좋은 농담이네요!"라고 대답합니다. 이 시점에서 당신의 대화 선택지는 앞서 "안녕하세요!" 이후와 동일합니다.
   <dt> "그럼 그들은 무엇을 하고 있는 거죠?"
   <dd> <p> 그녀가 물고기를 바라보고, 당신은 그녀의 배를 훔칠 기회를 갖습니다. 당신은 그렇게 하고 대화가 끝납니다.
  </dl>
 </dd>
</dl>

일부 게임에서는 대화가 더 단순합니다: 각 캐릭터는 그들이 하는 고정된 대사를 가지고 있습니다. 이 예에서 게임 FAQ/워크스루는 각 캐릭터의 알려진 가능한 응답 중 일부를 나열합니다:

<section>
 <h1>대화</h1>
 <p><small>일부 캐릭터는 상호 작용할 때마다 순서대로 대사를 반복하고, 다른 캐릭터는 그들의 대사 중에서 무작위로 선택합니다. 순서대로 응답하는 캐릭터는 아래 목록에서 번호가 매겨진 항목을 가지고 있습니다.</small>
 <h2>상점 주인</h2>
 <ul>
  <li>어떻게 도와드릴까요?
  <li>신선한 사과요!
  <li>여사님께 빵 한 덩이를 드릴까요?
 </ul>
 <h2>파일럿</h2>
 <p>사고 전:
 <ul>
  <li>나는 곧 출발해야 하니, 미안해!
  <li>미안해, 나는 출발 허가를 기다리고 있어, 그 후에 출발할 거야!
 </ul>
 <p>사고 후:
 <ol>
  <li>나는 곧 출발해야 하니, 미안해!
  <li>알겠어, 나는 지금 출발하지 않아, 내 비행기가 청소되고 있어.
  <li>알겠어, 청소 중이 아니고, 먼저 약간의 수리가 필요해.
  <li>알겠어, 알겠어, 그만 귀찮게 해! 사실은, 나는 추락했어.
 </ol>
 <h2>씨족장</h2>
 <p>첫 번째 씨족 회의 중:
 <ul>
  <li>이봐, 내 딸 본 적 있어? 분명히 또 뭔가 나쁜 짓을 꾸미고 있을 거야...
  <li>오늘 날씨가 좋네요, 그렇죠?
  <li>내 이름은 Bailey, Jeff Bailey야. 오늘 어떻게 도와드릴까요?
  <li>물 한 잔? 우물에서 갓 나온 물이에요!
 </ul>
 <p>지진 후:
 <ol>
  <li>모두 피난처에 안전하게 있으며, 불을 꺼야만 합니다!
  <li>나는 소방서에 가서 말할 테니, 계속 물을 뿌려줘!
 </ol>
</section>

4.14.4 각주

HTML은 각주를 마크업하는 전용 메커니즘을 제공하지 않습니다. 여기에 제안된 대안들이 있습니다.


짧은 인라인 주석의 경우, title 속성을 사용할 수 있습니다.

이 예제에서는 title 속성을 사용하여 각주와 유사한 내용을 대화의 두 부분에 주석으로 추가했습니다.

<p> <b>고객</b>: 안녕하세요! 불만을 접수하고 싶습니다. 안녕하세요, 아가씨?
<p> <b>상점 주인</b>: <span title="'무엇을'의 구어 발음">무엇을</span> 의미하시나요, 아가씨?
</p> </b>고객</b>: 아, 죄송합니다. 감기에 걸려서요. 불만을 접수하고 싶습니다.
</p> </b>상점 주인</b>: 죄송합니다, </span title="물론, 이것은 거짓말입니다.">우리는 점심 시간으로 문을 닫습니다</span>.

불행히도, title 속성에 의존하는 것은 현재 권장되지 않습니다. 많은 사용자 에이전트가 이 속성을 사양에서 요구하는 대로 접근 가능한 방식으로 노출하지 않기 때문입니다(예: 툴팁이 나타나기 위해 마우스와 같은 포인팅 장치를 요구하는데, 이는 키보드 전용 사용자와 터치 전용 사용자, 즉 현대의 스마트폰 또는 태블릿을 사용하는 사람들을 제외합니다).

title 속성이 사용되는 경우, CSS를 사용하여 해당 속성을 가진 요소에 독자의 관심을 끌 수 있습니다.

예를 들어, 다음 CSS는 title 속성을 가진 요소 아래에 점선 라인을 추가합니다.

[title] { border-bottom: thin dashed; }

긴 주석의 경우, a 요소를 사용하여 문서 내의 나중 요소를 가리켜야 합니다. 링크 내용은 대괄호 안에 숫자로 표시하는 것이 관례입니다.

이 예제에서는 대화 내 각주가 대화 아래의 단락과 연결됩니다. 그런 다음 단락은 다시 대화로 링크되어 사용자가 각주 위치로 돌아갈 수 있게 합니다.

<p> Announcer: Number 16: The <i>hand</i>.
<p> Interviewer: Good evening. I have with me in the studio tonight
Mr Norman St John Polevaulter, who for the past few years has been
contradicting people. Mr Polevaulter, why <em>do</em> you
contradict people?
<p> Norman: I don't. <sup><a href="#fn1" id="r1">[1]</a></sup>
<p> Interviewer: You told me you did!
...
<section>
 <p id="fn1"><a href="#r1">[1]</a> This is, naturally, a lie,
 but paradoxically if it were true he could not say so without
 contradicting the interviewer and thus making it false.</p>
</section>

사이드 노트의 경우, 특정 단어나 문장이 아닌 텍스트의 전체 섹션에 적용되는 긴 주석은 aside 요소를 사용해야 합니다.

이 예제에서는 대화 후에 사이드바가 제공되어 대화에 대한 컨텍스트를 제공합니다.

<p> <span class="speaker">고객</span>: 이 레코드는 사라서 사지 않겠습니다.
</p> </span class="speaker">상점 주인</span>: 죄송합니다?
</p> </span class="speaker">고객</span>: 이 레코드는 사라서 사지 않겠습니다.
</p> </span class="speaker">상점 주인</span>: 아니, 아니, 여기는 담배 가게입니다.
</aside> </p>1970년에, 대영제국은 폐허가 되었고, 외국 민족주의자들이 거리에서 자주 목격되었습니다. 그들 중 많은 이들이 헝가리인이었습니다(거리가 아니라, 외국 민족주의자들이). 슬프게도, Alexander Yalt는 무능하게 쓰여진 구문 책을 출판하고 있습니다.</aside>

도표나 표의 경우, 각주는 관련된 figcaption 또는 caption 요소 또는 주변의 서술문에서 포함될 수 있습니다.

이 예제에서는 각주가 설명된 표가 포함된 예제입니다. figure 요소가 사용되어 표와 각주를 조합한 전반적인 설명을 제공합니다.

<figure> </figcaption>표 1. 기사들을 위한 대안 활동.</figcaption> </table> </tr> </th> 활동
</th> </th> 장소
</th> 비용
</tr> </td></td> 가능한 곳 어디든지
</td> £0</sup><a href="#fn1">1</a></sup> </tr> </td> 루틴, 합창 장면</sup><a href="#fn2">2</a></sup> </td> 공개되지 않음
</td> 공개되지 않음
</tr> </td> 식사</sup><a href="#fn3">3</a></sup> </td> 카멜롯
</td> 햄, 잼, 스팸의 비용</sup><a href="#fn4">4</a></sup> </tr> </p id="fn1">1. 추정됨.</p> </p id="fn2">2. 발 동작이 훌륭함.</p> </p id="fn3">3. 품질이 '괜찮다'고 설명됨.</p> </p id="fn4">4. 많음.</p> </figure>

4.15 비활성화된 요소

다음 중 하나에 해당하는 경우 요소가 실제로 비활성화된 것으로 간주됩니다:

이 정의는 어떤 요소가 포커스할 수 있는지:enabled:disabled 가상 클래스와 일치하는지 결정하는 데 사용됩니다.

4.16 선택자와 CSS를 사용한 HTML 요소 일치

4.16.1 CSS 'attr()' 함수의 대소문자 구분

CSS Values and Units'attr()' 함수의 속성 이름에 대한 대소문자 구분을 호스트 언어에 의해 정의되도록 남겨둡니다. [CSSVALUES]

CSS 'attr()' 함수의 속성 이름 부분을 HTML 요소의 네임스페이스 없는 속성 이름과 비교할 때, CSS 'attr()' 함수의 이름 부분은 먼저 ASCII 소문자로 변환되어야 합니다. 다른 속성과 비교할 때는 원래의 대소문자로 비교해야 합니다. 두 경우 모두, 일치하려면 값이 동일해야 하며, 따라서 비교는 대소문자를 구분합니다.

이는 다음 섹션에 명시된 CSS 속성 선택자의 이름 부분을 비교하는 것과 동일합니다.

4.16.2 선택자의 대소문자 구분

Selectors는 요소 이름, 속성 이름 및 속성 값의 대소문자 구분을 호스트 언어에 의해 정의되도록 남겨둡니다. [SELECTORS]

CSS 요소 유형 선택자HTML 요소의 이름과 비교할 때, CSS 요소 유형 선택자는 먼저 ASCII 소문자로 변환되어야 합니다. 다른 요소와 비교할 때는 원래의 대소문자로 비교해야 합니다. 두 경우 모두, 일치하려면 값이 동일해야 하며, 따라서 비교는 대소문자를 구분합니다.

CSS 속성 선택자의 이름 부분을 HTML 요소의 속성 이름과 비교할 때, CSS 속성 선택자의 이름 부분은 먼저 ASCII 소문자로 변환되어야 합니다. 다른 속성과 비교할 때는 원래의 대소문자로 비교해야 합니다. 두 경우 모두, 비교는 대소문자를 구분합니다.

속성 선택자HTML 요소의 속성 이름 중 다음 이름을 가진 속성 값은 ASCII 대소문자 구분 없음으로 처리되어야 합니다:

예를 들어, 선택자 [bgcolor="#ffffff"]bgcolor 속성의 값이 #ffffff, #FFFFFF, #fffFFF 등을 포함하는 모든 HTML 요소와 일치합니다. 이는 bgcolor가 특정 요소(예: div)에 대해 아무런 영향을 미치지 않더라도 발생합니다.

선택자 [type=a s]type 속성의 값이 a인 HTML 요소와 일치하지만, A인 경우에는 일치하지 않습니다. 이는 s 플래그 때문에 발생합니다.

다른 모든 속성 값과 기타 항목은 선택자 일치 목적상 서로 동일한 것으로 간주되어야 합니다. 여기에는 다음이 포함됩니다:

Selectors비정상 모드 문서에서 요소와 일치할 때 ID 및 클래스 선택자(#foo.bar와 같은)가 ASCII 대소문자 구분 없음 방식으로 일치한다고 정의합니다. 그러나 속성 선택자에서 "id" 또는 "class"가 이름 부분으로 사용된 경우에는 적용되지 않습니다. 선택자 [class="foobar"]는 비정상 모드에서도 그 값을 대소문자 구분 방식으로 처리합니다.

4.16.3 의사 클래스

의사 클래스

HTML에서 사용할 수 있는 여러 동적 선택자가 있습니다. 이 섹션에서는 이러한 선택자가 HTML 요소와 일치하는 시점을 정의합니다. [SELECTORS] [CSSUI]

:defined

:defined

모든 최신 엔진에서 지원됩니다.

Firefox63+Safari10+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

:defined 의사 클래스정의된 모든 요소와 일치해야 합니다.

:link

:link

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3.5+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS3.2+Chrome Android?WebView Android1.5+Samsung Internet?Opera Android?
:visited

:visited

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3.5+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

모든 a 요소는 href 속성을 가지며, 모든 area 요소는 href 속성을 가지며, :link:visited 중 하나와 일치해야 합니다.

다른 사양에서는 이러한 요소가 이러한 의사 클래스와 일치하는 방법에 대해 더 구체적인 규칙을 적용할 수 있으며, 이 요구 사항의 직설적인 구현과 관련된 일부 개인정보 보호 문제를 완화합니다.

:active

:active

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera5+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

:active 의사 클래스는 사용자가 활성화된 요소와 일치하도록 정의됩니다.

특정 요소가 활성화되어 있는지 확인하려면, :active 의사 클래스를 정의하는 데, HTML 사용자 에이전트는 다음 목록에서 첫 번째 관련 항목을 사용해야 합니다.

요소가 버튼 요소인 경우
요소가 입력 요소이며 type 속성이 제출 버튼, 이미지 버튼, 리셋 버튼, 또는 버튼 상태인 경우
요소가 a 요소이며 href 속성이 있는 경우
요소가 영역 요소이며 href 속성이 있는 경우
요소가 포커스 가능한 경우

요소가 활성화되어 있는 경우, 형식적인 활성화 상태에 있어야 합니다.

예를 들어, 사용자가 키보드를 사용하여 스페이스바를 눌러 버튼 요소를 누를 때, 이 요소는 keydown 이벤트를 받은 순간부터 keyup 이벤트를 받는 순간 사이에 이 의사 클래스와 일치하게 됩니다.

요소가 활발하게 가리키고 있는 경우

요소가 활성화되어 있는 상태입니다.

요소는 사용자가 활성화 동작을 트리거할 의도를 나타내기 시작하는 시점과 사용자가 활성화 동작을 트리거할 의도를 나타내는 것을 중지하는 시점 사이에 또는 요소의 활성화 동작이 완료되는 시점 중 먼저 오는 시점 사이에 형식적인 활성화 상태에 있다고 합니다.

요소는 사용자가 포인팅 장치를 사용하여 그 포인팅 장치가 "다운" 상태에 있을 때 (예: 마우스의 경우, 마우스 버튼이 눌린 시점과 버튼이 놓인 시점 사이; 멀티터치 환경에서 손가락이 디스플레이 표면에 닿아 있을 때) 활발하게 가리키고 있는 상태라고 합니다.

Selectors 정의에 따르면, :active활성화되어 있는 요소의 평면 트리 조상에도 일치합니다. [SELECTORS]

또한, 현재 :active와 일치하는 레이블 요소의 레이블 제어인 요소는 또한 :active와 일치합니다. (하지만, 활성화되어 있는 것으로 간주되지 않습니다.)

:hover

:hover

모든 최신 엔진에서 지원됨.

Firefox1+Safari2+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

:hover 가상 클래스는 사용자가 포인팅 장치를 사용하여 요소를 지정할 때 요소와 일치하도록 정의됩니다. :hover 가상 클래스를 정의하기 위해, HTML 사용자 에이전트는 사용자가 포인팅 장치를 사용하여 지목하는 요소를 지정된 요소로 간주해야 합니다.

Selectors 정의에 따르면, :hover플랫 트리 조상 요소와도 일치합니다. 이 요소들은 지정됩니다. [SELECTORS]

또한, 현재 :hover와 일치하는 라벨 요소의 레이블 컨트롤인 모든 요소는 또한 :hover와 일치합니다. (하지만, 이는 지정된 것으로 간주되지 않습니다.)

다음과 같은 조각을 특히 고려해보세요:

<p> <label for=c> <input id=a> </label> <span id=b> <input id=c> </span> </p>

사용자가 ID가 "a"인 요소를 포인팅 장치로 지정하면, p 요소 (그리고 위의 스니펫에 표시되지 않은 모든 조상 요소들), 라벨 요소, ID가 "a"인 요소, ID가 "c"인 요소는 :hover 가상 클래스와 일치합니다. ID가 "a"인 요소는 지정된 상태로 일치하고, 라벨p 요소는 플랫 트리 조상에 관한 조건 때문에 일치하며, ID가 "c"인 요소는 위에서 언급한 레이블 컨트롤의 추가 조건 때문에 일치합니다 (즉, 그 라벨 요소가 :hover와 일치함). 그러나 ID가 "b"인 요소는 :hover와 일치하지 않습니다: 그 플랫 트리 자손이 지명되지 않았기 때문입니다, 비록 그 플랫 트리 자손이 :hover와 일치하지만.

:focus

:focus

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera7+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

CSS :focus 의사 클래스의 목적을 위해, 요소가 포커스를 가지고 있는 경우는 다음과 같습니다:

:target

:target

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1.3+Chrome1+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS2+Chrome Android?WebView Android2+Samsung Internet?Opera Android10.1+

CSS :target 의사 클래스의 목적을 위해, document대상 요소들document대상 요소를 포함하는 목록입니다. 대상 요소가 null이 아니면 포함되며, 그렇지 않으면 요소가 포함되지 않습니다. [SELECTORS]

:popover-open

:popover-open

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari미리보기+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

:popover-open 의사 클래스는 다음과 같이 정의됩니다: HTML 요소popover 속성이 비어 있는 popover 상태가 아니고, popover 가시성 상태표시 중인 요소.

:enabled

:enabled

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android2+Samsung Internet?Opera Android10.1+

:enabled 가상 클래스는 다음과 같은 요소와 일치해야 합니다: 버튼입력선택텍스트 영역옵트그룹옵션필드셋 요소 또는 폼 관련 커스텀 요소실제로 비활성화된 요소가 아닙니다.

:disabled

:disabled

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android2+Samsung Internet?Opera Android10.1+

:disabled 가상 클래스실제로 비활성화된 요소와 일치해야 합니다.

:checked

:checked

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS?Chrome Android18+WebView Android2+Samsung Internet?Opera Android10.1+

:checked 가상 클래스는 다음 카테고리 중 하나에 해당하는 요소와 일치해야 합니다:

:indeterminate

:indeterminate

모든 현재 엔진에서 지원됩니다.

Firefox2+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

:indeterminate 가상 클래스 는 다음 카테고리 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:default

:default

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

:default 가상 클래스는 다음 카테고리 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:placeholder-shown

:placeholder-shown 가상 클래스는 다음 카테고리 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:valid

:valid

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

:valid 가상 클래스는 다음 카테고리 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:invalid

:invalid

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

:invalid 가상 클래스는 다음 카테고리 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:user-valid

:user-valid 가상 클래스는 다음 조건을 충족하는 input, textarea, select 요소와 일치해야 합니다: 사용자 유효성이 true이고, 제약 조건 검사의 후보이며, 제약 조건을 충족하는 요소.

:user-invalid

:user-invalid 가상 클래스는 다음 조건을 충족하는 input, textarea, select 요소와 일치해야 합니다: 사용자 유효성이 true이고, 제약 조건 검사의 후보이며, 제약 조건을 충족하지 않는 요소.

:in-range

:in-range

모든 현재 엔진에서 지원됩니다.

Firefox29+Safari5.1+Chrome10+
Opera11+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android16+Safari iOS?Chrome Android?WebView Android2.2+Samsung Internet1.0+Opera Android11+

:in-range 가상 클래스제약 조건 검사의 후보이고, 범위 제한이 있으며, 언더플로우 또는 오버플로우 상태가 아닌 모든 요소와 일치해야 합니다.

:out-of-range

:out-of-range

모든 현재 엔진에서 지원됩니다.

Firefox29+Safari5.1+Chrome10+
Opera11+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android16+Safari iOS?Chrome Android?WebView Android2.2+Samsung Internet1.0+Opera Android11+

:out-of-range 가상 클래스제약 조건 검사의 후보이고, 범위 제한이 있으며, 언더플로우 또는 오버플로우 상태인 모든 요소와 일치해야 합니다.

:required

:required

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android10.1+

:required 가상 클래스는 다음 범주 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:optional

:optional

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

:optional 가상 클래스는 다음 범주 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:autofill

:autofill

Firefox86+Safari15+Chrome🔰 1+
Opera?Edge🔰 79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS15+Chrome Android?WebView Android?Samsung Internet?Opera Android?
:-webkit-autofill

:autofill:-webkit-autofill 가상 클래스input 요소와 일치해야 하며, 이 요소는 사용자 에이전트에 의해 자동으로 채워진 상태입니다. 사용자가 자동 채워진 필드를 편집하면 이 가상 클래스는 더 이상 일치하지 않아야 합니다.

이러한 자동 채우기는 autocomplete 속성을 통해 발생할 수 있지만, 사용자 에이전트는 해당 속성이 관여하지 않아도 자동으로 채울 수 있습니다.

:read-only

:read-only

모든 현재 엔진에서 지원됩니다.

Firefox78+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android🔰 4+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
:read-write

:read-write

모든 현재 엔진에서 지원됩니다.

Firefox78+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android🔰 4+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

:read-write 가상 클래스는 다음 범주 중 하나에 해당하는 모든 요소와 일치해야 합니다. Selectors의 목적을 위해 이 요소들은 사용자 변경 가능으로 간주됩니다: [SELECTORS]

:read-only 가상 클래스는 다른 모든 HTML 요소와 일치해야 합니다.

:modal

:modal 가상 클래스는 다음 범주 중 하나에 해당하는 모든 요소와 일치해야 합니다:

:dir(ltr)

:dir

Firefox49+Safari16.4+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

:dir(ltr) 가상 클래스방향성이 'ltr'인 모든 요소와 일치해야 합니다.

:dir(rtl)

:dir(rtl) 가상 클래스방향성이 'rtl'인 모든 요소와 일치해야 합니다.

사용자 정의 상태 가상 클래스

:state(identifier) 가상 클래스는 사용자 정의 요소상태 집합에서 집합 항목identifier가 포함된 모든 요소와 일치해야 합니다.

:playing

:playing 가상 클래스미디어 요소paused 속성이 false인 모든 요소와 일치해야 합니다.

:paused

:paused 가상 클래스미디어 요소paused 속성이 true인 모든 요소와 일치해야 합니다.

:seeking

:seeking 가상 클래스미디어 요소seeking 속성이 true인 모든 요소와 일치해야 합니다.

:buffering

:buffering 가상 클래스미디어 요소paused 속성이 false이며, networkState 속성이 NETWORK_LOADING이고, 준비 상태가 HAVE_CURRENT_DATA 이하인 모든 요소와 일치해야 합니다.

:stalled

:stalled 가상 클래스미디어 요소:buffering 가상 클래스와 일치하고, 현재 정지 상태가 true인 모든 요소와 일치해야 합니다.

:muted

:muted 가상 클래스미디어 요소음소거된 모든 요소와 일치해야 합니다.

:volume-locked

:volume-locked 가상 클래스는 사용자 에이전트의 볼륨 잠금이 true일 때 모든 미디어 요소와 일치해야 합니다.

이 사양은 :lang() 동적 가상 클래스가 언제 일치하는지 정의하지 않으며, 이는 Selectors에서 언어에 구애받지 않는 방식으로 충분히 상세하게 정의되어 있습니다. [SELECTORS]

5 마이크로데이터

5.1 소개

5.1.1 개요

이 섹션은 비규범적입니다.

때때로 페이지에 맞춤형 서비스를 제공하기 위해 일반적인 스크립트가 필요하거나, 여러 협력 작가의 콘텐츠를 일관되게 처리하기 위해 특정한 기계가 읽을 수 있는 라벨로 콘텐츠를 주석 달고 싶을 때가 있습니다.

이 목적을 위해, 저자는 이 섹션에서 설명된 마이크로데이터 기능을 사용할 수 있습니다. 마이크로데이터는 기존 콘텐츠와 병행하여 문서에 이름-값 쌍의 중첩된 그룹을 추가할 수 있게 합니다.

5.1.2 기본 문법

이 섹션은 비규범적입니다.

상위 수준에서, 마이크로데이터는 이름-값 쌍의 그룹으로 구성됩니다. 이 그룹들은 아이템이라고 불리며, 각 이름-값 쌍은 속성입니다. 아이템과 속성은 일반적인 요소로 표현됩니다.

아이템을 생성하려면 itemscope 속성을 사용합니다.

아이템에 속성을 추가하려면, 해당 아이템의 자손 중 하나에 itemprop 속성을 사용합니다.

다음은 각각 "name" 속성을 가진 두 개의 아이템입니다:

<div itemscope>
 <p>My name is <span itemprop="name">Elizabeth</span>.</p>
</div>

<div itemscope>
 <p>My name is <span itemprop="name">Daniel</span>.</p>
</div>

마이크로데이터 관련 속성이 없는 마크업은 마이크로데이터 모델에 영향을 미치지 않습니다.

이 두 예제는 마이크로데이터 수준에서 이전 두 예제와 각각 완전히 동일합니다:

<div itemscope>
 <p>My <em>name</em> is <span itemprop="name">E<strong>liz</strong>abeth</span>.</p>
</div>

<section>
 <div itemscope>
  <aside>
   <p>My name is <span itemprop="name"><a href="/?user=daniel">Daniel</a></span>.</p>
  </aside>
 </div>
</section>

속성은 일반적으로 문자열 값을 가집니다.

여기 아이템에는 세 가지 속성이 있습니다:

<div itemscope>
 <p>My name is <span itemprop="name">Neil</span>.</p>
 <p>My band is called <span itemprop="band">Four Parts Water</fspan>.</fp>
 <p>I am <span itemprop="nationality">British</fspan>.</p>
</div>

문자열 값이 URL인 경우, 이는 a 요소와 그 요소의 href 속성, img 요소와 그 속성인 src 속성, 또는 외부 리소스를 링크하거나 임베드하는 다른 요소들을 사용하여 표현됩니다.

이 예제에서 아이템은 "image"라는 속성을 가지며, 그 값은 URL입니다:

<div itemscope>
 <img itemprop="image" src="google-logo.png" alt="Google">
</div>

문자열 값이 인간이 소비하기에 부적합한 기계가 읽을 수 있는 형식으로 되어 있는 경우, value 속성을 가진 data 요소를 사용하여 표현하며, 사람에게 읽을 수 있는 버전은 해당 요소의 내용으로 제공합니다.

여기에는 값이 제품 ID인 속성을 가진 아이템이 있습니다. 이 ID는 사람이 이해하기 어렵기 때문에, 제품의 이름이 ID 대신 사람이 볼 수 있는 텍스트로 사용됩니다.

<h1 itemscope>
 <data itemprop="product-id" value="9678AOU879">The Instigator 2000</data>
</h1>

숫자 데이터를 위해서는, meter 요소와 그 속성인 value 속성을 대신 사용할 수 있습니다.

여기에서는 meter 요소를 사용하여 평점이 주어졌습니다.

<div itemscope itemtype="http://schema.org/Product">
 <span itemprop="name">Panasonic White 60L Refrigerator</span>
 <img src="panasonic-fridge-60l-white.jpg" alt="">
  <div itemprop="aggregateRating"
       itemscope itemtype="http://schema.org/AggregateRating">
   <meter itemprop="ratingValue" min=0 value=3.5 max=5>Rated 3.5/5</meter>
   (based on <span itemprop="reviewCount">11</span> customer reviews)
  </div>
</div>

유사하게, 날짜 및 시간 관련 데이터의 경우, time 요소와 그 속성인 datetime 속성을 대신 사용할 수 있습니다.

이 예제에서, 아이템은 "birthday"라는 속성을 가지며, 그 값은 날짜입니다:

<div itemscope>
 I was born on <time itemprop="birthday" datetime="2009-05-10">May 10th 2009</time>.
</div>

속성 자체가 이름-값 쌍의 그룹일 수도 있으며, 이 경우 속성을 선언하는 요소에 itemscope 속성을 추가합니다.

다른 아이템에 속하지 않는 아이템들은 최상위 마이크로데이터 아이템이라고 합니다.

이 예제에서, 외부 아이템은 사람을 나타내고, 내부 아이템은 밴드를 나타냅니다:

<div itemscope>
 <p>Name: <span itemprop="name">Amanda</span></p>
 <p>Band: <span itemprop="band" itemscope> <span itemprop="name">Jazz Band</span> (<span itemprop="size">12</span> players)</span></p>
</div>

여기에서 외부 아이템은 "name"과 "band"라는 두 가지 속성을 가지고 있습니다. "name"은 "Amanda"이며, "band"는 자체적으로 두 가지 속성, "name"과 "size"를 가진 아이템입니다. 밴드의 "name"은 "Jazz Band"이며, "size"는 "12"입니다.

이 예제에서 외부 아이템은 최상위 마이크로데이터 아이템입니다.

itemscope 속성을 가진 요소의 자손이 아닌 속성들은 itemref 속성을 사용하여 아이템과 연결할 수 있습니다. 이 속성은 itemscope 속성을 가진 요소의 자손을 크롤링하는 것 외에도 크롤링할 요소들의 ID 목록을 받습니다.

이 예제는 이전 예제와 동일하지만, 모든 속성이 각자의 아이템과 분리되어 있습니다:

<div itemscope id="amanda" itemref="a b"></div>
<p id="a">Name: <span itemprop="name">Amanda</span></p>
<div id="b" itemprop="band" itemscope itemref="c"></div>
<div id="c">
 <p>Band: <span itemprop="name">Jazz Band</span></p>
 <p>Size: <span itemprop="size">12</span> players</p>
</div>

이 결과는 이전 예제와 동일합니다. 첫 번째 아이템은 "name"과 "band"라는 두 가지 속성을 가지며, "name"은 "Amanda", "band"는 또 다른 아이템으로 설정됩니다. 두 번째 아이템은 "name"이 "Jazz Band", "size"가 "12"인 두 가지 속성을 가집니다.

하나의 아이템은 같은 이름을 가진 여러 속성과 서로 다른 값을 가질 수 있습니다.

이 예제는 두 가지 맛을 가진 아이스크림을 설명합니다:

<div itemscope>
 <p>Flavors in my favorite ice cream:</p>
 <ul>
  <li itemprop="flavor">Lemon sorbet</li>
  <li itemprop="flavor">Apricot sorbet</li>
 </ul>
</div>

이렇게 하면 "flavor"라는 두 가지 속성, "Lemon sorbet"와 "Apricot sorbet"라는 값을 가진 아이템이 생성됩니다.

하나의 요소가 속성을 도입할 때, 일부 속성이 동일한 값을 가질 경우 중복을 피하기 위해 여러 속성을 동시에 도입할 수도 있습니다.

여기에서 우리는 "favorite-color"와 "favorite-fruit"라는 두 가지 속성을 가진 아이템을 볼 수 있으며, 둘 다 "orange"로 설정되어 있습니다:

<div itemscope>
 <span itemprop="favorite-color favorite-fruit">orange</span>
</div>

마이크로데이터와 마이크로데이터가 마크업된 문서의 내용 사이에는 아무런 관계가 없다는 점을 유념하는 것이 중요합니다.

예를 들어, 다음 두 예제 간에는 의미상의 차이가 없습니다:

<figure>
 <img src="castle.jpeg">
 <figcaption><span itemscope><span itemprop="name">The Castle</span></span> (1986)</figcaption>
</figure>
<span itemscope><meta itemprop="name" content="The Castle"></span>
<figure>
 <img src="castle.jpeg">
 <figcaption>The Castle (1986)</figcaption>
</figure>

둘 다 캡션이 있는 figure 요소를 가지고 있으며, 둘 다 figure와는 완전히 관련이 없는 아이템을 가지고 있고, 이름 "name"과 값 "The Castle"을 가진 이름-값 쌍을 포함합니다. 유일한 차이점은 사용자가 캡션을 문서에서 드래그할 경우, 전자의 경우 아이템이 드래그 앤 드롭 데이터에 포함된다는 것입니다. 어느 경우에도 이미지와 아이템 간에는 어떤 연관성도 없습니다.

5.1.3 타입이 지정된 아이템

이 섹션은 비규범적입니다.

이전 섹션의 예제들은 마이크로데이터가 재사용될 것을 예상하지 않는 페이지에서 정보를 어떻게 마크업할 수 있는지를 보여줍니다. 그러나 마이크로데이터는 다른 저자와 독자들이 마크업을 새로운 방식으로 활용할 수 있는 환경에서 가장 유용합니다.

이 목적을 위해서는 각 아이템에 "https://example.com/person", "https://example.org/cat", 또는 "https://band.example.net/"과 같은 타입을 부여해야 합니다. 타입은 URL로 식별됩니다.

아이템의 타입은 itemtype 속성의 값으로, itemscope 속성이 있는 동일한 요소에 지정됩니다.

여기에서 아이템의 타입은 "https://example.org/animals#cat"입니다:

<section itemscope itemtype="https://example.org/animals#cat">
 <h1 itemprop="name">Hedral</h1>
 <p itemprop="desc">Hedral is a male american domestic shorthair, with a fluffy black fur with white paws and belly.</p>
 <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months">
</section>

이 예제에서 "https://example.org/animals#cat" 아이템은 세 가지 속성을 가집니다. "name"("Hedral"), "desc"("Hedral is..."), 그리고 "img"("hedral.jpeg")입니다.

타입은 속성에 대한 문맥을 제공하여 어휘를 선택합니다. 예를 들어 "https://census.example/person" 타입의 아이템에 "class"라는 속성이 주어지면 개인의 경제적 계급을 나타낼 수 있지만, "https://example.com/school/teacher" 타입의 아이템에 "class"라는 속성이 주어지면 교사가 배정된 교실을 나타낼 수 있습니다. 여러 타입이 어휘를 공유할 수 있습니다. 예를 들어, "https://example.org/people/teacher"와 "https://example.org/people/engineer" 타입은 동일한 어휘를 사용하도록 정의될 수 있습니다 (다만 일부 속성은 두 경우 모두에서 특별히 유용하지 않을 수 있으며, 예를 들어 "https://example.org/people/engineer" 타입은 일반적으로 "classroom" 속성과 함께 사용되지 않을 수 있습니다). 동일한 어휘를 사용하는 여러 타입은 속성 값에 공백으로 구분된 URL 목록을 나열하여 단일 아이템에 지정될 수 있습니다. 그러나 동일한 어휘를 사용하지 않는 두 타입을 하나의 아이템에 지정할 수는 없습니다.

5.1.4 아이템의 전역 식별자

이 섹션은 비규범적입니다.

때때로, 아이템이 전역 식별자를 가진 주제에 대한 정보를 제공합니다. 예를 들어, 책은 ISBN 번호로 식별될 수 있습니다.

itemtype 속성으로 식별되는 어휘는 아이템itemid 속성에 주어진 URL을 통해 전역 식별자를 명확하게 연결할 수 있도록 설계될 수 있습니다.

itemid 속성에 주어진 URL의 정확한 의미는 사용된 어휘에 따라 달라집니다.

여기서는 특정 책에 대한 아이템을 설명하고 있습니다:

<dl itemscope
    itemtype="https://vocab.example.net/book"
    itemid="urn:isbn:0-330-34032-8">
 <dt>Title
 <dd itemprop="title">The Reality Dysfunction
 <dt>Author
 <dd itemprop="author">Peter F. Hamilton
 <dt>Publication date
 <dd><time itemprop="pubdate" datetime="1996-01-26">26 January 1996</time>
</dl>

이 예제에서 "https://vocab.example.net/book" 어휘는 itemid 속성이 책의 ISBN을 가리키는 URL을 취하도록 정의됩니다.

5.1.5 어휘를 정의할 때 이름 선택

이 섹션은 비규범적입니다.

마이크로데이터를 사용하려면 어휘를 사용해야 합니다. 일부 목적에서는 임시 어휘로도 충분하지만, 다른 경우에는 어휘를 설계해야 할 필요가 있습니다. 가능하면 저자들은 기존 어휘를 재사용하는 것이 좋으며, 이는 콘텐츠 재사용을 용이하게 만듭니다.

새로운 어휘를 설계할 때 식별자는 URL을 사용하거나, 속성의 경우 점이나 콜론이 없는 일반 단어로 만들 수 있습니다. URL의 경우 저자가 제어할 수 있는 페이지에 해당하는 식별자만 사용하면 다른 어휘와의 충돌을 피할 수 있습니다.

예를 들어, Jon과 Adam이 각각 example.com에서 https://example.com/~jon/...https://example.com/~adam/...에 콘텐츠를 작성한다고 가정할 때, 각각 "https://example.com/~jon/name"과 "https://example.com/~adam/name" 형식의 식별자를 선택할 수 있습니다.

이름이 일반 단어인 속성은 해당 속성이 의도된 타입의 문맥 내에서만 사용할 수 있으며, URL을 사용하여 이름이 지정된 속성은 어떤 타입의 아이템에서도 재사용할 수 있습니다. 아이템에 타입이 없고 다른 아이템의 일부가 아닌 경우, 속성의 이름이 일반 단어라면 이는 전역적으로 고유하지 않으며, 대신 제한된 용도로만 사용될 의도로 만들어진 것입니다. 일반적으로 저자들은 전역적으로 고유한 이름(URL)을 가진 속성을 사용하거나, 그들의 아이템에 타입을 지정하는 것이 좋습니다.

여기서 아이템은 "https://example.org/animals#cat" 타입이며, 대부분의 속성 이름은 해당 타입의 문맥에서 정의된 단어입니다. 또한 다른 어휘에서 가져온 몇 가지 추가 속성도 있습니다.

<section itemscope itemtype="https://example.org/animals#cat">
 <h1 itemprop="name https://example.com/fn">Hedral</h1>
 <p itemprop="desc">Hedral is a male American domestic shorthair, with a fluffy <span
 itemprop="https://example.com/color">black</span> fur with <span
 itemprop="https://example.com/color">white</span> paws and belly.</p>
 <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months">
</section>

이 예제에는 "https://example.org/animals#cat" 타입의 하나의 아이템과 다음 속성들이 있습니다:

속성
name Hedral
https://example.com/fn Hedral
desc Hedral is a male American domestic shorthair, with a fluffy black fur with white paws and belly.
https://example.com/color black
https://example.com/color white
img .../hedral.jpeg

5.2 마이크로데이터 인코딩

5.2.1 마이크로데이터 모델

마이크로데이터 모델은 아이템이라고 알려진 이름-값 쌍의 그룹으로 구성됩니다.

각 그룹은 아이템으로 알려져 있습니다. 각 아이템아이템 타입, 전역 식별자 (만약 아이템 타입에 의해 지정된 어휘가 아이템에 대한 전역 식별자를 지원한다면), 그리고 이름-값 쌍의 목록을 가질 수 있습니다. 이름-값 쌍에서 각 이름은 속성으로 알려져 있으며, 각 속성은 하나 이상의 을 가집니다. 각 은 문자열이거나, 자체적으로 이름-값 쌍의 그룹 (아이템)일 수 있습니다. 이름들은 서로 간에 순서가 없지만, 특정 이름이 여러 값을 가지는 경우에는 그들 사이에 상대적 순서가 존재합니다.

5.2.2 아이템

Global_attributes/itemscope

모든 현재 엔진에서 지원.

FirefoxYes SafariYes ChromeYes
Opera? EdgeYes
Edge (Legacy)12+ Internet ExplorerYes
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

모든 HTML 요소에는 itemscope 속성을 지정할 수 있습니다. itemscope 속성은 불리언 속성입니다.

itemscope 속성이 지정된 요소는 새로운 아이템, 즉 이름-값 쌍의 그룹을 생성합니다.


Global_attributes/itemtype

모든 현재 엔진에서 지원.

FirefoxYes SafariYes ChromeYes
Opera? EdgeYes
Edge (Legacy)12+ Internet ExplorerYes
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

itemscope 속성을 가진 요소에는 itemtype 속성을 지정하여 아이템 타입을 정의할 수 있습니다.

itemtype 속성이 지정된 경우, 그 값은 공백으로 구분된 고유한 토큰의 비순서 집합이어야 하며, 토큰 중 어느 것도 다른 토큰과 일치해서는 안 되며 각 토큰은 유효한 URL 문자열이어야 하며 절대 URL이어야 합니다. 이 속성의 값에는 최소한 하나의 토큰이 있어야 합니다.

아이템아이템 타입요소의 itemtype 속성의 값을 ASCII 공백으로 분리하여 얻은 토큰입니다. itemtype 속성이 없거나 이 방식으로 파싱하여 토큰을 찾지 못한 경우, 해당 아이템아이템 타입이 없다고 합니다.

아이템 타입은 모두 적용 가능한 사양에서 정의된 타입이어야 하며, 동일한 어휘를 사용하도록 정의되어야 합니다.

그 사양에서 달리 명시하지 않는 한, URL로 지정된 아이템 타입은 자동으로 역참조되지 않아야 합니다.

사양에서는 아이템 타입을 역참조하여 예를 들어 사용자에게 도움 정보를 제공할 수 있도록 정의할 수 있습니다. 사실 어휘 저자들은 지정된 URL에서 유용한 정보를 제공하는 것이 권장됩니다.

아이템 타입은 불투명한 식별자이며, 사용자 에이전트는 이를 역참조하거나, 아이템을 처리하는 방법을 결정하기 위해 아이템에 사용된 아이템 타입을 해체해서는 안 됩니다.

itemtype 속성은 itemscope 속성이 지정되지 않은 요소에 지정되어서는 안 됩니다.


아이템아이템 타입을 가지거나, 타입이 지정된 아이템속성인 경우 타입이 지정된 아이템이라고 합니다. 타입이 지정된 아이템관련 타입은 해당 아이템아이템 타입이며, 없을 경우 이는 아이템속성입니다.


Global_attributes/itemid

모든 현재 엔진에서 지원.

FirefoxYes SafariYes ChromeYes
Opera? EdgeYes
Edge (Legacy)12+ Internet ExplorerYes
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

itemscope 속성과, 항목에 대한 전역 식별자를 지원하는 것으로 정의된 어휘를 참조하는 itemtype 속성을 가진 요소는 전역 식별자를 제공하기 위해 itemid 속성을 지정할 수도 있습니다. 이로 인해 웹의 다른 페이지에서 다른 아이템과 연관될 수 있습니다.

itemid 속성이 지정된 경우, 그 값은 유효한 URL(공백으로 둘러싸일 수 있음)이어야 합니다.

아이템전역 식별자는 해당 요소에 지정된 itemid 속성의 값이며, 파싱하여 요소가 지정된 노드 문서와 상대적으로 연결됩니다. itemid 속성이 없거나 파싱에 실패한 경우, 전역 식별자가 없는 것으로 간주됩니다.

itemid 속성은 itemscope 속성과 itemtype 속성이 모두 지정되지 않은 요소에 지정되어서는 안 되며, itemscope 속성을 가진 요소에 지정되어서는 안 됩니다. 또한 해당 어휘의 사양에 따라 항목에 대한 전역 식별자를 지원하지 않는 itemtype 속성이 지정된 요소에도 지정되어서는 안 됩니다.

전역 식별자의 정확한 의미는 어휘의 사양에 의해 결정됩니다. 동일한 전역 식별자를 가진 여러 아이템이 존재할 수 있는지 여부(같은 페이지에서든 다른 페이지에서든)와, 동일한 ID를 가진 여러 아이템을 처리하는 규칙에 대해서는 이러한 사양에 따라 정의됩니다.


Global_attributes/itemref

모든 현재 엔진에서 지원.

FirefoxYes SafariYes ChromeYes
Opera? EdgeYes
Edge (Legacy)12+ Internet ExplorerYes
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

itemscope 속성이 있는 요소에는 itemref 속성을 지정하여 아이템의 이름-값 쌍을 찾기 위해 추가로 크롤링할 요소 목록을 지정할 수 있습니다.

itemref 속성이 지정된 경우, 그 값은 공백으로 구분된 고유한 토큰의 비순서 집합이어야 하며, 토큰 중 어느 것도 다른 토큰과 일치해서는 안 되며, 동일한 ID를 가지는 동일한 트리 내의 요소들로 구성되어야 합니다.

itemref 속성은 itemscope 속성이 지정되지 않은 요소에 지정되어서는 안 됩니다.

itemref 속성은 마이크로데이터 데이터 모델의 일부가 아닙니다. 이는 단순히 트리 구조를 따르지 않는 데이터를 주석 처리할 수 있도록 저자에게 도움을 주기 위한 구문적 구성 요소입니다. 예를 들어, 각 열이 별도의 아이템을 정의하면서 속성을 셀에 유지하도록 데이터를 표에 마크업할 수 있게 합니다.

이 예제는 모델 철도 제조업체의 제품을 설명하는 데 사용되는 간단한 어휘를 보여줍니다. 이 어휘에는 다섯 가지 속성 이름만 있습니다:

product-code
제조업체의 카탈로그에서 제품을 나타내는 정수입니다.
name
제품에 대한 간단한 설명입니다.
scale
제품의 크기를 나타내는 "HO", "1", 또는 "Z" (앞 또는 뒤에 공백이 있을 수 있음) 중 하나입니다.
digital
제품에 디지털 디코더가 있는 경우, "Digital", "Delta", 또는 "Systems" (앞 또는 뒤에 공백이 있을 수 있음) 중 하나를 나타냅니다.
track-type
선로 전용 제품의 경우, 해당 제품이 의도된 트랙의 유형을 나타내는 "K", "M", "C" (앞 또는 뒤에 공백이 있을 수 있음) 중 하나입니다.

이 어휘에는 네 가지 아이템 타입이 정의되어 있습니다:

https://md.example.com/loco
엔진이 있는 차량
https://md.example.com/passengers
승객 차량
https://md.example.com/track
트랙 조각
https://md.example.com/lighting
조명이 있는 장비

이 어휘를 사용하는 각 아이템은 제품이 무엇인지에 따라 이 타입들 중 하나 이상을 가질 수 있습니다.

따라서, 기관차는 다음과 같이 마크업될 수 있습니다:

<dl itemscope itemtype="https://md.example.com/loco
                        https://md.example.com/lighting">
 <dt>Name:
 <dd itemprop="name">Tank Locomotive (DB 80)
 <dt>Product code:
 <dd itemprop="product-code">33041
 <dt>Scale:
 <dd itemprop="scale">HO
 <dt>Digital:
 <dd itemprop="digital">Delta
</dl>

전환 랜턴 레트로핏 키트는 다음과 같이 마크업될 수 있습니다:

<dl itemscope itemtype="https://md.example.com/track
                        https://md.example.com/lighting">
 <dt>Name:
 <dd itemprop="name">Turnout Lantern Kit
 <dt>Product code:
 <dd itemprop="product-code">74470
 <dt>Purpose:
 <dd>For retrofitting 2 <span itemprop="track-type">C</span> Track turnouts. <meta itemprop="scale" content="HO">
</dl>

조명이 없는 객차는 다음과 같이 마크업될 수 있습니다:

<dl itemscope itemtype="https://md.example.com/passengers">
 <dt>Name:
 <dd itemprop="name">Express Train Passenger Car (DB Am 203)
 <dt>Product code:
 <dd itemprop="product-code">8710
 <dt>Scale:
 <dd itemprop="scale">Z
</dl>

새로운 어휘를 만들 때는 매우 신중해야 합니다. 종종 각 항목이 단일 유형만을 갖는 어휘를 결과로 하는 계층적 접근 방식을 사용할 수 있으며, 이는 일반적으로 관리하기 훨씬 간단합니다.

5.2.3 이름: itemprop 속성

Global_attributes/itemprop

모든 최신 엔진에서 지원됩니다.

FirefoxSafariChrome
Opera?Edge
Edge (구 버전)12+Internet Explorer
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

모든 HTML 요소itemprop 속성을 가질 수 있으며, 이 속성을 지정하면 하나 이상의 속성을 하나 이상의 아이템에 추가합니다(아래 정의된 대로).

itemprop 속성을 지정하면, 값은 고유한 공백으로 구분된 토큰의 비정렬 집합이어야 하며, 각 토큰은 서로 동일하지 않아야 하며, 이 토큰들은 추가하는 이름-값 쌍의 이름을 나타냅니다. 속성 값에는 적어도 하나의 토큰이 있어야 합니다.

각 토큰은 다음 중 하나여야 합니다:

정의된 속성 이름을 도입하는 명세서는 이러한 모든 속성 이름에 U+002E FULL STOP 문자(.)나 U+003A COLON 문자(:), 그리고 ASCII 공백 문자가 포함되지 않도록 보장해야 합니다.

위의 규칙은 URL이 아닌 값에서 U+003A COLON 문자(:)를 허용하지 않으며, 그렇지 않으면 URL과 구분할 수 없기 때문입니다. U+002E FULL STOP 문자(.)가 포함된 값은 미래 확장을 위해 예약되어 있습니다. ASCII 공백 문자는 값이 여러 토큰으로 파싱될 수 있기 때문에 허용되지 않습니다.

요소에 itemprop 속성이 지정되고, 이 속성이 여러 아이템속성을 추가하면, 위에서 언급한 토큰에 관한 요구 사항은 각 아이템별로 개별적으로 적용됩니다.

요소의 속성 이름은 요소의 itemprop 속성이 포함된 것으로 확인된 토큰들이며, 값이 ASCII 공백으로 분리될 때 순서가 유지되지만 중복이 제거됩니다(각 이름의 첫 번째 발생만 남김).

하나의 아이템 내에서, 속성들은 서로 간에 순서가 지정되지 않으며, 같은 이름의 속성들만 해당 속성들이 아이템의 속성을 정의하는 알고리즘에 의해 주어진 순서대로 정렬됩니다.

다음 예제에서, "a" 속성은 "1"과 "2" 값을 가지며, 그 순서대로입니다. 그러나 "a" 속성이 "b" 속성보다 먼저 오는지 여부는 중요하지 않습니다:

<div itemscope>
 <p itemprop="a">1</p>
 <p itemprop="a">2</p>
 <p itemprop="b">test</p>
</div>

따라서 다음은 동등합니다:

<div itemscope>
 <p itemprop="b">test</p>
 <p itemprop="a">1</p>
 <p itemprop="a">2</p>
</div>

다음과 같이:

<div itemscope>
 <p itemprop="a">1</p>
 <p itemprop="b">test</p>
 <p itemprop="a">2</p>
</div>

그리고 다음과 같이:

<div id="x">
 <p itemprop="a">1</p>
</div>
<div itemscope itemref="x">
 <p itemprop="b">test</p>
 <p itemprop="a">2</p>
</div>

5.2.4

itemprop 속성이 있는 요소가 추가한 이름-값 쌍의 속성 값은 다음 목록에서 일치하는 첫 번째 경우에 따라 결정됩니다:

해당 요소에 itemscope 속성이 있는 경우

값은 해당 요소가 생성한 아이템입니다.

해당 요소가 meta 요소인 경우

값은 요소의 content 속성의 값입니다. 해당 속성이 없는 경우 빈 문자열이 됩니다.

해당 요소가 audio, embed, iframe, img, source, track, 또는 video 요소인 경우

값은 요소의 src 속성 값을 기준으로, 요소의 노드 문서에 상대적으로 URL을 인코딩, 파싱 및 직렬화한 결과입니다. 해당 속성이 없거나 결과가 실패인 경우 빈 문자열이 됩니다.

해당 요소가 a, area, 또는 link 요소인 경우

값은 요소의 href 속성 값을 기준으로, 요소의 노드 문서에 상대적으로 URL을 인코딩, 파싱 및 직렬화한 결과입니다. 해당 속성이 없거나 결과가 실패인 경우 빈 문자열이 됩니다.

해당 요소가 object 요소인 경우

값은 요소의 data 속성 값을 기준으로, 요소의 노드 문서에 상대적으로 URL을 인코딩, 파싱 및 직렬화한 결과입니다. 해당 속성이 없거나 결과가 실패인 경우 빈 문자열이 됩니다.

해당 요소가 data 요소인 경우

값은 요소의 value 속성의 값입니다. 해당 속성이 없는 경우 빈 문자열이 됩니다.

해당 요소가 meter 요소인 경우

값은 요소의 value 속성의 값입니다. 해당 속성이 없는 경우 빈 문자열이 됩니다.

해당 요소가 time 요소인 경우

값은 요소의 datetime 값입니다.

그 외의 경우

값은 요소의 하위 텍스트 콘텐츠입니다.

URL 속성 요소a, area, audio, embed, iframe, img, link, object, source, track, 그리고 video 요소입니다.

속성의 이 해당 속성의 정의에 따라 절대 URL인 경우, 해당 속성은 URL 속성 요소를 사용하여 지정해야 합니다.

이 요구 사항은 속성 값이 우연히 URL 구문과 일치한다고 해서 적용되는 것은 아닙니다. 이 요구 사항은 속성이 명시적으로 그러한 값을 취하도록 정의된 경우에만 적용됩니다.

예를 들어, 최초의 달 착륙에 관한 책이 "mission:moon"이라는 제목을 가질 수 있습니다. 제목을 문자열로 정의하는 어휘에서 "title" 속성은 URL처럼 보이더라도 a 요소로 제목을 지정하지 않아야 합니다. 반면, "URL처럼 보이는 제목을 가진 책"이라는 (매우 좁은 범위의!) 어휘가 있으며, 이 어휘의 "title" 속성은 URL을 취하도록 정의된 경우에는, 위의 요구 사항 때문에 제목을 a 요소(또는 다른 URL 속성 요소 중 하나)로 지정해야 합니다.

5.2.5 항목과 이름 연결하기

요소 root에 의해 정의된 항목의 속성을 찾기 위해, 사용자 에이전트는 다음 단계를 실행해야 합니다. 이러한 단계는 또한 마이크로데이터 오류를 플래그 지정하는 데 사용됩니다.

  1. results, memory, pending이라는 비어 있는 요소 목록을 만듭니다.

  2. root 요소를 memory에 추가합니다.

  3. root의 자식 요소가 있다면 pending에 추가합니다.

  4. rootitemref 속성이 있는 경우, 그 itemref 속성의 값을 ASCII 공백으로 나눕니다. 그렇게 해서 나온 각 토큰 ID에 대해, root트리에 해당 ID를 가진 요소가 있다면, 그 중 첫 번째 요소를 pending에 추가합니다.

  5. pending이 비어 있지 않은 동안:

    1. pending에서 요소를 제거하고 그 요소를 current라고 합니다.

    2. 만약 current가 이미 memory에 있다면, 이는 마이크로데이터 오류가 발생한 것이므로 계속 진행합니다.

    3. currentmemory에 추가합니다.

    4. 만약 currentitemscope 속성이 없다면, current의 모든 자식 요소를 pending에 추가합니다.

    5. currentitemprop 속성이 지정되어 있고 하나 이상의 속성 이름이 있는 경우, currentresults에 추가합니다.

  6. results트리 순서로 정렬합니다.

  7. results를 반환합니다.

문서에는 항목의 속성을 찾는 알고리즘에서 마이크로데이터 오류를 찾는 항목이 포함되지 않아야 합니다.

요소에 itemprop 속성이 지정되어 있지 않다면, 그 항목최상위 마이크로데이터 항목이라고 합니다.

모든 itemref 속성은 문서 내의 항목이 노드로 표현되고, 항목의 속성이 다른 항목으로 연결된 그래프에서 순환이 없도록 해야 합니다.

문서에는 속성이 결정될 경우, 해당 문서에 포함된 항목의 속성으로 발견되지 않을 itemprop 속성을 가진 요소가 포함되어 있어서는 안 됩니다.

다음 예에서는 단일 라이선스 선언이 itemref를 사용하여 두 개의 작품에 적용됩니다:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Photo gallery</title>
 </head>
 <body>
  <h1>My photos</h1>
  <figure itemscope itemtype="http://n.whatwg.org/work" itemref="licenses">
   <img itemprop="work" src="images/house.jpeg" alt="A white house, boarded up, sits in a forest.">
   <figcaption itemprop="title">The house I found.</figcaption>
  </figure>
  <figure itemscope itemtype="http://n.whatwg.org/work" itemref="licenses">
   <img itemprop="work" src="images/mailbox.jpeg" alt="Outside the house is a mailbox. It has a leaflet inside.">
   <figcaption itemprop="title">The mailbox.</figcaption>
  </figure>
  <footer>
   <p id="licenses">All images licensed under the <a itemprop="license"
   href="http://www.opensource.org/licenses/mit-license.php">MIT
   license</a>.</p>
  </footer>
 </body>
</html>

위의 코드는 "http://n.whatwg.org/work" 타입을 가진 두 개의 항목을 생성하며, 하나는 다음과 같습니다:

work
images/house.jpeg
title
The house I found.
license
http://www.opensource.org/licenses/mit-license.php

...그리고 다른 하나는 다음과 같습니다:

work
images/mailbox.jpeg
title
The mailbox.
license
http://www.opensource.org/licenses/mit-license.php

5.2.6 마이크로데이터와 기타 네임스페이스

현재, itemscope, itemprop 및 기타 마이크로데이터 속성은 HTML 요소에만 정의되어 있습니다. 이는 "itemscope", "itemprop" 등의 문자 그대로의 이름을 가진 속성이 SVG와 같은 다른 네임스페이스의 요소에서 마이크로데이터 처리를 발생시키지 않는다는 것을 의미합니다.

따라서 아래 예제에서 항목은 두 개가 아니라 하나만 존재합니다.

<p itemscope></p> <!-- 이 요소는 항목입니다 (속성과 유형이 없음) -->
<svg itemscope></svg> <!-- 이 요소는 항목이 아닙니다. 그저 알 수 없는 속성이 있는 SVG SVG svg 요소일 뿐입니다. -->

5.3 샘플 마이크로데이터 어휘

이 섹션의 어휘는 어휘가 어떻게 지정되는지를 보여주기 위한 주된 목적으로 사용되지만, 자체적으로도 사용 가능합니다.

5.3.1 vCard

아이템 유형 http://microformats.org/profile/hcard을 가진 아이템은 사람이나 조직의 연락처 정보를 나타냅니다.

이 어휘는 아이템에 대한 글로벌 식별자 지원을 지원하지 않습니다.

다음은 이 유형의 정의된 속성 이름입니다. 이는 vCard Format Specification(vCard) 및 그 확장에서 정의된 어휘를 기반으로 하며, 값의 해석에 대한 자세한 정보는 해당 문서에서 찾을 수 있습니다. [RFC6350]

kind

아이템이 나타내는 연락처의 종류를 설명합니다.

다음과 동일한 kind strings 중 하나여야 합니다.

kind라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

fn

사람이나 조직의 이름에 해당하는 형식화된 텍스트를 제공합니다.

은 텍스트여야 합니다.

fn이라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재해야 합니다.

n

사람이나 조직의 구조화된 이름을 제공합니다.

아이템이어야 하며, family-name, given-name, additional-name, honorific-prefix, honorific-suffix 속성을 각각 0개 이상 포함할 수 있습니다.

n이라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재해야 합니다.

family-name (inside n)

사람의 성 또는 조직의 전체 이름을 제공합니다.

은 텍스트여야 합니다.

family-name라는 이름을 가진 속성은 아이템 내에서 n 속성의 일부로 존재할 수 있습니다.

given-name (inside n)

사람의 이름을 제공합니다.

은 텍스트여야 합니다.

given-name라는 이름을 가진 속성은 아이템 내에서 n 속성의 일부로 존재할 수 있습니다.

additional-name (inside n)

사람의 추가 이름을 제공합니다.

은 텍스트여야 합니다.

additional-name라는 이름을 가진 속성은 아이템 내에서 n 속성의 일부로 존재할 수 있습니다.

honorific-prefix (inside n)

사람의 경칭을 제공합니다.

은 텍스트여야 합니다.

honorific-prefix라는 이름을 가진 속성은 아이템 내에서 n 속성의 일부로 존재할 수 있습니다.

honorific-suffix (inside n)

사람의 존칭을 제공합니다.

은 텍스트여야 합니다.

honorific-suffix라는 이름을 가진 속성은 아이템 내에서 n 속성의 일부로 존재할 수 있습니다.

nickname

사람이나 조직의 별명을 제공합니다.

별명은 사람, 장소, 또는 사물에 속하는 이름 대신에, 또는 그에 추가하여 주어진 설명적인 이름입니다. fn 또는 n 속성으로 지정된 고유 이름의 친숙한 형태를 지정하는 데에도 사용할 수 있습니다.

은 텍스트여야 합니다.

nickname라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

photo

사람이나 조직의 사진을 제공합니다.

절대 URL이어야 합니다.

photo라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

bday

사람이나 조직의 생년월일을 제공합니다.

유효한 날짜 문자열이어야 합니다.

bday라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

anniversary

사람이나 조직의 기념일을 제공합니다.

유효한 날짜 문자열이어야 합니다.

anniversary라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

sex

사람의 생물학적 성별을 제공합니다.

F, "여성"을 의미, M, "남성"을 의미, N, "없음 또는 해당 없음"을 의미, O, "기타"를 의미, U, "알 수 없음"을 의미하는 값 중 하나여야 합니다.

sex라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

gender-identity

사람의 성 정체성을 제공합니다.

은 텍스트여야 합니다.

gender-identity라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

adr

사람이나 조직의 배송 주소를 제공합니다.

아이템이어야 하며, type, post-office-box, extended-address, street-address 속성을 0개 이상 포함할 수 있으며, 선택적으로 locality, region, postal-code, country-name 속성을 선택적으로 포함할 수 있습니다.

만약 type 속성이 아이템 내에 존재하지 않는다면 work가 암시됩니다.

adr라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

type (inside adr)

배송 주소의 유형을 제공합니다.

다음과 동일한 주소 유형 문자열 중 하나여야 합니다.

type라는 이름을 가진 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

post-office-box (inside adr)

사람이나 조직의 배송 주소의 우편함 구성 요소를 제공합니다.

은 텍스트여야 합니다.

post-office-box라는 이름을 가진 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

vCard는 이 필드의 사용을 자제할 것을 권고합니다.

extended-address (inside adr)

사람이나 조직의 배송 주소의 추가 구성 요소를 제공합니다.

은 텍스트여야 합니다.

extended-address라는 이름을 가진 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

vCard는 이 필드의 사용을 자제할 것을 권고합니다.

street-address (inside adr)

사람이나 조직의 배송 주소의 거리 주소 구성 요소를 제공합니다.

은 텍스트여야 합니다.

street-address라는 이름을 가진 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

locality (inside adr)

사람이나 조직의 배송 주소의 지역 구성 요소(예: 도시)를 제공합니다.

은 텍스트여야 합니다.

locality라는 이름을 가진 단일 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

region (inside adr)

사람이나 조직의 배송 주소의 지역 구성 요소(예: 주 또는 도)를 제공합니다.

은 텍스트여야 합니다.

region라는 이름을 가진 단일 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

postal-code (inside adr)

사람이나 조직의 배송 주소의 우편번호 구성 요소를 제공합니다.

은 텍스트여야 합니다.

postal-code라는 이름을 가진 단일 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

country-name (inside adr)

사람이나 조직의 배송 주소의 국가 이름 구성 요소를 제공합니다.

은 텍스트여야 합니다.

country-name라는 이름을 가진 단일 속성은 아이템 내에서 adr 속성의 일부로 존재할 수 있습니다.

tel

사람이나 조직의 전화번호를 제공합니다.

은 텍스트로, CCITT 명세 E.163 및 X.121에서 정의한 전화번호로 해석될 수 있어야 하며, 또는 아이템이어야 하며, 0개 이상의 type 속성과 정확히 하나의 value 속성을 가져야 합니다. [E163] [X121]

만약 type 속성이 아이템 내에 존재하지 않는다면, 또는 tel 속성의 이 텍스트일 경우, voice 전화 유형 문자열이 암시됩니다.

tel라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

type (inside tel)

전화번호의 유형을 제공합니다.

다음과 동일한 전화 유형 문자열 중 하나여야 합니다.

type라는 이름을 가진 속성은 아이템 내에서 tel 속성의 일부로 존재할 수 있습니다.

value (inside tel)

사람이나 조직의 실제 전화번호를 제공합니다.

은 CCITT 명세 E.163 및 X.121에서 정의된 전화번호로 해석될 수 있는 텍스트여야 합니다. [E163] [X121]

value라는 이름을 가진 단일 속성은 아이템 내에서 tel 속성의 일부로 존재해야 합니다.

email

사람이나 조직의 이메일 주소를 제공합니다.

은 텍스트여야 합니다.

email라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

impp

사람이나 조직과의 인스턴트 메시징 및 상태 프로토콜 통신을 위한 URL을 제공합니다.

절대 URL이어야 합니다.

impp라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

lang

사람이나 조직이 이해하는 언어를 제공합니다.

은 유효한 BCP 47 언어 태그여야 합니다. [BCP47]

lang라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

tz

사람이나 조직의 시간대를 제공합니다.

은 텍스트여야 하며 다음 구문과 일치해야 합니다:

  1. U+002B PLUS SIGN 문자(+) 또는 U+002D HYPHEN-MINUS 문자(-) 중 하나.
  2. 유효한 0 이상의 정수로, 정확히 두 자리 숫자여야 하며, 00..23 범위의 숫자를 나타냅니다.
  3. U+003A COLON 문자(:).
  4. 유효한 0 이상의 정수로, 정확히 두 자리 숫자여야 하며, 00..59 범위의 숫자를 나타냅니다.

tz라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

geo

사람이나 조직의 지리적 위치를 제공합니다.

은 텍스트여야 하며 다음 구문과 일치해야 합니다:

  1. 옵션으로, U+002B PLUS SIGN 문자(+) 또는 U+002D HYPHEN-MINUS 문자(-) 중 하나.
  2. 하나 이상의 ASCII 숫자.
  3. 옵션으로*, U+002E FULL STOP 문자(.) 뒤에 하나 이상의 ASCII 숫자.
  4. U+003B SEMICOLON 문자(;).
  5. 옵션으로, U+002B PLUS SIGN 문자(+) 또는 U+002D HYPHEN-MINUS 문자(-) 중 하나.
  6. 하나 이상의 ASCII 숫자.
  7. 옵션으로*, U+002E FULL STOP 문자(.) 뒤에 하나 이상의 ASCII 숫자.

별표(*)가 있는 선택적 구성 요소는 포함되어야 하며, 각각 6자리 숫자를 가져야 합니다.

값은 위도와 경도를 순서대로 나타내며, 10진수로 표현된 도 단위입니다. 경도는 본초 자오선의 동쪽과 서쪽 위치를 각각 양수 또는 음수의 실수로 나타냅니다. 위도는 적도의 북쪽과 남쪽 위치를 각각 양수 또는 음수의 실수로 나타냅니다.

geo라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

title

사람이나 조직의 직위, 기능적 위치 또는 역할을 제공합니다.

은 텍스트여야 합니다.

title라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

role

사람이나 조직의 역할, 직업 또는 사업 카테고리를 제공합니다.

은 텍스트여야 합니다.

role라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

사람이나 조직의 로고를 제공합니다.

절대 URL이어야 합니다.

라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

agent

사람이나 조직을 대신하여 행동할 다른 사람의 연락처 정보를 제공합니다.

아이템이거나 절대 URL, 또는 텍스트여야 합니다.

agent라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

org

조직의 이름 및 단위를 제공합니다.

은 텍스트이거나, 아이템으로서 organization-name 속성을 하나 가지고, 0개 이상의 organization-unit 속성을 가질 수 있습니다.

org라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

organization-name (inside org)

조직의 이름을 제공합니다.

은 텍스트여야 합니다.

organization-name라는 이름을 가진 단일 속성은 아이템 내에서 org 속성의 일부로 존재해야 합니다.

organization-unit (inside org)

조직 단위의 이름을 제공합니다.

은 텍스트여야 합니다.

organization-unit라는 이름을 가진 속성은 아이템 내에서 org 속성의 일부로 존재할 수 있습니다.

member

URL을 제공하며, 그룹의 구성원을 나타냅니다.

절대 URL이어야 합니다.

member라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다. 해당 아이템이 또한 kind이라는 이름을 가진 속성과 함께, "group" 값으로 존재할 경우에 한합니다.

related

다른 엔터티와의 관계를 제공합니다.

아이템이어야 하며, 하나의 url 속성과 하나의 rel 속성을 가져야 합니다.

related라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

url (inside related)

관련 엔터티의 URL을 제공합니다.

절대 URL이어야 합니다.

url라는 이름을 가진 단일 속성은 아이템 내에서 related 속성의 일부로 존재해야 합니다.

rel (inside related)

엔터티와 관련 엔터티 사이의 관계를 제공합니다.

다음과 동일한 관계 문자열 중 하나여야 합니다.

rel라는 이름을 가진 단일 속성은 아이템 내에서 related 속성의 일부로 존재해야 합니다.

categories

사람이나 조직을 분류할 수 있는 카테고리 또는 태그의 이름을 제공합니다.

은 텍스트여야 합니다.

categories라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

note

사람이나 조직에 대한 추가 정보 또는 코멘트를 제공합니다.

은 텍스트여야 합니다.

note라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

rev

연락처 정보의 수정 날짜와 시간을 제공합니다.

유효한 글로벌 날짜 및 시간 문자열이어야 합니다.

값은 다른 버전의 정보에 대한 현재 정보 수정을 구분합니다.

rev라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

sound

사람이나 조직과 관련된 사운드 파일을 제공합니다.

절대 URL이어야 합니다.

sound라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

uid

사람이나 조직에 해당하는 전역 고유 식별자를 제공합니다.

은 텍스트여야 합니다.

uid라는 이름을 가진 단일 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

url

사람이나 조직과 관련된 URL을 제공합니다.

절대 URL이어야 합니다.

url라는 이름을 가진 속성은 아이템의 유형 http://microformats.org/profile/hcard 내에 존재할 수 있습니다.

유형 문자열은 다음과 같습니다:

individual

단일 엔터티를 나타냅니다 (예: 사람).

group

다수의 엔터티를 나타냅니다 (예: 메일링 리스트).

org

사람이 아닌 단일 엔터티를 나타냅니다 (예: 회사).

location

지리적 장소를 나타냅니다 (예: 사무실 건물).

주소 유형 문자열은 다음과 같습니다:

home

거주지의 배송 주소를 나타냅니다.

work

작업장의 배송 주소를 나타냅니다.

전화 유형 문자열은 다음과 같습니다:

home

거주지 전화번호를 나타냅니다.

work

작업장의 전화번호를 나타냅니다.

text

문자 메시지(SMS)를 지원하는 전화번호를 나타냅니다.

voice

음성 전화번호를 나타냅니다.

fax

팩스 전화번호를 나타냅니다.

cell

휴대전화 번호를 나타냅니다.

video

화상 회의 전화번호를 나타냅니다.

pager

호출기 전화번호를 나타냅니다.

textphone

청각 또는 언어 장애인을 위한 통신 장치를 나타냅니다.

관계 문자열은 다음과 같습니다:

emergency

긴급 연락처.

agent

이 엔터티를 대신하여 행동하는 다른 엔터티.

contact
acquaintance
friend
met
worker
colleague
resident
neighbor
child
parent
sibling
spouse
kin
muse
crush
date
sweetheart
me

XFN에서 정의된 의미를 갖습니다. [XFN]

5.3.1.1 vCard로의 변환

사용자 에이전트는 document 내의 노드 목록 nodes가 주어졌을 때, 다음 알고리즘을 실행하여 해당 노드들에 의해 표현된 vCard 데이터를 추출해야 합니다(첫 번째 vCard만 반환됩니다):

  1. 만약 nodes에 있는 노드들 중 아이템으로서 아이템 타입http://microformats.org/profile/hcard인 노드가 없다면, vCard가 없습니다. 알고리즘을 중단하고 아무것도 반환하지 않습니다.

  2. nodenodes에서 아이템으로서 아이템 타입http://microformats.org/profile/hcard인 첫 번째 노드로 설정합니다.

  3. output을 빈 문자열로 설정합니다.

  4. vCard 라인 추가 작업을 수행하여 output에 "BEGIN" 타입과 "VCARD" 값을 추가합니다.

  5. vCard 라인 추가 작업을 수행하여 output에 "PROFILE" 타입과 "VCARD" 값을 추가합니다.

  6. vCard 라인 추가 작업을 수행하여 output에 "VERSION" 타입과 "4.0" 값을 추가합니다.

  7. vCard 라인 추가 작업을 수행하여 output에 "SOURCE" 타입과 vCard 텍스트 문자열 이스케이프를 통해 얻어진 문서의 URL 값을 추가합니다.

  8. title 요소가 null이 아니라면, vCard 라인 추가 작업을 수행하여 output에 "NAME" 타입과 vCard 텍스트 문자열 이스케이프를 통해 title 요소후손 텍스트 콘텐츠로부터 얻어진 값을 추가합니다.

  9. sex를 빈 문자열로 설정합니다.

  10. gender-identity를 빈 문자열로 설정합니다.

  11. 아이템 node속성인 각 element에 대해, element속성 이름들에 있는 각 name에 대해 다음의 하위 단계를 실행합니다:

    1. parameters를 이름-값 쌍의 빈 집합으로 설정합니다.

    2. 다음 목록에서 적절한 하위 단계 집합을 실행합니다. 단계들은 다음 단계에서 사용될 value 변수를 설정합니다.

      속성의 아이템 subitem이고 namen인 경우
      1. value를 빈 문자열로 설정합니다.

      2. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 family-name 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      3. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      4. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 given-name 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      5. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      6. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 additional-name 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      7. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      8. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 honorific-prefix 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      9. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      10. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 honorific-suffix 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      속성의 아이템 subitem이고 nameadr인 경우
      1. value를 빈 문자열로 설정합니다.

      2. vCard 서브속성 수집 작업을 통해 subitem에서 post-office-box 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      3. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      4. vCard 서브속성 수집 작업을 통해 subitem에서 extended-address 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      5. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      6. vCard 서브속성 수집 작업을 통해 subitem에서 street-address 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      7. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      8. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 locality 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      9. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      10. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 region 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      11. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      12. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 postal-code 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      13. value에 U+003B 세미콜론 문자(;)를 추가합니다.
      14. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 country-name 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      15. subitemtype이라는 이름의 속성이 있고, 그 첫 번째 속성의 아이템이 아니며 값이 ASCII 알파뉴메릭으로만 구성된 경우, 해당 속성의 parameters에 "TYPE"이라는 이름으로 추가합니다.

      속성의 아이템 subitem이고 nameorg인 경우
      1. value를 빈 문자열로 설정합니다.

      2. 첫 번째 vCard 서브속성 수집 작업을 통해 subitem에서 organization-name 이름의 서브속성을 수집한 결과를 value에 추가합니다.

      3. subitemorganization-unit이라는 이름의 속성이 있다면, 다음 단계를 실행합니다:

        1. 속성의 아이템인 경우, 이 속성을 건너뜁니다.

        2. value에 U+003B 세미콜론 문자(;)를 추가합니다.
        3. 해당 속성의 vCard 텍스트 문자열 이스케이프를 통해 처리한 결과를 value에 추가합니다.

      속성의 아이템 subitem이며 아이템 타입http://microformats.org/profile/hcard이고 namerelated인 경우
      1. value를 빈 문자열로 설정합니다.

      2. subitemurl이라는 이름의 속성이 있으며, 그 요소가 URL 속성 요소인 경우, value에 첫 번째 속성의 vCard 텍스트 문자열 이스케이프를 통해 추가하고, "VALUE"라는 이름과 "URI"라는 값을 가진 매개변수를 parameters에 추가합니다.

      3. subitemrel이라는 이름의 속성이 있으며, 그 첫 번째 속성의 아이템이 아니며 값이 ASCII 알파뉴메릭으로만 구성된 경우, 해당 속성의 parameters에 "RELATION"이라는 이름으로 추가합니다.

      속성의 아이템이며, name이 위에 나열된 경우가 아닌 경우
      1. valuesubitem에서 value라는 이름의 첫 번째 vCard 서브속성 수집 작업을 통해 얻은 결과로 설정합니다.

      2. subitemtype이라는 이름의 속성이 있고, 그 첫 번째 속성의 아이템이 아니며 값이 ASCII 알파뉴메릭으로만 구성된 경우, 해당 속성의 parameters에 "TYPE"이라는 이름으로 추가합니다.

      속성의 아이템이 아니며, namesex인 경우

      이 속성이 처음 발견된 경우, sex를 해당 속성의 으로 설정합니다.

      속성의 아이템이 아니며, namegender-identity인 경우

      이 속성이 처음 발견된 경우, gender-identity를 해당 속성의 으로 설정합니다.

      그 외의 경우 (속성의 아이템이 아닌 경우)
      1. value를 속성의 으로 설정합니다.

      2. elementURL 속성 요소 중 하나인 경우, "VALUE"라는 이름과 "URI"라는 값을 가진 매개변수를 parameters에 추가합니다.

      3. 그 외의 경우, namebday 또는 anniversary인 경우, 그리고 value유효한 날짜 문자열인 경우, "VALUE"라는 이름과 "DATE"라는 값을 가진 매개변수를 parameters에 추가합니다.

      4. 그 외의 경우, namerev이고, value유효한 전역 날짜 및 시간 문자열인 경우, "VALUE"라는 이름과 "DATE-TIME"라는 값을 가진 매개변수를 parameters에 추가합니다.

      5. value 내의 모든 U+005C 역슬래시(\) 문자를 동일한 문자로 하나 더 추가합니다.

      6. value 내의 모든 U+002C 콤마(,) 문자를 U+005C 역슬래시(\) 문자로 앞에 추가합니다.

      7. namegeo가 아닌 경우, value 내의 모든 U+003B 세미콜론 문자(;)를 U+005C 역슬래시(\) 문자로 앞에 추가합니다.

      8. value 내의 모든 U+000D 캐리지 리턴 U+000A 라인 피드 문자 쌍(CRLF)을 U+005C 역슬래시(\) 문자와 그 뒤에 U+006E 라틴 소문자 n(n) 문자로 대체합니다.

      9. value 내의 남아 있는 모든 U+000D 캐리지 리턴(CR) 또는 U+000A 라인 피드(LF) 문자를 U+005C 역슬래시(\) 문자와 그 뒤에 U+006E 라틴 소문자 n(n) 문자로 대체합니다.

    3. vCard 라인 추가 작업을 수행하여 outputname 타입, parameters 매개변수, value 값을 추가합니다.

  12. 만약 sex 또는 gender-identity 중 하나라도 빈 문자열이 아닌 값을 가지고 있다면, vCard 라인 추가 작업을 수행하여 output에 "GENDER" 타입과 sex, U+003B 세미콜론 문자(;), gender-identity 값을 이어 붙인 결과를 추가합니다.

  13. vCard 라인 추가 작업을 수행하여 output에 "END" 타입과 "VCARD" 값을 추가합니다.

위의 알고리즘이 사용자 에이전트에게 vCard 줄 추가를 요청할 때, 타입 type, 선택적 매개 변수, 그리고 값 value로 구성된 줄을 문자열 output에 추가해야 한다고 명시할 경우, 다음 단계를 수행해야 합니다:

  1. line을 빈 문자열로 설정합니다.

  2. typeASCII 대문자로 변환하여 line에 추가합니다.

  3. 매개 변수가 있는 경우, 추가된 순서대로 각 매개 변수에 대해 다음 하위 단계를 수행합니다:

    1. line에 U+003B 세미콜론 문자(;)를 추가합니다.

    2. 매개 변수의 이름을 line에 추가합니다.

    3. line에 U+003D 이퀄 사인 문자(=)를 추가합니다.

    4. 매개 변수의 값을 line에 추가합니다.

  4. line에 U+003A 콜론 문자(:)를 추가합니다.

  5. valueline에 추가합니다.

  6. maximum length를 75로 설정합니다.

  7. line코드 포인트 길이maximum length보다 클 때:

    1. line의 처음 maximum length 코드 포인트를 output에 추가합니다.

    2. line에서 처음 maximum length 코드 포인트를 제거합니다.

    3. output에 U+000D 캐리지 리턴 문자(CR)를 추가합니다.

    4. output에 U+000A 라인 피드 문자(LF)를 추가합니다.

    5. output에 U+0020 스페이스 문자를 추가합니다.

    6. maximum length를 74로 설정합니다.

  8. line의 남은 부분을 output에 추가합니다.

  9. output에 U+000D 캐리지 리턴 문자(CR)를 추가합니다.

  10. output에 U+000A 라인 피드 문자(LF)를 추가합니다.

위 단계가 사용자 에이전트에게 subitem에서 subname이라는 이름의 vCard 하위 속성을 수집한 결과를 얻으라고 요구할 때, 다음 단계를 수행해야 합니다:

  1. value를 빈 문자열로 설정합니다.

  2. subitem의 항목 중 subname이라는 이름의 각 속성에 대해, 다음 하위 단계를 수행합니다:

    1. 해당 속성의 항목 자체인 경우, 이 속성을 건너뜁니다.

    2. 이전 단계에서 건너뛴 속성을 제외한, subitemsubname이라는 이름의 첫 번째 속성이 아닌 경우, value에 U+002C 콤마 문자(,)를 추가합니다.

    3. 해당 속성의 으로부터 vCard 텍스트 문자열 이스케이프 결과를 value에 추가합니다.

  3. value를 반환합니다.

위 단계가 사용자 에이전트에게 subitem에서 subname이라는 이름의 첫 번째 vCard 하위 속성을 수집한 결과를 얻으라고 요구할 때, 다음 단계를 수행해야 합니다:

  1. subitemsubname이라는 이름의 속성이 없다면, 빈 문자열을 반환합니다.

  2. subname이라는 이름의 첫 번째 속성의 항목인 경우, 빈 문자열을 반환합니다.

  3. subitem에서 subname이라는 이름의 첫 번째 속성의 으로부터 vCard 텍스트 문자열 이스케이프 결과를 반환합니다.

위 알고리즘이 사용자 에이전트에게 value에 대해 vCard 텍스트 문자열을 이스케이프하라고 요구할 때, 다음 단계를 수행해야 합니다:

  1. value에 있는 모든 U+005C 리버스 솔리더스 문자(\) 앞에 또 다른 U+005C 리버스 솔리더스 문자(\)를 추가합니다.

  2. value에 있는 모든 U+002C 콤마 문자(,) 앞에 U+005C 리버스 솔리더스 문자(\)를 추가합니다.

  3. value에 있는 모든 U+003B 세미콜론 문자(;) 앞에 U+005C 리버스 솔리더스 문자(\)를 추가합니다.

  4. value에 있는 모든 U+000D 캐리지 리턴 U+000A 라인 피드 문자 쌍(CRLF)을 U+005C 리버스 솔리더스 문자(\)와 그 뒤에 오는 U+006E 라틴 소문자 N 문자(n)로 대체합니다.

  5. value에 있는 나머지 모든 U+000D 캐리지 리턴(CR) 또는 U+000A 라인 피드(LF) 문자를 U+005C 리버스 솔리더스 문자(\)와 그 뒤에 오는 U+006E 라틴 소문자 N 문자(n)로 대체합니다.

  6. 변경된 value를 반환합니다.

이 알고리즘은 입력이 http://microformats.org/profile/hcard 아이템 유형정의된 속성 이름에 대한 규칙을 준수하지 않을 경우, 유효하지 않은 vCard 출력을 생성할 수 있습니다.

5.3.1.2 예제

이 섹션은 비규범적입니다.

"Jack Bauer"라는 가상의 인물에 대한 긴 vCard 예제입니다:

<section id="jack" itemscope itemtype="http://microformats.org/profile/hcard">
 <h1 itemprop="fn">
  <span itemprop="n" itemscope>
   <span itemprop="given-name">Jack</span>
   <span itemprop="family-name">Bauer</span>
  </span>
 </h1>
 <img itemprop="photo" alt="" src="jack-bauer.jpg">
 <p itemprop="org" itemscope>
  <span itemprop="organization-name">Counter-Terrorist Unit</span>
  (<span itemprop="organization-unit">Los Angeles Division</span>)
 </p>
 <p>
  <span itemprop="adr" itemscope>
   <span itemprop="street-address">10201 W. Pico Blvd.</span><br>
   <span itemprop="locality">Los Angeles</span>,
   <span itemprop="region">CA</span>
   <span itemprop="postal-code">90064</span><br>
   <span itemprop="country-name">United States</span><br>
  </span>
  <span itemprop="geo">34.052339;-118.410623</span>
 </p>
 <h2>연락 방법</h2>
 <ul>
  <li itemprop="tel" itemscope>
   <span itemprop="value">+1 (310) 597 3781</span> <span itemprop="type">work</span>
   <meta itemprop="type" content="voice">
  </li>
  <li><a itemprop="url" href="https://en.wikipedia.org/wiki/Jack_Bauer">나의 위키백과 문서</a>에 메시지를 남길 수 있습니다.</li>
  <li><a itemprop="url" href="http://www.jackbauerfacts.com/">Jack Bauer 사실</a></li>
  <li itemprop="email"><a href="mailto:j.bauer@la.ctu.gov.invalid">j.bauer@la.ctu.gov.invalid</a></li>
  <li itemprop="tel" itemscope>
   <span itemprop="value">+1 (310) 555 3781</span> <span>
   <meta itemprop="type" content="cell">mobile phone</span>
  </li>
 </ul>
 <ins datetime="2008-07-20 21:00:00+01:00">
  <meta itemprop="rev" content="2008-07-20 21:00:00+01:00">
  <p itemprop="tel" itemscope><strong>업데이트!</strong><span itemprop="type"></span> 전화번호는
  <span itemprop="value">01632 960 123</span>입니다.</p>
 </ins>
</section>

줄 바꿈이 이상하게 되어 있는 것은 줄 바꿈이 마이크로데이터에서 의미가 있기 때문입니다. 줄 바꿈은 예를 들어 vCard 형식으로 변환할 때 보존됩니다.

이 예제는 사이트의 연락처 세부정보( address 요소 사용)를 보여주며, 두 개의 도로 구성 요소를 포함한 주소를 포함합니다:

<address itemscope itemtype="http://microformats.org/profile/hcard">
 <strong itemprop="fn"><span itemprop="n" itemscope><span itemprop="given-name">Alfred</span>
 <span itemprop="family-name">Person</span></span></strong> <br>
 <span itemprop="adr" itemscope>
  <span itemprop="street-address">1600 Amphitheatre Parkway</span> <br>
  <span itemprop="street-address">Building 43, Second Floor</span> <br>
  <span itemprop="locality">Mountain View</span>,
   <span itemprop="region">CA</span> <span itemprop="postal-code">94043</span>
 </span>
</address>

vCard 어휘는 사람의 이름만을 마크업하는 데 사용될 수 있습니다:

<span itemscope itemtype="http://microformats.org/profile/hcard"
><span itemprop=fn><span itemprop="n" itemscope><span itemprop="given-name"
>George</span> <span itemprop="family-name">Washington</span></span
></span></span>

이것은 "fn"이라는 이름과 "George Washington"이라는 값을 가진 이름-값 쌍 하나와 "n"이라는 이름과 값을 가진 두 번째 항목을 생성합니다. 두 번째 항목에는 "given-name"과 "family-name"이라는 두 개의 이름-값 쌍이 각각 "George"와 "Washington"이라는 값을 가집니다. 이것은 다음 vCard로 매핑되도록 정의됩니다:

BEGIN:VCARD
PROFILE:VCARD
VERSION:4.0
SOURCE:문서의 주소
FN:George Washington
N:Washington;George;;;
END:VCARD

5.3.2 vEvent

아이템 타입 http://microformats.org/profile/hcalendar#vevent을 가진 항목은 이벤트를 나타냅니다.

이 어휘는 아이템에 대한 전역 식별자를 지원하지 않습니다.

다음은 이 타입의 정의된 속성 이름입니다. 이들은 인터넷 일정 및 스케줄링 핵심 객체 사양 (iCalendar)에서 정의된 어휘를 기반으로 하며, 값 해석에 대한 자세한 정보는 해당 문서에서 확인할 수 있습니다. [RFC5545]

여기서는 iCalendar 어휘 중 이벤트와 관련된 부분만 사용되며, 이 어휘는 완전한 iCalendar 인스턴스를 표현할 수 없습니다.

attach

이벤트와 관련된 문서의 주소를 제공합니다.

절대 URL이어야 합니다.

attach라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

categories

이벤트가 분류될 수 있는 카테고리나 태그의 이름을 제공합니다.

은 텍스트여야 합니다.

categories라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

class

이벤트와 관련된 정보의 접근 분류를 제공합니다.

은 다음 값 중 하나를 가진 텍스트여야 합니다:

이것은 단지 권고사항일 뿐, 비밀 유지 조치로 간주될 수 없습니다.

class라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

comment

이벤트에 대한 코멘트를 제공합니다.

은 텍스트여야 합니다.

comment라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

description

이벤트에 대한 상세 설명을 제공합니다.

은 텍스트여야 합니다.

description라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

geo

이벤트의 지리적 위치를 제공합니다.

은 텍스트여야 하며, 다음 구문과 일치해야 합니다:

  1. 선택적으로, U+002B PLUS SIGN 문자(+) 또는 U+002D HYPHEN-MINUS 문자(-).
  2. 하나 이상의 ASCII 숫자.
  3. 선택적으로*, U+002E FULL STOP 문자(.)와 그 뒤에 하나 이상의 ASCII 숫자.
  4. U+003B SEMICOLON 문자(;).
  5. 선택적으로, U+002B PLUS SIGN 문자(+) 또는 U+002D HYPHEN-MINUS 문자(-).
  6. 하나 이상의 ASCII 숫자.
  7. 선택적으로*, U+002E FULL STOP 문자(.)와 그 뒤에 하나 이상의 ASCII 숫자.

별표(*)로 표시된 선택적 구성 요소는 포함되어야 하며, 각각 6자리 숫자여야 합니다.

값은 위도와 경도를 각각 그 순서대로(LAT LON 순서) 10진수로 지정합니다. 경도는 기준 자오선의 동서 위치를 각각 양수 또는 음수 실수로 나타내며, 위도는 적도의 북남 위치를 각각 양수 또는 음수 실수로 나타냅니다.

geo라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

location

이벤트의 위치를 제공합니다.

은 텍스트여야 합니다.

location라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

resources

이벤트에 필요한 자원을 제공합니다.

은 텍스트여야 합니다.

resources라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

status

이벤트의 확인 상태를 제공합니다.

은 다음 값 중 하나를 가진 텍스트여야 합니다:

status라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

summary

이벤트의 간략한 요약을 제공합니다.

은 텍스트여야 합니다.

사용자 에이전트는 을 사용할 때 U+000A LINE FEED (LF) 문자를 U+0020 SPACE 문자로 대체해야 합니다.

summary라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

dtend

이벤트가 끝나는 날짜와 시간을 제공합니다.

dtend라는 이름의 속성이 http://microformats.org/profile/hcalendar#vevent 타입의 아이템 내에 존재하며, 해당 아이템에 dtstart라는 이름의 속성이 있고 그 값이 유효한 날짜 문자열인 경우, dtend라는 이름의 속성의 유효한 날짜 문자열이어야 합니다. 그렇지 않으면, 해당 속성의 유효한 전역 날짜 및 시간 문자열이어야 합니다.

어느 경우든, 은 동일한 아이템dtstart 속성 값보다 늦어야 합니다.

dtend 속성으로 제공된 시간은 포함되지 않습니다. 따라서 하루 종일 진행되는 이벤트의 경우, dtend 속성의 은 이벤트가 끝나는 날 다음 날이 됩니다.

dtend라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서, duration라는 이름의 속성이 없는 경우에만 하나 존재할 수 있습니다.

dtstart

이벤트가 시작되는 날짜와 시간을 제공합니다.

유효한 날짜 문자열이거나 유효한 전역 날짜 및 시간 문자열이어야 합니다.

dtstart라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재해야 합니다.

duration

이벤트의 지속 시간을 제공합니다.

유효한 vevent 기간 문자열이어야 합니다.

표시된 기간은 값 내의 정수로 표현된 모든 기간의 합입니다.

duration라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서, dtend라는 이름의 속성이 없는 경우에만 하나 존재할 수 있습니다.

transp

이벤트가 캘린더에서 시간을 소비하는 것으로 간주되는지 여부를 제공하여, 바쁨/여유 시간 검색을 위한 목적에 사용됩니다.

은 다음 값 중 하나를 가진 텍스트여야 합니다:

transp라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

contact

이벤트의 연락처 정보를 제공합니다.

은 텍스트여야 합니다.

contact라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

url

이벤트의 URL을 제공합니다.

절대 URL이어야 합니다.

url라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

uid

이벤트에 해당하는 전역 고유 식별자를 제공합니다.

은 텍스트여야 합니다.

uid라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

exdate

반복 규칙에도 불구하고 이벤트가 발생하지 않는 날짜와 시간을 제공합니다.

유효한 날짜 문자열이거나 유효한 전역 날짜 및 시간 문자열이어야 합니다.

exdate라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

rdate

이벤트가 반복되는 날짜와 시간을 제공합니다.

은 다음 중 하나의 텍스트여야 합니다:

rdate라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

rrule

이벤트가 발생하는 날짜와 시간을 찾기 위한 규칙을 제공합니다.

iCalendar에서 정의된 RECUR 값 유형과 일치하는 텍스트여야 합니다. [RFC5545]

rrule라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

created

이벤트 정보가 일정 시스템에 처음 생성된 날짜와 시간을 제공합니다.

유효한 전역 날짜 및 시간 문자열이어야 합니다.

created라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

last-modified

이벤트 정보가 일정 시스템에서 마지막으로 수정된 날짜와 시간을 제공합니다.

유효한 전역 날짜 및 시간 문자열이어야 합니다.

last-modified라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

sequence

이벤트 정보의 개정 번호를 제공합니다.

유효한 음수가 아닌 정수이어야 합니다.

sequence라는 이름의 속성은 http://microformats.org/profile/hcalendar#vevent 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

문자열이 유효한 vevent 기간 문자열인 경우, 다음 패턴과 일치해야 합니다:

  1. U+0050 LATIN CAPITAL LETTER P 문자(P).

  2. 다음 중 하나:

5.3.2.1 iCalendar로 변환

nodes 목록이 document에 주어졌을 때, 사용자 에이전트는 다음 알고리즘을 실행하여 해당 노드들이 나타내는 모든 vEvent 데이터를 추출해야 합니다:

  1. nodes의 어떤 노드도 http://microformats.org/profile/hcalendar#vevent 타입의 아이템이 아니라면, vEvent 데이터가 없습니다. 알고리즘을 중단하고 아무것도 반환하지 않습니다.

  2. output을 빈 문자열로 설정합니다.

  3. 타입 "BEGIN"과 값 "VCALENDAR"을 가진 iCalendar 줄output에 추가합니다.

  4. 타입 "PRODID"과 사용자 에이전트를 나타내는 사용자 에이전트별 문자열과 동일한 값을 가진 iCalendar 줄output에 추가합니다.

  5. 타입 "VERSION"과 값 "2.0"을 가진 iCalendar 줄output에 추가합니다.

  6. nodes에서 http://microformats.org/profile/hcalendar#vevent 타입의 아이템인 각 노드 node에 대해 다음 단계를 실행합니다:

    1. 타입 "BEGIN"과 값 "VEVENT"을 가진 iCalendar 줄output에 추가합니다.

    2. 타입 "DTSTAMP"과 현재 날짜 및 시간을 나타내는 iCalendar DATE-TIME 문자열로 구성된 값을 가진 iCalendar 줄을 "VALUE=DATE-TIME" 주석과 함께 output에 추가합니다. [RFC5545]

    3. node아이템의 속성인 각 요소 element에 대해: element속성 이름에 있는 각 이름 name에 대해, 다음 목록에서 적절한 하위 단계를 실행합니다:

      속성의 아이템인 경우

      속성을 건너뜁니다.

      속성이 dtend인 경우
      속성이 dtstart인 경우
      속성이 exdate인 경우
      속성이 rdate인 경우
      속성이 created인 경우
      속성이 last-modified인 경우

      value를 속성의 에서 모든 U+002D HYPHEN-MINUS(-) 및 U+003A COLON(:) 문자를 제거한 결과로 설정합니다.

      속성의 유효한 날짜 문자열인 경우, name 타입과 value 값을 가진 iCalendar 줄을 "VALUE=DATE" 주석과 함께 output에 추가합니다.

      그렇지 않고 속성의 유효한 전역 날짜 및 시간 문자열인 경우, name 타입과 value 값을 가진 iCalendar 줄을 "VALUE=DATE-TIME" 주석과 함께 output에 추가합니다.

      그렇지 않으면 속성을 건너뜁니다.

      그 외의 경우

      name 타입과 속성의 을 가진 iCalendar 줄output에 추가합니다.

    4. 타입 "END"과 값 "VEVENT"을 가진 iCalendar 줄output에 추가합니다.

  7. 타입 "END"과 값 "VCALENDAR"을 가진 iCalendar 줄output에 추가합니다.

위 알고리즘에서 사용자 에이전트가 type 타입, value 값, 및 선택적으로 주석으로 구성된 iCalendar 줄을 문자열 output에 추가해야 한다고 하는 경우, 다음 단계를 실행해야 합니다:

  1. line을 빈 문자열로 설정합니다.

  2. ASCII 대문자로 변환된 typeline에 추가합니다.

  3. 주석이 있는 경우:

    1. U+003B SEMICOLON 문자(;)를 line에 추가합니다.

    2. 주석을 line에 추가합니다.

  4. U+003A COLON 문자(:)를 line에 추가합니다.

  5. value에 있는 모든 U+005C REVERSE SOLIDUS 문자(\) 앞에 다른 U+005C REVERSE SOLIDUS 문자(\)를 추가합니다.

  6. value에 있는 모든 U+002C COMMA 문자(,) 앞에 U+005C REVERSE SOLIDUS 문자(\)를 추가합니다.

  7. value에 있는 모든 U+003B SEMICOLON 문자(;) 앞에 U+005C REVERSE SOLIDUS 문자(\)를 추가합니다.

  8. value에 있는 모든 U+000D CARRIAGE RETURN 및 U+000A LINE FEED 문자 쌍(CRLF)을 U+005C REVERSE SOLIDUS 문자(\)와 U+006E LATIN SMALL LETTER N 문자(n)로 교체합니다.

  9. value에 남아 있는 모든 U+000D CARRIAGE RETURN(CR) 또는 U+000A LINE FEED(LF) 문자를 U+005C REVERSE SOLIDUS 문자(\)와 U+006E LATIN SMALL LETTER N 문자(n)로 교체합니다.

  10. valueline에 추가합니다.

  11. maximum length를 75로 설정합니다.

  12. line코드 포인트 길이maximum length보다 큰 동안:

    1. line의 첫 maximum length 코드 포인트를 output에 추가합니다.

    2. line의 첫 maximum length 코드 포인트를 제거합니다.

    3. U+000D CARRIAGE RETURN 문자(CR)를 output에 추가합니다.

    4. U+000A LINE FEED 문자(LF)를 output에 추가합니다.

    5. U+0020 SPACE 문자를 output에 추가합니다.

    6. maximum length를 74로 설정합니다.

  13. (남아 있는) lineoutput에 추가합니다.

  14. U+000D CARRIAGE RETURN 문자(CR)를 output에 추가합니다.

  15. U+000A LINE FEED 문자(LF)를 output에 추가합니다.

이 알고리즘은 입력이 아이템 타입정의된 속성 이름에 대해 설명된 규칙을 따르지 않는 경우, 유효하지 않은 iCalendar 출력을 생성할 수 있습니다.

5.3.2.2 예시

이 섹션은 비규범적입니다.

다음은 vEvent 어휘를 사용하여 이벤트를 마크업한 페이지의 예시입니다:

<body itemscope itemtype="http://microformats.org/profile/hcalendar#vevent">
...
<h1 itemprop="summary">Bluesday Tuesday: Money Road</h1>
...
<time itemprop="dtstart" datetime="2009-05-05T19:00:00Z">May 5th @ 7pm</time>
(until <time itemprop="dtend" datetime="2009-05-05T21:00:00Z">9pm</time>)
...
<a href="http://livebrum.co.uk/2009/05/05/bluesday-tuesday-money-road"rel="bookmark" itemprop="url">Link to this page</a>
...
<p>Location: <span itemprop="location">The RoadHouse</span></p>
...
<p><input type=button value="Add to Calendar"onclick="location = getCalendar(this)"></p>
...
<meta itemprop="description" content="via livebrum.co.uk">
</body>

getCalendar() 함수는 독자가 연습으로 남겨둡니다.

같은 페이지는 블로그에 복사하여 붙여넣기 위한 다음과 같은 마크업을 제공할 수도 있습니다:

<div itemscope itemtype="http://microformats.org/profile/hcalendar#vevent">
<p>I'm going to
<strong itemprop="summary">Bluesday Tuesday: Money Road</strong>,
<time itemprop="dtstart" datetime="2009-05-05T19:00:00Z">May 5th at 7pm</time>
to <time itemprop="dtend" datetime="2009-05-05T21:00:00Z">9pm</time>,
at <span itemprop="location">The RoadHouse</span>!</p>
<p><a href="http://livebrum.co.uk/2009/05/05/bluesday-tuesday-money-road" itemprop="url">See this event on livebrum.co.uk</a>.</p>
<meta itemprop="description" content="via livebrum.co.uk">
</div>

5.3.3 저작물의 라이선스

아이템 타입 http://n.whatwg.org/work을 가진 항목은 저작물(예: 기사, 이미지, 비디오, 노래 등)을 나타냅니다. 이 타입은 주로 저작물의 라이선스 정보를 포함하도록 하기 위해 고안되었습니다.

다음은 이 타입의 정의된 속성 이름들입니다.

work

설명된 저작물을 식별합니다.

절대 URL이어야 합니다.

work라는 이름의 속성은 http://n.whatwg.org/work 타입의 각 아이템 내에 정확히 하나만 존재해야 합니다.

title

저작물의 이름을 제공합니다.

title라는 이름의 속성은 http://n.whatwg.org/work 타입의 각 아이템 내에서 하나만 존재할 수 있습니다.

author

저작물의 저자나 창작자의 이름 또는 연락처 정보를 제공합니다.

http://microformats.org/profile/hcard 타입의 아이템이거나 텍스트여야 합니다.

author라는 이름의 속성은 http://n.whatwg.org/work 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

license

저작물이 이용 가능한 라이선스 중 하나를 식별합니다.

절대 URL이어야 합니다.

license라는 이름의 속성은 http://n.whatwg.org/work 타입의 각 아이템 내에서 여러 개 존재할 수 있습니다.

5.3.3.1 예시

이 섹션은 비규범적입니다.

다음 예시는 My Pond라는 제목의 이미지를 포함하며, 이 이미지는 크리에이티브 커먼즈 저작자표시-동일조건변경허락 4.0 국제 라이선스와 MIT 라이선스로 동시에 라이선스되었습니다.

<figure itemscope itemtype="http://n.whatwg.org/work">
 <img itemprop="work" src="mypond.jpeg">
 <figcaption>
  <p><cite itemprop="title">My Pond</cite></p>
  <p><small>Licensed under the <a itemprop="license"
  href="https://creativecommons.org/licenses/by-sa/4.0/">Creative
  Commons Attribution-Share Alike 4.0 International License</a>
  and the <a itemprop="license"
  href="http://www.opensource.org/licenses/mit-license.php">MIT
  license</a>.</small>
 </figcaption>
</figure>

5.4 HTML을 다른 포맷으로 변환하기

5.4.1 JSON

사용자가 document 내의 nodes 리스트를 가지고, 해당 노드에서 마이크로데이터를 JSON 형식으로 추출하는 알고리즘을 실행해야 할 때:

  1. result를 빈 객체로 설정합니다.

  2. items를 빈 배열로 설정합니다.

  3. nodes 내의 각 node에 대해, 해당 요소가 최상위 마이크로데이터 항목인지 확인하고, 그렇다면 해당 요소에 대해 객체를 가져와 items에 추가합니다.

  4. result에 "items"라는 항목을 추가하고, 그 값으로 items 배열을 설정합니다.

  5. 최소화된 형태로 result를 JSON으로 직렬화한 결과를 반환합니다(토큰 사이에 공백 없이, 숫자에서 불필요한 0 자리를 없애고, 전용 이스케이프 시퀀스가 없는 문자의 경우에만 유니코드 이스케이프를 사용하며, 적절할 때 소문자 "e"를 사용). [JSON]

이 알고리즘은 객체에 배열을 포함하는 단일 속성을 반환하며, 이는 필요할 때 알고리즘을 확장할 수 있도록 하기 위함입니다.

사용자가 item에 대한 객체를 가져와야 할 때, 선택적으로 memory 요소 목록과 함께 다음 단계를 실행해야 합니다:

  1. result를 빈 객체로 설정합니다.

  2. 알고리즘에 memory가 전달되지 않았다면, memory를 빈 리스트로 설정합니다.

  3. itemmemory에 추가합니다.

  4. 만약 item아이템 타입을 가지고 있다면, result에 "type"이라는 항목을 추가하고 그 값으로 item아이템 타입을 나열한 배열을 추가합니다. 이 배열은 itemtype 속성에 명시된 순서대로 나열합니다.

  5. 만약 item글로벌 식별자를 가지고 있다면, result에 "id"라는 항목을 추가하고 그 값으로 item글로벌 식별자를 추가합니다.

  6. properties를 빈 객체로 설정합니다.

  7. 한 개 이상의 속성 이름을 가지고 있으며 해당 아이템의 속성 중 하나인 element에 대해, 알고리즘에 의해 주어진 순서로 다음 단계를 실행합니다:

    1. element속성 값value로 설정합니다.

    2. 만약 value아이템인 경우: 만약 valuememory에 있는 경우 value를 문자열 "ERROR"로 설정합니다. 그렇지 않다면 memory의 복사본을 전달하여 value에 대해 객체를 가져오고 반환된 객체로 value를 대체합니다.

    3. element속성 이름에 있는 각 name에 대해 다음 단계를 실행합니다:

      1. 만약 propertiesname이라는 항목이 없다면, propertiesname이라는 항목을 추가하고 그 값을 빈 배열로 설정합니다.

      2. propertiesname 항목에 value를 추가합니다.

  8. result에 "properties"라는 항목을 추가하고 그 값으로 properties 객체를 설정합니다.

  9. result를 반환합니다.

예를 들어, 이 마크업을 보세요:

<!DOCTYPE HTML>
<html lang="en">
<title>My Blog</title>
<article itemscope itemtype="http://schema.org/BlogPosting">
 <header>
  <h1 itemprop="headline">Progress report</h1>
  <p><time itemprop="datePublished" datetime="2013-08-29">today</time></p>
  <link itemprop="url" href="?comments=0">
 </header>
 <p>All in all, he's doing well with his swim lessons. The biggest thing was he had trouble
 putting his head in, but we got it down.</p>
 <section>
  <h1>Comments</h1>
  <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c1">
   <link itemprop="url" href="#c1">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">Greg</span>
    </span></p>
    <p><time itemprop="commentTime" datetime="2013-08-29">15 minutes ago</time></p>
   </footer>
   <p>Ha!</p>
  </article>
  <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c2">
   <link itemprop="url" href="#c2">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">Charlotte</span>
    </span></p>
    <p><time itemprop="commentTime" datetime="2013-08-29">5 minutes ago</time></p>
   </footer>
   <p>When you say "we got it down"...</p>
  </article>
 </section>
</article>

위 알고리즘에 의해 이 마크업은 다음과 같은 JSON으로 변환됩니다(페이지의 URL이 https://blog.example.com/progress-report라고 가정):

{
  "items": [
    {
      "type": [ "http://schema.org/BlogPosting" ],
      "properties": {
        "headline": [ "Progress report" ],
        "datePublished": [ "2013-08-29" ], 
        "url": [ "https://blog.example.com/progress-report?comments=0" ],
        "comment": [
          {
            "type": [ "http://schema.org/UserComments" ],
            "properties": { 
              "url": [ "https://blog.example.com/progress-report#c1" ], 
              "creator": [
                {
                  "type": [ "http://schema.org/Person" ], 
                  "properties": { 
                    "name": [ "Greg" ] 
                  }
                }
              ], 
              "commentTime": [ "2013-08-29" ] 
            } 
          } 
          { 
            "type": [ "http://schema.org/UserComments" ], 
            "properties": { 
              "url": [ "https://blog.example.com/progress-report#c2" ], 
              "creator": [ 
                { 
                  "type": [ "http://schema.org/Person" ], 
                  "properties": { 
                    "name": [ "Charlotte" ] 
                  } 
                } 
              ], 
              "commentTime": [ "2013-08-29" ] 
            } 
          } 
        ] 
      } 
    } 
  ] 
}

6 사용자 상호작용

6.1 hidden 속성

Global_attributes/hidden

단 하나의 엔진에서만 지원됩니다.

Firefox지원 안 됨Safari지원 안 됨Chrome102+
Opera지원 안 됨Edge102+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Global_attributes/hidden

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5.1+Chrome10+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android12+

모든 HTML 요소hidden 콘텐츠 속성을 설정할 수 있습니다. hidden 속성은 다음 키워드 및 상태를 가지는 열거형 속성입니다:

키워드 상태 간단한 설명
hidden 숨김 렌더링되지 않습니다.
(빈 문자열)
until-found 발견될 때까지 숨김 렌더링되지 않지만 내부 콘텐츠는 페이지 찾기프래그먼트 탐색에서 접근할 수 있습니다.

이 속성의 누락된 값 기본값숨기지 않음 상태이며, 잘못된 값 기본값숨김 상태입니다.

요소가 hidden 속성을 숨김 상태에서 가지고 있을 때, 이는 해당 요소가 아직 페이지의 현재 상태와 직접적으로 관련이 없거나, 더 이상 관련이 없음을 나타내거나, 페이지의 다른 부분에서 재사용되도록 선언된 콘텐츠를 사용자에게 직접 접근하지 않도록 사용 중임을 나타냅니다. 사용자 에이전트는 숨김 상태에 있는 요소를 렌더링하지 않아야 합니다. 이 요구 사항은 스타일 레이어를 통해 간접적으로 구현될 수 있습니다. 예를 들어, 웹 브라우저는 렌더링 섹션에서 제안된 규칙을 사용하여 이러한 요구 사항을 구현할 수 있습니다.

요소가 hidden 속성을 발견될 때까지 숨김 상태에서 가지고 있을 때, 이는 해당 요소가 숨김 상태와 유사하게 숨겨져 있지만, 요소 내의 콘텐츠는 페이지 찾기프래그먼트 탐색에서 접근할 수 있음을 나타냅니다. 이러한 기능들이 요소의 하위 트리 내의 목표로 스크롤하려고 할 때, 사용자 에이전트는 콘텐츠를 스크롤하기 전에 hidden 속성을 제거하여 콘텐츠를 노출합니다. beforematch라는 이벤트도 속성이 제거되기 전에 요소에서 발생합니다.

웹 브라우저는 hidden 속성이 발견될 때까지 숨김 상태에 있을 때 'display: none' 대신 'content-visibility: hidden'을 사용합니다. 이는 렌더링 섹션에 명시되어 있습니다.

이 속성이 일반적으로 CSS를 사용하여 구현되기 때문에 CSS를 사용하여 재정의할 수도 있습니다. 예를 들어, 모든 요소에 'display: block'을 적용하는 규칙은 숨김 상태의 효과를 취소합니다. 따라서 저자는 스타일 시트를 작성할 때 속성이 여전히 기대대로 스타일링되는지 확인해야 합니다. 또한, 발견될 때까지 숨김 상태를 지원하지 않는 레거시 사용자 에이전트는 'content-visibility: hidden' 대신 'display: none'을 가지므로, 저자는 스타일 시트에서 발견될 때까지 숨김 요소의 'display' 또는 'content-visibility' 속성을 변경하지 않도록 주의해야 합니다.

hidden 속성이 발견될 때까지 숨김 상태에 있는 요소는 'content-visibility: hidden'을 사용하며 'display: none'과는 다릅니다. 다음 두 가지 주의사항이 있습니다:

  1. 요소는 레이아웃 컨테인먼트의 영향을 받아야 페이지 찾기에서 노출됩니다. 이는 요소가 발견될 때까지 숨김 상태에 있으며 'display' 값이 'none', 'contents', 또는 'inline'일 경우 페이지 찾기에 의해 노출되지 않음을 의미합니다.

  2. 요소는 생성된 박스를 발견될 때까지 숨김 상태에서도 가지므로, 요소 주위의 테두리, 여백 및 패딩이 여전히 렌더링됩니다.

다음의 골격 예제에서 이 속성은 사용자가 로그인할 때까지 웹 게임의 메인 화면을 숨기는 데 사용됩니다:

  <h1>The Example Game</h1>
  <section id="login">
   <h2>Login</h2>
   <form>
    ...
    <!-- calls login() once the user's credentials have been checked -->
   </form>
   <script>
    function login() {
      // 화면 전환
      document.getElementById('login').hidden = true;
      document.getElementById('game').hidden = false;
    }
   </script>
  </section>
  <section id="game" hidden>
   ...
  </section>

hidden 속성은 다른 프레젠테이션에서 정당하게 표시될 수 있는 콘텐츠를 숨기는 데 사용되어서는 안 됩니다. 예를 들어, hidden 속성을 탭 대화 상자의 패널을 숨기는 데 사용하는 것은 잘못된 사용입니다. 이는 탭 인터페이스가 단순한 오버플로우 프레젠테이션의 일종이기 때문입니다. 모든 양식 컨트롤을 큰 페이지에서 스크롤바로 표시하는 것과 마찬가지로 사용할 수 있습니다. 이 속성을 사용하여 특정 프레젠테이션에서만 콘텐츠를 숨기는 것도 잘못된 사용입니다. hidden으로 표시된 콘텐츠는 모든 프레젠테이션에서 숨겨지며, 예를 들어 스크린 리더에서도 숨겨집니다.

hidden이 아닌 요소는 hidden인 요소에 하이퍼링크를 걸 수 없습니다. labeloutput 요소의 for 속성도 hidden인 요소를 참조해서는 안 됩니다. 이러한 경우 사용자에게 혼란을 줄 수 있습니다.

그러나 요소와 스크립트는 다른 컨텍스트에서 hidden인 요소를 참조할 수 있습니다.

예를 들어, href 속성을 사용하여 hidden 속성으로 표시된 섹션에 링크를 거는 것은 잘못된 사용입니다. 콘텐츠가 관련이 없거나 적용되지 않는 경우, 링크를 걸 이유가 없습니다.

그러나 ARIA aria-describedby 속성을 사용하여 hidden인 설명을 참조하는 것은 문제가 없습니다. 설명이 숨겨져 있다는 것은 단독으로는 유용하지 않음을 의미하지만, 설명이 특정 맥락에서 참조되는 요소에서 유용하게 작성될 수 있습니다.

마찬가지로, canvas 요소는 hidden 속성으로 표시되어 스크립트 그래픽 엔진에서 오프스크린 버퍼로 사용될 수 있으며, 폼 컨트롤은 form 속성을 사용하여 숨겨진 form 요소를 참조할 수 있습니다.

hidden 속성으로 숨겨진 섹션 내의 요소는 여전히 활성 상태이며, 예를 들어 스크립트와 폼 컨트롤은 계속 실행되고 제출됩니다. 사용자에게 표시되는 방식만 변경됩니다.

HTMLElement/hidden

모든 최신 엔진에서 지원됩니다.

Firefox4+Safari5.1+Chrome6+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android12+

hidden getter 단계는 다음과 같습니다:

  1. hidden 속성이 발견될 때까지 숨김 상태에 있는 경우, "until-found"를 반환합니다.

  2. hidden 속성이 설정되어 있으면 true를 반환합니다.

  3. false를 반환합니다.

hidden setter 단계는 다음과 같습니다:

  1. 주어진 값이 ASCII 대소문자 무시 일치로 "until-found"와 일치하는 문자열인 경우, hidden 속성을 "until-found"로 설정합니다.

  2. 그렇지 않고 주어진 값이 false인 경우, hidden 속성을 제거합니다.

  3. 그렇지 않고 주어진 값이 빈 문자열인 경우, hidden 속성을 제거합니다.

  4. 그렇지 않고 주어진 값이 null인 경우, hidden 속성을 제거합니다.

  5. 그렇지 않고 주어진 값이 0인 경우, hidden 속성을 제거합니다.

  6. 그렇지 않고 주어진 값이 NaN인 경우, hidden 속성을 제거합니다.

  7. 그렇지 않으면, hidden 속성을 빈 문자열로 설정합니다.

상위 발견될 때까지 숨김 상태 노출 알고리즘currentNode에 대해 다음 단계를 수행합니다:

  1. currentNode평면 트리 내에서 부모 노드를 가지고 있을 때:

    1. currentNode발견될 때까지 숨김 상태의 hidden 속성이 있는 경우:

      1. 이벤트를 발생시킵니다 beforematch라는 이름으로 currentNode에서 이벤트를 발생시킵니다.

      2. currentNode에서 hidden 속성을 제거합니다.

    2. currentNodecurrentNode의 부모 노드로 설정합니다. 이 부모 노드는 평면 트리 내에 있습니다.

6.2 페이지 가시성

탐색 가능한 내비게이션시스템 가시성 상태는, 생성 시 초기 값을 포함하여, 사용자 에이전트에 의해 결정됩니다. 예를 들어 브라우저 창이 최소화되었는지, 브라우저 탭이 현재 백그라운드에 있는지, 또는 작업 전환기와 같은 시스템 요소가 페이지를 가리고 있는지를 나타냅니다.

사용자 에이전트가 시스템 가시성 상태탐색 가능한 내비게이션 traversable에 대해 newState로 변경되었다고 판단하면, 다음 단계를 실행해야 합니다:

  1. traversable활성 문서포함 자손 내비게이션navigables로 합니다.

  2. navigables의 각 navigable에 대해 다음과 같이 순차적으로 실행합니다:

    1. navigable활성 문서document로 합니다.

    2. 글로벌 작업을 큐에 추가하고, document관련 글로벌 객체newState를 사용하여 document가시성 상태를 업데이트합니다.

Document가시성 상태를 가지고 있으며, 이는 "hidden" 또는 "visible" 중 하나입니다. 초기 값은 "hidden"로 설정됩니다.

Document/visibilityState

모든 최신 엔진에서 지원됩니다.

Firefox18+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android20+

visibilityState getter 단계는 다음과 같습니다: this가시성 상태를 반환합니다.

Document/hidden

모든 최신 엔진에서 지원됩니다.

Firefox18+Safari7+Chrome33+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android12.1+

hidden getter 단계는 this가시성 상태가 "hidden"인 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

Document documentvisibilityState업데이트하려면 다음과 같이 합니다:

  1. document가시성 상태visibilityState와 동일하면, 반환합니다.

  2. document가시성 상태visibilityState로 설정합니다.

  3. 새로운 VisibilityStateEntry를 큐에 추가하고, 그 가시성 상태visibilityState로 하고, 현재 고해상도 시간document관련 글로벌 객체에 따라 타임스탬프로 사용합니다.

  4. 화면 방향 변경 단계document로 실행합니다. [SCREENORIENTATION]

  5. 뷰 전환 페이지 가시성 변경 단계document로 실행합니다.

  6. 다른 사양에서 정의된 페이지 가시성 변경 단계가시성 상태document로 실행합니다.

    사양 저자들이 페이지 가시성 변경 단계 훅을 사용하기보다는 이 지점에서 그들의 사양에 대한 호출을 직접 추가하는 것이 더 나을 것입니다. 그렇게 하면 교차 사양 호출 순서가 명확히 정의될 수 있습니다. 이 문서를 작성하는 시점에서 페이지 가시성 변경 단계를 포함하는 것으로 알려진 사양은 다음과 같습니다: Device Posture APIWeb NFC. [DEVICEPOSTURE] [WEBNFC]

  7. documentvisibilitychange라는 이름의 이벤트를 발생시키고, 그 bubbles 속성을 true로 초기화합니다.

6.2.1 VisibilityStateEntry 인터페이스

VisibilityStateEntry

단일 엔진에서만 지원됩니다.

Firefox지원 안 함Safari지원 안 함Chrome115+
Opera?Edge115+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

VisibilityStateEntry 인터페이스는 문서가 활성화되는 순간부터 가시성 변화를 노출합니다.

예를 들어, 이는 페이지의 JavaScript 코드가 가시성 변화와 페인트 타이밍 간의 상관관계를 조사할 수 있게 합니다:
function wasHiddenBeforeFirstContentfulPaint() {
    const fcpEntry = performance.getEntriesByName("first-contentful-paint")[0];
    const visibilityStateEntries = performance.getEntriesByType("visibility-state");
    return visibilityStateEntries.some(e =>
                                            e.startTime < fcpEntry.startTime &&
                                            e.name === "hidden");
}

페이지를 숨기면 렌더링 및 기타 사용자 에이전트 작업의 제한이 발생할 수 있으므로 가시성 변화를 이러한 제한이 발생했다는 징후로 사용하는 것이 일반적입니다. 그러나 다른 브라우저에서는 긴 비활성화 기간과 같은 다른 요인이 제한을 유발할 수도 있습니다.

[Exposed=(Window)]
interface VisibilityStateEntry : PerformanceEntry {
  readonly attribute DOMString name;                 // 상속된 name을 가립니다.
  readonly attribute DOMString entryType;            // 상속된 entryType을 가립니다.
  readonly attribute DOMHighResTimeStamp startTime;  // 상속된 startTime을 가립니다.
  readonly attribute unsigned long duration;         // 상속된 duration을 가립니다.
};

VisibilityStateEntry에는 DOMHighResTimeStamp 타임스탬프가 연결되어 있습니다.

VisibilityStateEntry에는 "visible" 또는 "hidden" 가시성 상태가 연결되어 있습니다.

name getter 단계는 this가시성 상태를 반환합니다.

entryType getter 단계는 "visibility-state"를 반환합니다.

startTime getter 단계는 this타임스탬프를 반환합니다.

duration getter 단계는 0을 반환합니다.

6.3 비활성 서브트리

동일한 이름의 속성에 대한 설명은 inert를 참조하십시오.

노드(특히 요소와 텍스트 노드)는 비활성 상태가 될 수 있습니다. 노드가 비활성 상태일 때:

비활성 노드는 일반적으로 포커스를 받을 수 없으며, 사용자 에이전트는 비활성 노드를 접근성 API나 보조 기술에 노출하지 않습니다. 비활성 노드가 명령일 경우, 위에서 설명한 방식으로 사용자가 이를 사용할 수 없게 됩니다.

그러나 사용자 에이전트는 사용자가 페이지 내 검색과 텍스트 선택에 대한 제한을 무시할 수 있도록 허용할 수 있습니다.

기본적으로, 노드는 비활성 상태가 아닙니다.

document documentsubjectdocument상단 레이어에서 가장 상위에 있는 대화 상자 요소일 때, 모달 대화 상자로 인해 차단됩니다. document가 이 상태로 차단되는 동안, subject 요소와 그 평면 트리 하위 요소들을 제외한 모든 document연결된 노드는 비활성 상태가 되어야 합니다.

subjectinert 속성을 통해 추가적으로 비활성 상태가 될 수 있지만, 이는 subject 자체에 지정된 경우에만 가능합니다(즉, subject는 조상 요소들의 비활성 상태를 벗어납니다). subject평면 트리 하위 요소들도 유사한 방식으로 비활성 상태가 될 수 있습니다.

대화 상자 요소의 showModal() 메서드는 이 메커니즘을 트리거하여, 요소를 상단 레이어에 추가함으로써 대화 상자 요소를 노드 문서상단 레이어에 추가합니다.

6.3.2 inert 속성

Global_attributes/inert

모든 현재 엔진에서 지원됨.

Firefox112+Safari15.5+Chrome102+
Opera?Edge102+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

inert 속성은 요소와 그 평면 트리 자손 중 inert 상태를 벗어나지 않는 것들을 사용자 에이전트가 inert 상태로 만들도록 지시하는 부울 속성입니다.

비활성 서브트리는 페이지의 inert 상태가 아닌 다른 부분을 이해하거나 사용하는 데 중요한 콘텐츠나 컨트롤을 포함해서는 안 됩니다. 비활성 서브트리의 콘텐츠는 모든 사용자에게 인지되지 않거나 인터랙티브하지 않습니다. 저자는 콘텐츠가 시각적으로 가려진 경우를 제외하고는 요소를 inert로 지정하지 않아야 합니다. 대부분의 경우, 저자는 개별 폼 컨트롤에 inert 속성을 지정해서는 안 됩니다. 이러한 경우에는 disabled 속성이 더 적절할 가능성이 큽니다.

다음 예제는 "로딩" 메시지에 의해 시각적으로 가려진 부분적으로 로드된 콘텐츠를 inert로 표시하는 방법을 보여줍니다.

<section aria-labelledby=s1>
  <h3 id=s1>Population by City</h3>
  <div class=container>
    <div class=loading><p>Loading...</p></div>
    <div inert>
      <form>
        <fieldset>
          <legend>Date range</legend>
          <div>
            <label for=start>Start</label>
            <input type=date id=start>
          </div>
          <div>
            <label for=end>End</label>
            <input type=date id=end>
          </div>
          <div> 
            <button>적용</button>
          </div>
        </fieldset>
      </form>
      <table>
        <caption>20--년부터 20--년까지</caption>
        <thead>
          <tr>
            <th>도시</th>
            <th></th>
            <th>20-- 인구수</th>
            <th>20-- 인구수</th> 
            <th>인구 변화율</th> 
          </tr>
        </thead>
        <tbody>
          <!-- ... -->
        </tbody>
      </table>
    </div>
  </div>
</section>
시 인구 콘텐츠가 로드되지 않은 상태로 '로딩 중' 메시지가 시각적으로 가려지고 있습니다. 이는 콘텐츠가 완전히 렌더링되지 않았기 때문에 비활성 상태입니다.

"로딩" 오버레이가 비활성 콘텐츠를 가리며, 이로 인해 비활성 콘텐츠가 현재 접근할 수 없음을 시각적으로 명확히 합니다. 제목과 "로딩 중" 텍스트는 inert 속성이 있는 요소의 하위 자손이 아닙니다. 이는 이 텍스트가 모든 사용자에게 접근 가능하도록 하면서도, 비활성 콘텐츠는 누구도 상호작용할 수 없도록 보장합니다.

기본적으로, 요소 또는 그 서브트리가 비활성 상태라는 시각적 표시가 지속적으로 제공되지는 않습니다. 이러한 콘텐츠에 적절한 시각적 스타일은 상황에 따라 다를 수 있습니다. 예를 들어, 비활성화된 오프스크린 내비게이션 패널은 기본 스타일이 필요하지 않으며, 이는 오프스크린 위치가 콘텐츠를 시각적으로 가리기 때문입니다. 마찬가지로, 모달 대화 상자 요소의 백드롭은 웹 페이지의 비활성 콘텐츠를 시각적으로 가리는 수단으로 사용되며, 비활성 콘텐츠를 특별히 스타일링하지 않아도 됩니다.

그러나 다른 상황에서는 문서의 활성 부분과 비활성 부분을 명확히 구분하는 것이 중요합니다. 특히 모든 사용자가 페이지의 모든 부분을 한 번에 볼 수 있는 것은 아니기 때문에 사용자 혼란을 방지하기 위해서입니다. 예를 들어, 스크린 리더를 사용하는 사용자, 작은 장치나 확대경을 사용하는 사용자, 심지어 매우 작은 창을 사용하는 사용자도 페이지의 활성 부분을 볼 수 없을 수 있으며, 비활성 섹션이 명확히 비활성으로 표시되지 않으면 좌절감을 느낄 수 있습니다.

HTMLElement/inert

모든 현재 엔진에서 지원됨.

Firefox112+Safari15.5+Chrome102+
Opera?Edge102+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

inert IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

6.4 사용자 활성화 추적

사용자에게 불쾌감을 줄 수 있는 특정 API(예: 팝업 열기 또는 전화 진동)를 남용하지 않도록, 사용자 에이전트는 사용자가 웹 페이지와 적극적으로 상호작용하고 있을 때 또는 적어도 한 번 이상 상호작용한 경우에만 이러한 API를 허용합니다. 이 "적극적인 상호작용" 상태는 이 섹션에서 정의된 메커니즘을 통해 유지됩니다.

6.4.1 데이터 모델

사용자 활성화를 추적하기 위해 각 Window W에는 다음 두 가지 관련 값이 있습니다:

사용자 에이전트는 또한 일시적 활성화 지속 시간을 정의합니다. 이는 사용자 활성화 기반 API(예: 팝업 열기 등)가 사용할 수 있는 일정 기간을 나타내는 상수 값입니다.

일시적 활성화 지속 시간은 몇 초 정도로 예상되며, 사용자가 페이지와의 상호작용과 페이지가 활성화 기반 API를 호출하는 것 사이의 연결을 인식할 수 있도록 합니다.

그런 다음, W에 대해 다음과 같은 불리언 사용자 활성화 상태가 있습니다:

고정 활성화

현재 고해상도 시간W에서 마지막 활성화 타임스탬프보다 크거나 같은 경우, W고정 활성화 상태로 간주됩니다.

이것은 W의 역사적인 활성화 상태로, 사용자가 W에서 한 번이라도 상호작용했는지를 나타냅니다. 초기에는 false로 시작하며, W가 첫 번째 활성화 알림을 받을 때 true로 변경되며, 다시 false로 돌아가지 않습니다.

일시적 활성화

현재 고해상도 시간W에서 마지막 활성화 타임스탬프보다 크거나 같고, W에서 마지막 활성화 타임스탬프일시적 활성화 지속 시간을 더한 값보다 작은 경우, W일시적 활성화 상태로 간주됩니다.

이것은 W의 현재 활성화 상태로, 사용자가 최근에 W와 상호작용했는지를 나타냅니다. 초기에는 false 값으로 시작하며, W가 각 활성화 알림을 받을 때마다 일정 시간 동안 true로 유지됩니다.

일시적 활성화 상태는 일시적 활성화 지속 시간이 경과하여 마지막 사용자 활성화 이후 false가 되면 만료된 것으로 간주됩니다. 이는 활성화 소비를 통해 만료 시간 이전에도 false가 될 수 있습니다.

히스토리 액션 활성화

W마지막 히스토리 액션 활성화 타임스탬프W마지막 활성화 타임스탬프와 같지 않은 경우, W히스토리 액션 활성화 상태로 간주됩니다.

이것은 사용자 활성화의 특별한 변형으로, 특정 세션 히스토리 API에 접근할 수 있게 해줍니다. 이러한 API가 너무 자주 사용되면 사용자가 브라우저 UI를 통해 뒤로 이동하는 것이 어려워질 수 있기 때문입니다. 초기에는 false 값으로 시작하며, 사용자가 W와 상호작용할 때마다 true가 되지만, 히스토리 액션 활성화 소비를 통해 다시 false로 재설정됩니다. 이는 중간에 사용자 활성화 없이 이러한 API를 여러 번 연속으로 사용할 수 없도록 보장합니다. 그러나 일시적 활성화와 달리, 이러한 API를 사용해야 하는 시간 제한은 없습니다.

마지막 활성화 타임스탬프마지막 히스토리 액션 활성화 타임스탬프document완전 활성 상태가 변경된 후에도 유지됩니다(예: document에서 탐색하거나 캐시된 document로 탐색한 후). 이는 동일한 document가 재사용되는 한 고정 활성화 상태가 여러 탐색에 걸쳐 유지됨을 의미합니다. 일시적 활성화 상태에 대해서는, 원래의 만료 시간이 그대로 유지되며(즉, 상태는 원래의 활성화 트리거 입력 이벤트 이후 일시적 활성화 지속 시간 내에 여전히 만료됨), 이를 고려하여 고정 활성화 또는 일시적 활성화 중 어느 것을 기준으로 할지 결정하는 것이 중요합니다.

6.4.2 처리 모델

사용자 상호작용이 document document에서 활성화 트리거 입력 이벤트를 발생시키는 경우, 사용자 에이전트는 이벤트를 디스패치하기 전에 다음 활성화 알림 단계를 수행해야 합니다:

  1. 단언: document완전히 활성화된 상태입니다.

  2. windows를 « document관련 전역 객체 »로 설정합니다.

  3. 확장합니다. windowsdocument의 각 조상 내비게이션 가능활성 창을 추가합니다.

  4. 확장합니다. windowsdocument의 각 후손 내비게이션 가능활성 창을 추가합니다. 단, 이때 포함된 내비게이션 가능활성 문서출처document출처동일 출처인 것들만 필터링하여 포함합니다.

  5. 각각windowwindows에서 다음과 같이 처리합니다:

    1. window마지막 활성화 타임스탬프현재 고해상도 시간으로 설정합니다.

    2. 사용자 활성화에 대해 가까운 감시 관리자에게 알림window에게 제공합니다.

활성화 트리거 입력 이벤트isTrusted 속성이 true이고, 유형이 다음 중 하나인 이벤트입니다:

활성화 소비 API는 이 및 다른 명세에서 정의된 대로 사용자 활성화를 소비할 수 있으며, Window W에 대해 다음 단계를 수행합니다:

  1. W내비게이션 가능이 null인 경우, 종료합니다.

  2. topW내비게이션 가능최상위 내비게이션 가능으로 설정합니다.

  3. navigablestop활성 문서포함된 후손 내비게이션 가능으로 설정합니다.

  4. windowsnavigables의 각 항목에서 활성 창을 가져와 구성된 Window 객체 목록으로 설정합니다.

  5. 각각의 window에 대해, window마지막 활성화 타임스탬프가 양의 무한대가 아닌 경우, window마지막 활성화 타임스탬프를 음의 무한대로 설정합니다.

히스토리 작업 활성화 소비 API히스토리 작업 사용자 활성화를 소비할 수 있으며, Window W에 대해 다음 단계를 수행합니다:

  1. W내비게이션 가능이 null인 경우, 종료합니다.

  2. topW내비게이션 가능최상위 내비게이션 가능으로 설정합니다.

  3. navigablestop활성 문서포함된 후손 내비게이션 가능으로 설정합니다.

  4. windowsnavigables의 각 항목에서 활성 창을 가져와 구성된 Window 객체 목록으로 설정합니다.

  5. 각각의 window에 대해, window마지막 히스토리 작업 활성화 타임스탬프window마지막 활성화 타임스탬프로 설정합니다.

활성화 알림활성화 소비에 의해 영향을 받는 페이지의 탐색 문맥 집합에서 비대칭성을 주의하십시오. 활성화 소비는 페이지의 모든 탐색 문맥에 대한 일시적 활성화 상태를 변경(거짓으로)하지만, 활성화 알림은 그 탐색 문맥의 하위 집합에 대한 상태만을 변경(참으로)합니다. 여기서 소비의 포괄적인 성격은 의도된 것입니다: 이는 악의적인 사이트가 단일 사용자 활성화로부터 여러 호출을 활성화 소비 API로 실행하지 못하도록 방지합니다(아마도 iframe의 깊은 계층 구조를 악용하여).

6.4.3 사용자 활성화로 제한된 API

사용자 활성화에 의존하는 API는 다양한 수준으로 분류됩니다:

지속적 활성화로 제한된 API

이러한 API는 지속적 활성화 상태가 참이어야 하며, 따라서 최초의 사용자 활성화가 있기 전까지는 차단됩니다.

일시적 활성화로 제한된 API

이러한 API는 일시적 활성화 상태가 참이어야 하지만, 이를 소비하지 않으므로, 일시적 상태가 만료될 때까지 사용자 활성화당 여러 번 호출할 수 있습니다.

일시적 활성화 소비 API

이러한 API는 일시적 활성화 상태가 참이어야 하며, 사용자 활성화를 소모하여 사용자 활성화당 여러 번 호출하는 것을 방지합니다.

히스토리 작업 활성화 소비 API

이러한 API는 히스토리 작업 활성화 상태가 참이어야 하며, 사용자 활성화를 소모하여 사용자 활성화당 여러 번 호출하는 것을 방지합니다.

6.4.4 사용자 활성화 인터페이스

UserActivation

Firefox지원 안됨Safari16.4+Chrome72+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Window에는 연관된 UserActivation이 있으며, 이는 UserActivation 객체입니다. Window 객체가 생성될 때, 해당 객체의 연관된 UserActivation새로운 UserActivation 객체로 설정되며, 이는 Window 객체의 관련 영역에서 생성됩니다.

[Exposed=Window]
interface UserActivation {
  readonly attribute boolean hasBeenActive;
  readonly attribute boolean isActive;
};

partial interface Navigator {
  [SameObject] readonly attribute UserActivation userActivation;
};
navigator.userActivation.hasBeenActive

창에 지속적 활성화가 있었는지를 반환합니다.

navigator.userActivation.isActive

창에 일시적 활성화가 있는지를 반환합니다.

Navigator/userActivation

Firefox지원 안됨Safari16.4+Chrome72+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

userActivation의 getter 단계는 this관련 전역 객체연관된 UserActivation을 반환하는 것입니다.

UserActivation/hasBeenActive

Firefox지원 안됨Safari16.4+Chrome72+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

hasBeenActive의 getter 단계는 this관련 전역 객체지속적 활성화가 있는 경우 true를 반환하고, 그렇지 않으면 false를 반환하는 것입니다.

UserActivation/hasBeenActive

Firefox지원 안됨Safari16.4+Chrome72+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

isActive의 getter 단계는 this관련 전역 객체일시적 활성화가 있는 경우 true를 반환하고, 그렇지 않으면 false를 반환하는 것입니다.

6.4.5 사용자 에이전트 자동화

사용자 에이전트 자동화 및 애플리케이션 테스트의 목적을 위해, 이 명세서는 Web Driver 명세에 대한 다음의 확장 명령을 정의합니다. 다음의 확장 명령을 지원하는 것은 사용자 에이전트의 선택 사항입니다. [WEBDRIVER]

HTTP 메서드 URI 템플릿
POST /session/{session id}/window/consume-user-activation

원격 엔드 단계는 다음과 같습니다:

  1. 현재 브라우징 컨텍스트활성 창window로 설정합니다.

  2. window일시적 활성화가 있는 경우 consume을 true로 설정하고, 그렇지 않으면 false로 설정합니다.

  3. consume이 true이면 window사용자 활성화를 소모합니다.

  4. 성공consume 데이터와 함께 반환합니다.

6.5 요소의 활성화 동작

HTML의 특정 요소는 활성화 동작을 가지며, 이는 사용자가 이들을 활성화할 수 있음을 의미합니다. 이는 항상 click 이벤트에 의해 발생합니다.

사용자 에이전트는 사용자가 키보드, 음성 입력 또는 마우스 클릭을 통해 활성화 동작을 가진 요소를 수동으로 트리거할 수 있도록 해야 합니다. 사용자가 클릭 이외의 방법으로 활성화 동작이 정의된 요소를 트리거할 때, 상호작용 이벤트의 기본 동작은 해당 요소에 click 이벤트를 발생시키는 것이어야 합니다.

element.click()

HTMLElement/click

모든 현재 엔진에서 지원됨.

Firefox3+Safari6+Chrome9+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS?Chrome Android?WebView Android4.4+Samsung Internet1.0+Opera Android11+

요소가 클릭된 것처럼 동작합니다.

각 요소는 연관된 클릭 진행 중 플래그를 가지며, 이는 초기에는 설정되지 않습니다.

click() 메서드는 다음 단계를 실행해야 합니다:

  1. 이 요소가 비활성화된 폼 컨트롤인 경우, 반환합니다.

  2. 이 요소의 클릭 진행 중 플래그가 설정된 경우, 반환합니다.

  3. 이 요소의 클릭 진행 중 플래그를 설정합니다.

  4. 신규 포인터 이벤트신뢰할 수 없는 플래그를 설정하여 click이라는 이름으로 이 요소에서 발생시킵니다.

  5. 이 요소의 클릭 진행 중 플래그를 해제합니다.

6.5.1 ToggleEvent 인터페이스

ToggleEvent/ToggleEvent

모든 현재 엔진에서 지원됨.

🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

ToggleEvent

모든 현재 엔진에서 지원됨.

🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=Window]
interface ToggleEvent : Event {
  constructor(DOMString type, optional ToggleEventInit eventInitDict = {});
  readonly attribute DOMString oldState;
  readonly attribute DOMString newState;
};

dictionary ToggleEventInit : EventInit {
  DOMString oldState = "";
  DOMString newState = "";
};
event.oldState

닫힘에서 열림으로 전환될 때 "closed"로 설정되며, 열림에서 닫힘으로 전환될 때 "open"로 설정됩니다.

event.newState

닫힘에서 열림으로 전환될 때 "open"로 설정되며, 열림에서 닫힘으로 전환될 때 "closed"로 설정됩니다.

ToggleEvent/oldState

모든 현재 엔진에서 지원됨.

🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

ToggleEvent/newState

모든 현재 엔진에서 지원됨.

🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

oldStatenewState 속성은 초기화된 값을 반환해야 합니다.

토글 작업 추적기는 다음과 같은 내용을 가진 구조체입니다:

작업
ToggleEvent를 발생시키는 작업.
이전 상태
oldState 속성의 값을 나타내는 문자열.

6.6 포커스

6.6.1 소개

이 섹션은 규범적이지 않습니다.

HTML 사용자 인터페이스는 일반적으로 폼 컨트롤, 스크롤 가능한 영역, 링크, 대화 상자, 브라우저 탭 등 여러 대화형 위젯으로 구성됩니다. 이러한 위젯은 일부(예: 브라우저 탭, 대화 상자)가 다른 위젯(예: 링크, 폼 컨트롤)을 포함하는 계층 구조를 형성합니다.

키보드를 사용하여 인터페이스와 상호작용할 때, 키 입력은 시스템에서 대화형 위젯의 계층 구조를 통해 활성 위젯으로 전달되며, 이를 포커스가 있다고 합니다.

그래픽 환경에서 실행되는 브라우저 탭에서 실행 중인 HTML 애플리케이션을 고려해 보십시오. 이 애플리케이션에 텍스트 컨트롤과 링크가 포함된 페이지가 있고, 현재 모달 대화 상자를 표시하고 있다고 가정해 봅시다. 이 대화 상자 자체는 텍스트 컨트롤과 버튼을 포함하고 있습니다.

이 경우 포커스 가능한 위젯의 계층 구조에는 브라우저 창이 포함되며, 그 자식 요소로 HTML 애플리케이션을 포함하는 브라우저 탭이 있습니다. 탭 자체는 다양한 링크와 텍스트 컨트롤뿐만 아니라 대화 상자를 자식 요소로 포함합니다. 대화 상자 자체는 텍스트 컨트롤과 버튼을 자식 요소로 포함합니다.

이 예에서 대화 상자의 텍스트 컨트롤이 포커스된 위젯이라면, 키 입력은 그래픽 시스템에서 ① 웹 브라우저로, ② 탭으로, ③ 대화 상자로, 마지막으로 ④ 텍스트 컨트롤로 전달됩니다.

키보드 이벤트는 항상 이 포커스된 요소를 대상으로 합니다.

6.6.2 데이터 모델

최상위 탐색 가능 요소는 운영 체제에서 전달된 키보드 입력을 수신할 수 있을 때 시스템 포커스를 가지며, 이는 해당 요소의 활성 문서하위 탐색 가능 요소 중 하나를 대상으로 할 수 있습니다.

최상위 탐색 가능 요소는 그 시스템 가시성 상태가 "visible"이고, 시스템 포커스를 가지고 있거나, 사용자 에이전트 위젯이 운영 체제에서 전달된 키보드 입력을 직접 수신할 수 있을 때 사용자 주의를 가집니다.

브라우저 창이 포커스를 잃으면 사용자 주의가 상실되지만, 시스템 포커스는 브라우저 창의 다른 시스템 위젯(예: 주소 표시줄)으로도 상실될 수 있습니다.

document d사용자 주의가 있는 최상위 탐색 가능 요소의 활성 하위 요소일 때, 즉 d완전히 활성화되어 있고, d노드 탐색 가능 요소최상위 탐색 가능 요소사용자 주의를 가지고 있을 때 그렇습니다.

포커스 가능한 영역이라는 용어는 인터페이스의 영역 중 키보드 입력의 대상이 될 수 있는 영역을 가리킬 때 사용됩니다. 포커스 가능한 영역은 요소, 요소의 일부, 또는 사용자 에이전트에 의해 관리되는 다른 영역일 수 있습니다.

포커스 가능한 영역DOM 앵커를 가지며, 이는 노드 객체로, DOM 내에서 포커스 가능한 영역의 위치를 나타냅니다. (해당 포커스 가능한 영역이 자체적으로 노드일 경우, 해당 영역이 스스로의 DOM 앵커입니다.) DOM 앵커는 다른 DOM 객체가 포커스 가능한 영역을 나타내지 않을 때, 일부 API에서 포커스 가능한 영역의 대체물로 사용됩니다.

다음 표는 어떤 객체가 포커스 가능한 영역이 될 수 있는지를 설명합니다. 왼쪽 열의 셀은 포커스 가능한 영역이 될 수 있는 객체를 설명하고, 오른쪽 열의 셀은 해당 요소의 DOM 앵커를 설명합니다. (양쪽 열에 걸쳐 있는 셀은 규범적이지 않은 예시입니다.)

포커스 가능한 영역 DOM 앵커
예시
다음 기준을 모두 충족하는 요소: 해당 요소 자체.

iframe, dialog, <input type=text>, 경우에 따라 <a href=""> (플랫폼 관행에 따라 다름).

area 요소가 이미지 맵에서 생성한 도형으로, 해당 img 요소가 렌더링 중이고 비활성화되지 않은 경우. 해당 img 요소.

다음 예에서는 area 요소가 각각의 이미지에 두 개의 도형을 생성합니다. 첫 번째 도형의 DOM 앵커는 첫 번째 img 요소이며, 두 번째 도형의 DOM 앵커는 두 번째 img 요소입니다.

<map id=wallmap><area alt="Enter Door" coords="10,10,100,200" href="door.html"></map>
...
<img src="images/innerwall.jpeg" alt="There is a white wall here, with a door." usemap="#wallmap">
...
<img src="images/outerwall.jpeg" alt="There is a red wall here, with a door." usemap="#wallmap">
렌더링 중이고 비활성화되지 않았으며, 비활성화되지 않은 요소의 사용자 에이전트가 제공하는 하위 위젯들. 해당 포커스 가능한 영역이 하위 위젯인 요소.

사용자 인터페이스에 노출되는 비디오 요소의 컨트롤, <input type=number> 스핀 컨트롤의 위아래 버튼, details 요소의 렌더링 부분이 있으며, 이를 통해 키보드 입력을 사용하여 요소를 열거나 닫을 수 있습니다.

렌더링 중이며 비활성화되지 않은 요소의 스크롤 가능한 영역. 스크롤 가능한 영역의 상자를 생성한 요소.

CSS 'overflow' 속성의 'scroll' 값은 일반적으로 스크롤 가능한 영역을 생성합니다.

비활성화되지 않은 상태에서 비 null 탐색 컨텍스트를 가진 document뷰포트. 해당 뷰포트가 생성된 document.

iframe의 콘텐츠.

사용자 에이전트에 의해 포커스 가능한 영역으로 판단되는 다른 모든 요소 또는 요소의 일부, 특히 접근성을 높이거나 플랫폼 관행에 더 잘 맞추기 위해. 해당 요소.

사용자 에이전트는 사용자가 목록을 더 쉽게 탐색할 수 있도록 모든 목록 항목의 불릿을 순차적으로 포커스 가능하도록 만들 수 있습니다.

마찬가지로, 사용자 에이전트는 title 속성을 가진 모든 요소를 순차적으로 포커스 가능하도록 만들어 해당 요소의 조언 정보를 액세스할 수 있게 할 수 있습니다.

탐색 가능한 컨테이너(예: iframe)는 포커스 가능한 영역이지만, 탐색 가능한 컨테이너로 라우팅된 키 이벤트는 즉시 콘텐츠 탐색 가능 요소활성 문서로 라우팅됩니다. 마찬가지로, 순차적인 포커스 탐색에서는 탐색 가능한 컨테이너콘텐츠 탐색 가능 요소활성 문서의 자리 표시자 역할을 합니다.


document에는 하나의 포커스 가능한 영역문서의 포커스된 영역으로 지정됩니다. 이러한 제어는 이 명세서에 정의된 알고리즘에 따라 시간이 지남에 따라 변경됩니다.

문서가 완전히 활성화되지 않고 사용자에게 표시되지 않더라도 여전히 문서의 포커스된 영역을 가질 수 있습니다. 문서의 완전히 활성화 상태가 변경되더라도, 그 문서의 포커스된 영역은 그대로 유지됩니다.

traversable현재 포커스된 최상위 탐색 가능 영역은 다음 알고리즘에 의해 반환되는 포커스 가능한 영역 또는 null입니다:

  1. traversable시스템 포커스를 가지지 않는 경우, null을 반환합니다.

  2. candidatetraversable활성 문서로 설정합니다.

  3. candidate포커스된 영역이 비 null 콘텐츠 탐색 가능 요소를 가진 탐색 가능 컨테이너인 동안: candidate를 해당 탐색 가능 컨테이너콘텐츠 탐색 가능 요소활성 문서로 설정합니다.

  4. candidate포커스된 영역이 비 null인 경우, candidatecandidate포커스된 영역으로 설정합니다.

  5. candidate를 반환합니다.

traversable현재 포커스 체인traversable이 null이 아닌 경우 현재 포커스된 영역포커스 체인이며, 그렇지 않으면 빈 목록입니다.

포커스 가능한 영역DOM 앵커인 요소는 해당 포커스 가능한 영역현재 포커스된 최상위 탐색 가능 영역이 될 때 포커스를 얻는다고 합니다. 요소가 DOM 앵커포커스 가능한 영역현재 포커스된 최상위 탐색 가능 영역인 경우, 해당 요소는 포커스된 상태입니다.

subject포커스 가능한 영역포커스 체인은 다음과 같이 구성된 순서 목록입니다:

  1. output을 빈 목록으로 설정합니다.

  2. currentObjectsubject로 설정합니다.

  3. 다음이 참일 동안:

    1. 현재 객체output에 추가합니다.

    2. currentObjectarea 요소의 도형인 경우, 해당 요소를 output에 추가합니다.

      그렇지 않은 경우, currentObjectDOM 앵커currentObject 자신이 아닌 요소인 경우, 요소를 output에 추가합니다.

    3. currentObject포커스 가능한 영역인 경우, currentObjectDOM 앵커노드 문서로 설정합니다.

      그렇지 않은 경우, currentObject노드 탐색 가능 요소부모가 null이 아닌 document인 경우, currentObject노드 탐색 가능 요소부모로 설정합니다.

      그렇지 않으면 중단합니다.

  4. output을 반환합니다.

    이 체인은 subject로 시작하여(만약 subject가 최상위 탐색 가능 영역의 현재 포커스된 영역이거나 될 수 있는 경우) 포커스 계층 구조를 따라 document의 최상위 탐색 가능 영역으로 계속됩니다.

모든 포커스 가능한 영역포커스 가능하다고 합니다.

포커스 가능한 영역에는 두 가지 특별한 유형의 포커스 가능성이 있습니다:

포커스 가능하지 않은 요소는 포커스 가능한 영역이 아니므로, 순차적으로 포커스 가능하지도 않고, 클릭 포커스 가능하지도 않습니다.

포커스 가능 여부는 focus() 메서드나 autofocus 속성 등과 같은 프로그래밍 방식으로 요소가 포커스될 수 있는지 여부를 나타내는 것입니다. 이에 반해, 순차적으로 포커스 가능 여부와 클릭 포커스 가능 여부는 사용자 에이전트가 사용자 상호작용에 어떻게 반응하는지를 결정합니다: 각각 순차 포커스 탐색활성화 동작에 따라 반응합니다.

사용자 에이전트는 요소가 포커스 가능하고, document순차 포커스 탐색 순서에 포함되어 있더라도 사용자 환경설정에 따라 해당 요소를 순차적으로 포커스 가능하지 않다고 판단할 수 있습니다. 예를 들어, macOS 사용자는 비 폼 제어 요소를 건너뛰도록 사용자 에이전트를 설정할 수 있으며, Tab 키만을 사용하여 순차 포커스 탐색을 할 때 링크를 건너뛸 수 있습니다(예: OptionTab 키를 모두 사용하지 않는 경우).

마찬가지로, 사용자 에이전트는 요소가 포커스 가능하더라도 클릭 포커스 가능하지 않다고 판단할 수 있습니다. 예를 들어, 일부 사용자 에이전트에서는 비 편집 가능한 폼 제어 요소를 클릭해도 해당 요소에 포커스가 설정되지 않습니다. 즉, 사용자 에이전트는 이러한 제어 요소가 클릭 포커스 가능하지 않다고 판단한 것입니다.

따라서 요소는 포커스 가능하지만, 순차적으로 포커스 가능하지도 않고, 클릭 포커스 가능하지도 않을 수 있습니다. 예를 들어, 일부 사용자 에이전트에서는 음수 정수 탭 인덱스 값을 가진 비 편집 가능한 폼 제어 요소는 사용자 상호작용을 통해서는 포커스할 수 없고, 오직 프로그래밍 방식의 API를 통해서만 포커스할 수 있습니다.

사용자가 활성화할 때 클릭 포커스 가능 포커스 가능한 영역을 선택하면, 사용자 에이전트는 포커스 트리거를 "클릭"으로 설정하여 포커스 설정 단계를 실행해야 합니다.

포커스 설정은 활성화 동작이 아닙니다. 즉, 요소에서 click() 메서드를 호출하거나 합성 click 이벤트를 디스패치해도 해당 요소에 포커스가 설정되지 않습니다.


노드는 포커스 탐색 범위 소유자입니다. 이는 document, 섀도우 호스트, 슬롯 또는 팝오버 표시 상태에서 팝오버 호출자가 설정된 요소입니다.

포커스 탐색 범위 소유자포커스 탐색 범위를 가지며, 이는 요소 목록입니다. 그 내용은 다음과 같이 결정됩니다:

모든 요소 element연관된 포커스 탐색 소유자를 가지며, 이는 null이거나 포커스 탐색 범위 소유자입니다. 다음 알고리즘에 의해 결정됩니다:

  1. element의 부모가 null이면 null을 반환합니다.

  2. element의 부모가 섀도우 호스트라면, element할당된 슬롯을 반환합니다.

  3. element의 부모가 섀도우 루트라면, 부모의 호스트를 반환합니다.

  4. element의 부모가 문서 요소라면, 부모의 노드 문서를 반환합니다.

  5. element팝오버 표시 상태에 있으며 팝오버 호출자가 설정되어 있으면, element를 반환합니다.

  6. element의 부모의 연관된 포커스 탐색 소유자를 반환합니다.

그러면, 주어진 포커스 탐색 범위 소유자 owner포커스 탐색 범위의 내용은 연관된 포커스 탐색 소유자owner인 모든 요소가 됩니다.

포커스 탐색 범위 내 요소의 순서는 이 명세서의 알고리즘에 영향을 미치지 않습니다. 순서는 아래에 정의된 탭 인덱스 순서 포커스 탐색 범위평면화된 탭 인덱스 순서 포커스 탐색 범위 개념에 대해서만 중요합니다.

탭 인덱스 순서 포커스 탐색 범위포커스 가능한 영역포커스 탐색 범위 소유자 목록입니다. 모든 포커스 탐색 범위 소유자 owner탭 인덱스 순서 포커스 탐색 범위를 가지며, 그 내용은 다음과 같이 결정됩니다:

탭 인덱스 순서 포커스 탐색 범위 내의 순서는 각 요소의 탭 인덱스 값에 의해 결정됩니다. 아래 섹션에서 설명된 대로입니다.

여기에서의 규칙은 "권장" 문구와 상대적 순서로 구성되어 있기 때문에 정확한 순서를 제공하지 않습니다.

평면화된 탭 인덱스 순서 포커스 탐색 범위포커스 가능한 영역 목록입니다. 모든 포커스 탐색 범위 소유자 owner는 고유한 평면화된 탭 인덱스 순서 포커스 탐색 범위를 가지며, 그 내용은 다음 알고리즘에 의해 결정됩니다:

  1. resultowner탭 인덱스 순서 포커스 탐색 범위복제본으로 설정합니다.

  2. result의 각 item에 대해:

    1. item포커스 탐색 범위 소유자가 아닌 경우, 계속 진행합니다.

    2. item포커스 가능한 영역이 아닌 경우, itemitem평면화된 탭 인덱스 순서 포커스 탐색 범위 내의 모든 항목으로 대체합니다.

    3. 그 외의 경우, item평면화된 탭 인덱스 순서 포커스 탐색 범위의 내용을 item 이후에 삽입합니다.

6.6.3 tabindex 속성

Global_attributes/tabindex

모든 현재 엔진에서 지원됨.

Firefox1.5+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

tabindex 콘텐츠 속성은 작성자가 요소 및 해당 요소를 DOM 앵커로 하는 영역을 포커스 가능 영역으로 만들거나, 해당 영역이 순차적으로 포커스 가능하게 하거나, 순차 포커스 내비게이션 을 위해 상대적인 순서를 결정할 수 있도록 합니다.

"tab index"라는 이름은 포커스 가능한 요소를 탐색하기 위해 일반적으로 Tab 키를 사용하는 것에서 유래되었습니다. "탭핑"이라는 용어는 순차적으로 포커스 가능한 포커스 가능 영역을 통해 앞으로 이동하는 것을 나타냅니다.

tabindex 속성이 지정된 경우, 반드시 유효한 정수 값을 가져야 합니다. 양의 숫자는 포커스 가능 영역의 상대적인 위치를 지정하며, 음수는 해당 컨트롤이 순차적으로 포커스 가능하지 않음을 나타냅니다.

개발자는 tabindex 속성에 0 또는 −1이 아닌 값을 사용하는 경우 주의해야 합니다. 올바르게 사용하기가 복잡하기 때문입니다.

다음은 가능한 tabindex 속성 값의 동작에 대한 비규범적 요약입니다. 아래의 처리 모델에서는 더 정확한 규칙을 제공합니다.

생략됨 (또는 비정수 값)
사용자 에이전트는 요소가 포커스 가능한지 여부를 결정하며, 포커스 가능하다면 순차적으로 포커스 가능한지 아니면 클릭 포커스 가능한지 (또는 둘 다) 여부를 결정합니다.
−1 (또는 다른 음수 값)
요소를 포커스 가능하게 하며, 작성자는 해당 요소가 클릭 포커스 가능하지만 순차적으로 포커스 가능하지 않기를 원한다고 표시합니다. 그러나 사용자 에이전트는 플랫폼 관례에 따라 특정 요소 유형에 대해 키보드 전용 사용자 등을 위해 이 선호를 무시할 수 있습니다.
0
요소를 포커스 가능하게 하며, 작성자는 해당 요소가 클릭 포커스 가능하고 순차적으로 포커스 가능하기를 원한다고 표시합니다. 사용자 에이전트는 클릭 및 순차적 포커스 가능성에 대한 이 선호를 무시할 수 있습니다.
양의 정수 값
0과 동일하게 동작하지만, 추가로 tabindex-순서가 지정된 포커스 내비게이션 범위 내에서 상대적인 순서를 생성하여 tabindex 속성 값이 더 높은 요소가 나중에 나옵니다.

tabindex 속성을 사용하여 요소를 포커스 불가능하게 만들 수 없습니다. 페이지 작성자가 이를 수행하는 유일한 방법은 요소를 비활성화하거나, 비활성화하는 것입니다.


tabindex 값tabindex 속성의 값이며, 정수 파싱 규칙을 사용하여 파싱됩니다. 파싱에 실패하거나 속성이 지정되지 않은 경우, tabindex 값은 null입니다.

tabindex 값포커스 가능 영역tabindex 값이며, 해당 영역의 DOM 앵커에 해당합니다.

요소의 tabindex 값은 다음과 같이 해석되어야 합니다:

값이 null인 경우

사용자 에이전트는 플랫폼 규칙에 따라 해당 요소가 포커스 가능 영역으로 간주되어야 하는지 여부를 결정해야 하며, 그럴 경우 요소 및 해당 요소를 포커스 가능 영역으로 가지는 영역이 순차적으로 포커스 가능한지, 그리고 그렇다면, 해당 영역이 tabindex-순서가 지정된 포커스 내비게이션 범위 내에서 어떤 상대적 위치를 가질지를 결정해야 합니다. 해당 요소가 포커스 내비게이션 범위 소유자라면, tabindex-순서가 지정된 포커스 내비게이션 범위에 포함되어야 하며, 비록 포커스 가능 영역이 아니더라도 포함되어야 합니다.

동일한 포커스 내비게이션 범위에 속하는 요소 및 포커스 가능 영역tabindex 값이 null인 경우, 해당 요소들의 shadow-including tree order에 따라 상대적 순서가 정해져야 합니다.

플랫폼 규칙에 따라, 다음 요소들은 포커스 가능 영역으로 간주되며, 순차적으로 포커스 가능하다고 제안됩니다:

값이 음수인 경우

사용자 에이전트는 해당 요소를 포커스 가능 영역으로 간주해야 하지만, 해당 요소를 tabindex-순서가 지정된 포커스 내비게이션 범위에서 제외해야 합니다.

순차적인 포커스 내비게이션이 해당 요소로 이동할 수 없도록 하는 요구 사항을 무시할 수 있는 한 가지 유효한 이유는 사용자가 순차적인 포커스 내비게이션만을 통해 포커스를 이동할 수 있는 경우일 수 있습니다. 예를 들어, 키보드 전용 사용자는 음수 tabindex 값을 가진 텍스트 컨트롤을 클릭할 수 없으므로, 그 사용자의 사용자 에이전트가 사용자가 해당 컨트롤에 탭할 수 있도록 허용하는 것이 타당할 수 있습니다.

값이 0인 경우

사용자 에이전트는 해당 요소를 포커스 가능 영역으로 간주할 수 있어야 하며, 해당 요소 및 해당 요소를 포커스 가능 영역으로 가지는 영역을 DOM 앵커로 하여 순차적으로 포커스 가능하도록 허용해야 합니다.

동일한 포커스 내비게이션 범위에 속하는 요소 및 포커스 가능 영역tabindex 값이 0인 경우, shadow-including tree order에 따라 상대적 순서가 정해져야 합니다.

값이 0보다 큰 경우

사용자 에이전트는 해당 요소를 포커스 가능 영역으로 간주할 수 있어야 하며, 해당 요소 및 해당 요소를 포커스 가능 영역으로 가지는 영역을 DOM 앵커로 하여 순차적으로 포커스 가능하도록 허용해야 하며, 아래에서 후보라고 참조된 요소 및 앞서 언급한 포커스 가능 영역을 다음과 같이 tabindex-순서가 지정된 포커스 내비게이션 범위 내에서 위치시켜야 합니다. 이 요소가 속한 포커스 내비게이션 범위 내에서 다른 요소 및 포커스 가능 영역에 대해 상대적으로:

HTMLElement/tabIndex

모든 현재 엔진에서 지원됨.

Firefox1+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)18🔰 5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

tabIndex IDL 속성은 반영해야 하며, tabindex 콘텐츠 속성의 값을 반영해야 합니다. 기본 값은 0입니다. 요소가 a, area, button, frame, iframe, input, object, select, textarea, 또는 SVG a 요소이거나, summary 요소로서 상세한 내용을 위한 요약인 경우입니다. 그렇지 않은 경우 기본 값은 −1입니다.

요소 유형에 따른 기본 값의 차이는 역사적 산물입니다.

6.6.4 처리 모델

포커스 대상포커스 가능 영역이 아닌 요소이거나, 내비게이션 가능한 요소일 때, 선택적 문자열 포커스 트리거(기본값 "기타")와 함께 포커스 가능 영역을 가져오는 첫 번째 일치하는 단계들을 실행하십시오:

포커스 대상이 하나 이상의 포커스 가능 영역을 가진 area 요소인 경우

area 요소가 속한 이미지 맵을 사용하는 첫 번째 img 요소에 해당하는 도형을 반환합니다. 트리 순서에서

포커스 대상이 하나 이상의 포커스 가능 영역을 가진 스크롤 가능한 영역이 있는 요소인 경우

요소의 첫 번째 스크롤 가능한 영역을 반환합니다. 플랫 트리의 전위, 깊이 우선 순회를 따라. [CSSSCOPING]

포커스 대상Document문서 요소인 경우

Document뷰포트를 반환합니다.

포커스 대상내비게이션 가능한 요소인 경우

활성 문서를 반환합니다.

포커스 대상내비게이션 가능한 컨테이너이고, null이 아닌 콘텐츠 내비게이션 가능한 경우

내비게이션 가능한 컨테이너의 콘텐츠 내비게이션 가능활성 문서를 반환합니다.

포커스 대상섀도우 호스트이며, 섀도우 루트포커스 위임이 true인 경우
  1. focusedElement상위 레벨 탐색 가능 영역의 현재 포커스된 영역DOM 앵커로 설정합니다.

  2. 포커스 대상focusedElement섀도우를 포함한 포함 조상인 경우, focusedElement를 반환합니다.

  3. 포커스 대상에 대해 포커스 트리거가 주어졌을 때, 포커스 대리자를 반환합니다.

순차적으로 포커스 가능에 대한 처리는 섀도우 호스트포커스 위임이 포함된 경우, 순차 포커스 내비게이션 순서를 구성할 때 처리됩니다. 즉, 포커스 단계는 순차적 포커스 내비게이션의 일부로 섀도우 호스트에서 호출되지 않습니다.

그 외의 경우

null을 반환합니다.

포커스 대상에 대해 선택적 문자열 포커스 트리거(기본값 "기타")가 주어진 포커스 대리자는 다음 단계에 의해 주어집니다:

  1. 포커스 대상섀도우 호스트이고, 그 섀도우 루트포커스 위임이 false인 경우, null을 반환합니다.

  2. whereToLook포커스 대상으로 설정합니다.

  3. whereToLook섀도우 호스트인 경우, whereToLookwhereToLook섀도우 루트로 설정합니다.

  4. autofocusDelegatefocusTrigger를 고려한 whereToLook에 대한 자동 포커스 대리자로 설정합니다.

  5. autofocusDelegate가 null이 아닌 경우, autofocusDelegate를 반환합니다.

  6. whereToLook하위 요소에 대해 트리 순서로:

    1. focusableArea을 null로 설정합니다.

    2. 포커스 대상dialog 요소이고 descendant순차적으로 포커스 가능한 경우, focusableAreadescendant로 설정합니다.

    3. 그렇지 않고, 포커스 대상dialog가 아니며 descendant포커스 가능 영역인 경우, focusableAreadescendant로 설정합니다.

    4. 그렇지 않은 경우, focusTrigger가 주어진 descendant에 대한 포커스 가능 영역을 가져오는 결과로 focusableArea을 설정합니다.

      이 단계는 재귀적으로 수행될 수 있습니다. 즉, 포커스 가능 영역을 가져오는 단계가 descendant포커스 대리자를 반환할 수 있습니다.

    5. focusableArea가 null이 아닌 경우, focusableArea을 반환합니다.

    여기서는 섀도우를 포함한 하위 요소를 고려하지 않고, 하위 요소만을 고려하고 있다는 점이 중요합니다. 섀도우 호스트는 위에서 언급한 재귀적인 경우에 처리됩니다.

  7. null을 반환합니다.

위 알고리즘은 기본적으로 포커스 대상DOM 앵커포커스 가능 영역 간의 경로가 섀도우 트리 경계에서 포커스를 위임하는 첫 번째 적절한 포커스 가능 영역을 반환합니다.

자동 포커스 대리자focus target과 주어진 focus trigger에 따라 다음 단계로 결정됩니다:

  1. focus target하위 요소 각각에 대해 트리 순서로:

    1. 만약 descendantautofocus 콘텐츠 속성을 가지고 있지 않다면, 계속 진행합니다.

    2. 만약 descendant포커스 가능 영역이라면, focusable areadescendant로 설정하고, 그렇지 않으면 focus trigger를 고려하여 descendant에 대한 포커스 가능 영역을 가져오는 결과로 설정합니다.

    3. 만약 focusable area가 null이라면, 계속 진행합니다.

    4. 만약 focusable area클릭 포커스 가능이 아니고, focus trigger가 "click"이라면, 계속 진행합니다.

    5. focusable area를 반환합니다.

  2. null을 반환합니다.

포커스 단계new focus target포커스 가능 영역이거나, 포커스 가능 영역이 아닌 요소 또는 내비게이션 가능 요소인 경우에 따라 실행됩니다. 이들은 선택적으로 fallback target과 문자열 focus trigger와 함께 실행될 수 있습니다.

  1. 만약 new focus target포커스 가능 영역이 아니라면, focus trigger가 전달된 경우를 고려하여 new focus target에 대해 포커스 가능 영역을 가져오는 결과로 설정합니다.

  2. 만약 new focus target이 null이라면:

    1. 만약 fallback target이 지정되지 않았다면, 반환합니다.

    2. 그렇지 않으면, new focus targetfallback target으로 설정합니다.

  3. 만약 new focus target이 null이 아닌 내비게이션 가능한 컨테이너이고, 콘텐츠 내비게이션 가능이 null이 아닌 경우, new focus target콘텐츠 내비게이션 가능활성 문서로 설정합니다.

  4. 만약 new focus target포커스 가능 영역이고, 그 DOM 앵커비활성화된 경우, 반환합니다.

  5. 만약 new focus target상위 레벨 탐색 가능의 현재 포커스된 영역인 경우, 반환합니다.

  6. old chainnew focus target이 속한 상위 레벨 탐색 가능의 현재 포커스 체인으로 설정합니다.

  7. new chainnew focus target포커스 체인으로 설정합니다.

  8. old chain, new chain, 그리고 new focus target을 사용하여 포커스 업데이트 단계를 실행합니다.

사용자 에이전트는 사용자가 candidate에 포커스를 이동하려고 할 때마다 candidate에 대해 포커스 가능 영역 또는 내비게이션 가능에 대한 포커스 단계즉시 실행해야 합니다.

포커스 해제 단계old focus target포커스 가능 영역이거나 포커스 가능 영역이 아닌 요소일 때 다음과 같이 실행됩니다:

  1. 만약 old focus target섀도우 호스트이고, 그 섀도우 루트포커스 위임이 true이며, old focus target섀도우 루트섀도우를 포함한 포함 조상인 경우, old focus target을 해당 상위 레벨 탐색 가능의 현재 포커스된 영역으로 설정합니다.

  2. 만약 old focus target비활성화된 경우, 반환합니다.

  3. 만약 old focus targetarea 요소이고, 해당 도형 중 하나가 상위 레벨 탐색 가능의 현재 포커스된 영역인 경우, 또는 old focus target이 하나 이상의 스크롤 가능한 영역을 가진 요소이고, 그 중 하나가 상위 레벨 탐색 가능의 현재 포커스된 영역인 경우, old focus target을 해당 상위 레벨 탐색 가능의 현재 포커스된 영역으로 설정합니다.

  4. old chainold focus target이 속한 상위 레벨 탐색 가능의 현재 포커스 체인으로 설정합니다.

  5. 만약 old focus targetold chain의 항목 중 하나가 아니라면, 반환합니다.

  6. 만약 old focus target포커스 가능 영역이 아니라면, 반환합니다.

  7. topDocumentold chain의 마지막 항목으로 설정합니다.

  8. 만약 topDocument노드 네비게이블시스템 포커스가 있다면, topDocument뷰포트에 대해 포커싱 단계를 실행하세요.

    그렇지 않으면, topDocument탐색 가능한 노드에서 시스템 포커스를 제거하기 위해 관련된 플랫폼별 규칙을 적용하고, old chain, 빈 목록, 그리고 null을 사용하여 포커스 업데이트 단계를 실행합니다.

포커스 해제 단계는 항상 포커스가 변경되는 결과를 초래하지는 않습니다. 예를 들어, 상위 레벨 탐색 가능의 현재 포커스된 영역뷰포트인 경우, 다른 포커스 가능 영역이 명시적으로 포커스 단계에 의해 포커스되지 않는 한, 포커스를 유지하게 됩니다.


포커스 업데이트 단계old chain, new chain, 그리고 new focus target이 각각 주어졌을 때 다음과 같이 실행됩니다:

  1. 만약 old chain의 마지막 항목과 new chain의 마지막 항목이 동일하다면, old chainnew chain에서 마지막 항목을 제거하고 이 단계를 다시 실행합니다.

  2. old chain의 각 항목 entry에 대해 순서대로 다음 하위 단계를 실행합니다:

    1. 만약 entryinput 요소이고, change 이벤트가 해당 요소에 적용되며, 요소에 활성화 동작이 정의되어 있지 않고, 사용자가 해당 요소의 또는 선택된 파일 목록을 변경했지만 그 변경 사항을 커밋하지 않은 경우:

      1. entry사용자 유효성을 true로 설정합니다.

      2. 해당 요소에서 change라는 이름의 이벤트를 발생시키고, bubbles 속성을 true로 초기화합니다.

    2. 만약 entry가 요소인 경우, blur event targetentry로 설정합니다.

      만약 entryDocument 객체인 경우, blur event target을 해당 Document 객체의 관련 글로벌 객체로 설정합니다.

      그 외의 경우, blur event target을 null로 설정합니다.

    3. 만약 entryold chain의 마지막 항목이고, entryElement인 경우, 그리고 new chain의 마지막 항목도 Element인 경우, related blur targetnew chain의 마지막 항목으로 설정합니다. 그렇지 않으면, related blur target을 null로 설정합니다.

    4. 만약 blur event target이 null이 아닌 경우, related blur target을 관련 타겟으로 설정하여 blur event target에서 blur라는 이름의 포커스 이벤트를 발생시킵니다.

      일부 경우에는 entryarea 요소의 도형이거나, 스크롤 가능한 영역이거나, 뷰포트일 경우 이벤트가 발생하지 않습니다.

  3. new focus target에 포커스를 맞추기 위한 관련 플랫폼별 규칙을 적용합니다. (예를 들어, 일부 플랫폼은 텍스트 컨트롤이 포커스될 때 텍스트 컨트롤의 내용을 선택할 수 있습니다.)

  4. new chain의 각 항목 entry에 대해 역순으로 다음 하위 단계를 실행합니다:

    1. 만약 entry포커스 가능 영역이고, 문서의 포커스된 영역entry가 아닌 경우:

      1. document관련 글로벌 객체네비게이션 API진행 중인 네비게이션 중 포커스 변경을 true로 설정합니다.

      2. entry문서의 포커스된 영역으로 지정합니다.

    2. 만약 entry가 요소인 경우, focus event targetentry로 설정합니다.

      만약 entryDocument 객체인 경우, focus event target을 해당 Document 객체의 관련 글로벌 객체로 설정합니다.

      그 외의 경우, focus event target을 null로 설정합니다.

    3. 만약 entrynew chain의 마지막 항목이고, entryElement인 경우, 그리고 old chain의 마지막 항목도 Element인 경우, related focus targetold chain의 마지막 항목으로 설정합니다. 그렇지 않으면, related focus target을 null로 설정합니다.

    4. 만약 focus event target이 null이 아닌 경우, related focus target을 관련 타겟으로 설정하여 focus event target에서 focus라는 이름의 포커스 이벤트를 발생시킵니다.

      일부 경우, 예를 들어 entryarea 요소의 도형이거나, 스크롤 가능한 영역이거나, 뷰포트인 경우, 이벤트가 발생하지 않습니다.

포커스 이벤트 발생e라는 이름의 이벤트를 t라는 요소에서, 주어진 관련 타겟 r을 가지고 발생시킵니다. 이때, FocusEvent를 사용하며, relatedTarget 속성은 r로 초기화되고, view 속성은 t노드 문서관련 글로벌 객체로 초기화되며, 합성 플래그가 설정됩니다.


키 이벤트가 상위 레벨 탐색 가능에서 라우팅될 때, 사용자 에이전트는 다음 단계를 실행해야 합니다:

  1. target area상위 레벨 탐색 가능의 현재 포커스된 영역으로 설정합니다.

  2. 단언: target area는 null이 아닙니다. 키 이벤트는 시스템 포커스를 가진 상위 레벨 탐색 가능에만 라우팅되기 때문에, target area포커스 가능 영역입니다.

  3. target nodetarget areaDOM 앵커로 설정합니다.

  4. 만약 target nodeDocument이고 body 요소를 가지고 있다면, target node를 해당 Documentbody 요소로 설정합니다.

    그렇지 않고, 만약 target node가 비어 있지 않은 문서 요소를 가진 Document 객체라면, target node를 해당 문서 요소로 설정합니다.

  5. 만약 target node비활성화되지 않았다면:

    1. canHandletarget node에서 키 이벤트를 디스패치한 결과로 설정합니다.

    2. 만약 canHandle이 true라면, target area가 키 이벤트를 처리하도록 합니다. 여기에는 target node에서 클릭 이벤트 발생이 포함될 수 있습니다.


포커스 보유 단계target이라는 Document 객체에 대해 다음과 같이 실행됩니다:

  1. 만약 target탐색 가능한 노드상위 레벨 탐색 가능시스템 포커스를 가지고 있지 않다면, false를 반환합니다.

  2. candidatetarget탐색 가능한 노드상위 레벨 탐색 가능활성 문서로 설정합니다.

  3. 다음이 true일 때까지 반복합니다:

    1. 만약 candidatetarget이라면, true를 반환합니다.

    2. 만약 candidate문서의 포커스된 영역이 비어 있지 않은 내비게이션 가능한 컨테이너이고, 비어 있지 않은 콘텐츠 내비게이션 가능을 가지고 있다면, candidate를 해당 내비게이션 가능한 컨테이너콘텐츠 내비게이션 가능활성 문서로 설정합니다.

    3. 그렇지 않으면, false를 반환합니다.

6.6.5 순차 포커스 탐색

document에는 순차 포커스 탐색 순서가 있으며, 이는 document 내의 일부 또는 모든 포커스 가능 영역을 상대적으로 정렬합니다. 그 내용과 순서는 document평탄화된 tabindex-순서 탐색 범위에 의해 결정됩니다.

평탄화된 tabindex-순서 탐색 범위를 정의하는 규칙에 따라, 이 순서는 document트리 순서와 반드시 관련이 있는 것은 아닙니다.

만약 포커스 가능 영역이 그 document순차 포커스 탐색 순서에서 제외된다면, 이는 순차 포커스 탐색을 통해 접근할 수 없습니다.

순차 포커스 탐색 시작점도 있을 수 있습니다. 이는 처음에는 설정되지 않으며, 사용자가 이동해야 한다고 표시할 때 사용자 에이전트가 이를 설정할 수 있습니다.

예를 들어, 사용자가 문서 내용을 클릭하면 사용자 에이전트는 사용자의 클릭 위치로 이를 설정할 수 있습니다.

사용자가 프래그먼트로 탐색할 때, 사용자 에이전트는 순차 포커스 탐색 시작점타겟 요소에 설정해야 합니다.

사용자가 상위 레벨 탐색 가능한 현재 포커스된 영역에서 다음 또는 이전 포커스 가능 영역으로 포커스를 이동하도록 요청하거나(예: tab 키를 누르는 기본 동작으로) 사용자가 처음으로 상위 레벨 탐색 가능으로 포커스를 순차적으로 이동하도록 요청한 경우(예: 브라우저의 주소 표시줄에서), 사용자 에이전트는 다음 알고리즘을 사용해야 합니다:

  1. 만약 사용자가 그곳에서 포커스를 순차적으로 이동하도록 요청했다면, starting point상위 레벨 탐색 가능한 현재 포커스된 영역으로 설정하고, 그렇지 않으면 사용자가 대신 상위 레벨 탐색 가능 외부에서 포커스를 이동하도록 요청한 경우 상위 레벨 탐색 가능 자체로 설정합니다.

  2. 정의된 순차 포커스 탐색 시작점starting point 내부에 있으면, starting point를 대신 순차 포커스 탐색 시작점으로 설정합니다.

  3. 사용자가 다음 컨트롤을 요청한 경우 directionforward로, 이전 컨트롤을 요청한 경우 backward로 설정합니다.

    일반적으로 tab 키를 누르면 다음 컨트롤을 요청하고, shift + tab을 누르면 이전 컨트롤을 요청합니다.

  4. 반복: starting point탐색 가능이거나, starting point가 그 document순차 포커스 탐색 순서에 있으면 selection mechanismsequential로 설정합니다.

    그렇지 않으면, starting point가 그 document순차 포커스 탐색 순서에 없으므로 selection mechanismDOM으로 설정합니다.

  5. candidatestarting point, direction, selection mechanism을 인수로 하여 순차 탐색 검색 알고리즘을 실행한 결과로 설정합니다.

  6. candidate가 null이 아니면 candidate에 대해 포커싱 단계를 실행하고 종료합니다.

  7. 그렇지 않으면 순차 포커스 탐색 시작점을 설정 해제합니다.

  8. starting point상위 레벨 탐색 가능이거나 상위 레벨 탐색 가능 내의 포커스 가능 영역이면, 사용자 에이전트는 적절하게 자신의 컨트롤로 포커스를 옮기고(direction을 존중하며) 종료해야 합니다.

    예를 들어, directionbackward인 경우 브라우저의 렌더링 영역 이전의 마지막 순차적으로 포커스 가능한 컨트롤이 포커스할 컨트롤입니다.

    만약 사용자 에이전트가 순차적으로 포커스 가능한 컨트롤이 없는 경우 — 예를 들어, 키오스크 모드 브라우저 — 사용자 에이전트는 starting point상위 레벨 탐색 가능 자체로 설정하고 이 단계를 다시 시작할 수 있습니다.

  9. 그렇지 않으면, starting point자식 탐색 가능 내의 포커스 가능 영역입니다. starting point를 해당 자식 탐색 가능부모로 설정하고 반복 단계로 돌아갑니다.

순차 탐색 검색 알고리즘은 다음 단계로 구성됩니다. 이 알고리즘은 starting point, direction, selection mechanism이라는 세 가지 인수를 받습니다.

  1. 다음 표에서 적절한 셀을 선택하고, 해당 셀의 지침을 따르세요.

    적절한 셀은 direction을 설명하는 열의 헤더에서, starting pointselection mechanism을 설명하는 행의 첫 번째 헤더에서 선택된 셀입니다.

    directionforward일 때 directionbackward일 때
    starting point탐색 가능일 때 candidatestarting point활성 문서 내의 첫 번째 적합한 순차적으로 포커스 가능한 영역으로 설정하고, 없으면 null로 설정합니다. candidatestarting point활성 문서 내의 마지막 적합한 순차적으로 포커스 가능한 영역으로 설정하고, 없으면 null로 설정합니다.
    selection mechanismDOM일 때 candidatestarting point 뒤의 홈 문서 내의 첫 번째 적합한 순차적으로 포커스 가능한 영역으로 설정하고, 없으면 null로 설정합니다. candidatestarting point 이전의 홈 문서 내의 마지막 적합한 순차적으로 포커스 가능한 영역으로 설정하고, 없으면 null로 설정합니다.
    selection mechanismsequential일 때 candidatestarting point 뒤의 홈 순차 포커스 탐색 순서 내의 첫 번째 적합한 순차적으로 포커스 가능한 영역으로 설정하고, 없으면 null로 설정합니다. candidatestarting point 이전의 홈 순차 포커스 탐색 순서 내의 마지막 적합한 순차적으로 포커스 가능한 영역으로 설정하고, 없으면 null로 설정합니다.

    적합한 순차적으로 포커스 가능한 영역포커스 가능 영역으로, 그 DOM 앵커비활성화되지 않았고 순차적으로 포커스 가능한 영역입니다.

    홈 문서starting point가 속한 document입니다.

    홈 순차 포커스 탐색 순서starting point가 속한 순차 포커스 탐색 순서입니다.

    홈 순차 포커스 탐색 순서홈 문서순차 포커스 탐색 순서입니다. 그러나 이는 starting point가 해당 순차 포커스 탐색 순서에 있을 때만 사용됩니다(그렇지 않을 때는 selection mechanismDOM이 됩니다).

  2. 만약 candidate가 비어 있지 않은 콘텐츠 내비게이션 가능을 가진 내비게이션 가능한 컨테이너라면, new candidatecandidate콘텐츠 내비게이션 가능을 첫 번째 인수로, direction을 두 번째 인수로, sequential을 세 번째 인수로 하여 순차 탐색 검색 알고리즘을 실행한 결과로 설정합니다.

    만약 new candidate가 null이면 starting pointcandidate로 설정하고 이 알고리즘의 처음으로 돌아갑니다. 그렇지 않으면 candidatenew candidate로 설정합니다.

  3. candidate를 반환합니다.

6.6.6 포커스 관리 API

dictionary FocusOptions {
  boolean preventScroll = false;
  boolean focusVisible;
};
documentOrShadowRoot.activeElement

Document/activeElement

모든 현재 엔진에서 지원.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

ShadowRoot/activeElement

모든 현재 엔진에서 지원.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

키 이벤트가 문서를 통해 또는 문서로 라우팅되는 가장 깊은 요소를 반환합니다. 이는 대략적으로 문서에서 포커스된 요소입니다.

이 API의 목적상, 자식 탐색 가능이 포커스된 경우, 해당 컨테이너는 해당 부모활성 문서 내에서 포커스됩니다. 예를 들어 사용자가 iframe 내의 텍스트 제어로 포커스를 이동시키면, iframe이 해당 activeElement API에 의해 반환되는 요소입니다.

마찬가지로 포커스된 요소가 documentOrShadowRoot와 다른 노드 트리에 있는 경우, 반환되는 요소는 해당 documentOrShadowRoot와 같은 노드 트리 내에 있는 호스트가 됩니다. documentOrShadowRoot가 포커스된 요소의 그림자 포함 포함 조상인 경우에만 해당되며, 그렇지 않으면 null을 반환합니다.

document.hasFocus()

Document/hasFocus

모든 현재 엔진에서 지원.

Firefox3+Safari4+Chrome2+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?

키 이벤트가 문서를 통해 또는 문서로 라우팅되는 경우 true를 반환하고, 그렇지 않은 경우 false를 반환합니다. 대략적으로 이는 해당 문서 또는 그 안에 중첩된 문서가 포커스를 받고 있는 것과 일치합니다.

window.focus()

Window/focus

모든 현재 엔진에서 지원.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

포커스를 윈도우의 탐색 가능 요소로 이동합니다.

element.focus([ { preventScroll: true } ])

HTMLElement/focus

모든 현재 엔진에서 지원.

Firefox1.5+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

포커스를 해당 요소로 이동합니다.

해당 요소가 탐색 가능 컨테이너인 경우, 포커스를 해당 탐색 가능 콘텐츠로 이동시킵니다.

기본적으로 이 메서드는 요소를 보기로 스크롤합니다. preventScroll 옵션을 제공하고 true로 설정하면 이 동작을 방지할 수 있습니다.

element.blur()

HTMLElement/blur

모든 현재 엔진에서 지원.

Firefox1.5+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

포커스를 뷰포트로 이동시킵니다. 이 메서드의 사용은 권장되지 않습니다. 뷰포트를 포커스하려면 focus() 메서드를 호출하십시오. Document문서 요소에 포커스를 맞춥니다.

포커스 링을 숨기기 위해 이 메서드를 사용하지 마십시오. 대신, :focus-visible 의사 클래스를 사용하여 'outline' 속성을 덮어쓰고 포커스된 요소를 표시하는 다른 방법을 제공하십시오. 대안 포커스 스타일이 제공되지 않으면 페이지를 주로 키보드로 탐색하는 사용자나 시력이 약화된 사용자가 페이지를 탐색하는 데 포커스 링을 사용하는 사람들에게 페이지 사용이 상당히 어려워집니다.

예를 들어 textarea 요소의 아웃라인을 숨기고 대신 포커스를 나타내기 위해 노란색 배경을 사용하려면 다음을 사용할 수 있습니다:

textarea:focus-visible { outline: none; background: yellow; color: black; }

activeElement 속성의 getter는 다음 단계를 수행해야 합니다:

  1. candidate를 이 DocumentOrShadowRoot노드 문서포커스된 영역DOM 앵커로 설정합니다.

  2. candidate를 이 DocumentOrShadowRoot에 대해 재타겟팅한 결과로 설정합니다.

  3. candidate루트가 이 DocumentOrShadowRoot가 아닌 경우 null을 반환합니다.

  4. candidateDocument 객체가 아닌 경우, candidate를 반환합니다.

  5. candidate본문 요소가 있는 경우, 해당 본문 요소를 반환합니다.

  6. candidate문서 요소가 null이 아닌 경우 해당 문서 요소를 반환합니다.

  7. null을 반환합니다.

Document 객체의 hasFocus() 메서드는 호출될 때 포커스 여부 확인 단계를 실행하여 Document 객체를 인수로 반환해야 합니다.

focus() 메서드는 호출될 때 다음 단계를 수행해야 합니다:

  1. 현재 Window 객체의 탐색 가능 요소를 current로 설정합니다.

  2. current가 null인 경우 반환합니다.

  3. current와 함께 포커싱 단계를 실행합니다.

  4. current최상위 탐색 가능 요소인 경우, 사용자 에이전트는 페이지가 포커스를 얻으려 시도하고 있음을 사용자에게 알리기 위해 일부 알림을 트리거하는 것이 좋습니다.

Window/blur

모든 현재 엔진에서 지원.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

blur() 메서드 단계는 아무 작업도 하지 않습니다.

역사적으로 focus()blur() 메서드는 실제로 포함된 시스템 위젯(예: 탭 또는 윈도우)의 시스템 수준 포커스에 영향을 주었지만, 적대적인 사이트들이 이 동작을 악용하여 사용자에게 불이익을 주는 경우가 많았습니다.

focus(options) 메서드는 호출될 때 다음 단계를 수행해야 합니다:

  1. 해당 요소가 포커스 잠금으로 표시된 경우, 반환합니다.

  2. 해당 요소를 포커스 잠금으로 표시합니다.

  3. 해당 요소에 대한 포커싱 단계를 실행합니다.

  4. 만약 optionsfocusVisible 사전 멤버의 값이 true인 경우, 또는 존재하지 않지만 사용자 에이전트가 구현 정의된 방식으로 판단하여 그렇게 하는 것이 좋다고 결정하는 경우, 포커스를 나타내야 합니다.

  5. 만약 optionspreventScroll 사전 멤버의 값이 false인 경우, "auto", "center" 및 "center"를 사용하여 요소를 보기로 스크롤합니다.

  6. 해당 요소를 포커스 잠금에서 해제합니다.

blur() 메서드는 호출될 때 해당 메서드가 호출된 요소에 대해 포커스 해제 단계를 실행해야 합니다. 사용자 에이전트는 사용성 이유로 이 메서드 호출을 선택적으로 또는 일률적으로 무시할 수 있습니다.

예를 들어 blur() 메서드가 미관상의 이유로 포커스 링을 제거하는 데 사용되고 있다면, 페이지는 키보드 사용자에게 사용 불가능해집니다. 이 메서드 호출을 무시하면 키보드 사용자가 페이지와 상호작용할 수 있게 됩니다.

6.6.7 autofocus 속성

autofocus 콘텐츠 속성은 페이지가 로드되자마자 요소가 포커스되도록 지시하여 사용자가 주요 요소를 수동으로 포커스하지 않고도 바로 입력을 시작할 수 있게 합니다.

autofocus 속성이 dialog 요소 내부 또는 popover 속성이 설정된 HTML 요소 내에 지정된 경우, 해당 요소는 대화 상자 또는 팝오버가 표시될 때 포커스됩니다.

autofocus 속성은 boolean 속성입니다.

주어진 요소 element에 대해 가장 가까운 조상 자동 포커스 범위 설정 루트 요소를 찾으려면 다음 단계를 따릅니다:

  1. elementdialog 요소인 경우, element를 반환합니다.

  2. elementpopover 속성이 popover 없음 상태에 있지 않은 경우, element를 반환합니다.

  3. ancestorelement로 설정합니다.

  4. ancestor상위 요소가 있는 동안:

    1. ancestorancestor상위 요소로 설정합니다.

    2. ancestordialog 요소인 경우, ancestor를 반환합니다.

    3. ancestorpopover 속성이 popover 없음 상태에 있지 않은 경우, ancestor를 반환합니다.

  5. ancestor를 반환합니다.

동일한 가장 가까운 조상 자동 포커스 범위 설정 루트 요소를 가진 두 개의 요소가 모두 autofocus 속성을 지정해서는 안 됩니다.

document는 처음에는 비어 있는 자동 포커스 후보 목록을 가지고 있습니다.

document는 처음에는 false로 설정된 자동 포커스 처리 플래그 boolean 값을 가지고 있습니다.

autofocus 속성이 지정된 요소가 문서에 삽입될 때 다음 단계를 실행합니다:

  1. 사용자가 (예: 폼 컨트롤에서 입력을 시작하여) 포커스를 변경하지 않기를 원한다고 표시한 경우, 선택적으로 반환합니다.

  2. target을 요소의 노드 문서로 설정합니다.

  3. target완전히 활성화된 상태가 아니면 반환합니다.

  4. target활성 샌드박싱 플래그 세트샌드박스화된 자동 기능 브라우징 컨텍스트 플래그가 포함되어 있는 경우 반환합니다.

  5. ancestorNavigable에 대해 target조상 내비게이션 가능 요소 목록에서 ancestorNavigable활성 문서출처target출처와 동일하지 않은 경우 반환합니다.

  6. topDocumenttarget노드 내비게이션 가능 요소최상위 탐색 가능 요소활성 문서로 설정합니다.

  7. topDocument자동 포커스 처리 플래그가 false이면, 제거하고 추가합니다.

요소가 포커스 가능한 영역인지 확인하지 않고, 자동 포커스 후보 목록에 저장합니다. 삽입 당시 포커스 가능 영역이 아니더라도 자동 포커스 후보 플러시 작업이 실행될 때까지 포커스 가능 영역이 될 수 있기 때문입니다.

자동 포커스 후보 플러시를 위해 문서 topDocument에 대해 다음 단계를 실행합니다:

  1. topDocument자동 포커스 처리 플래그가 true이면 반환합니다.

  2. candidatestopDocument자동 포커스 후보로 설정합니다.

  3. candidates비어 있으면 반환합니다.

  4. topDocument포커스된 영역topDocument 자체가 아니거나, topDocument에 null이 아닌 타겟 요소가 있는 경우:

    1. 비웁니다 candidates.

    2. topDocument자동 포커스 처리 플래그를 true로 설정합니다.

    3. 반환합니다.

  5. candidates비어 있지 않은 동안:

    1. elementcandidates[0]으로 설정합니다.

    2. docelement노드 문서로 설정합니다.

    3. doc완전히 활성화되지 않은 경우, 제거하고 계속합니다.

    4. doc노드 내비게이션 가능 요소최상위 탐색 가능 요소topDocument노드 내비게이션 가능 요소와 동일하지 않은 경우, 제거하고 계속합니다.

    5. doc스크립트 차단 스타일 시트 세트비어 있지 않은 경우 반환합니다.

      이 경우 element는 현재 가장 좋은 후보이지만 doc이 자동 포커싱을 위한 준비가 되지 않았습니다. 다음에 자동 포커스 후보 플러시가 호출될 때 다시 시도합니다.

    6. 제거합니다 elementcandidates에서.

    7. inclusiveAncestorDocumentsdoc포괄적인 조상 내비게이션 가능 요소활성 문서로 구성된 목록으로 설정합니다.

    8. 포함된 문서 중에 null이 아닌 타겟 요소가 있는 경우 계속합니다.

    9. targetelement로 설정합니다.

    10. target포커스 가능한 영역이 아닌 경우, 포커스 가능한 영역 가져오기 결과를 target으로 설정합니다.

      자동 포커스 후보에는 포함될 수 있습니다 포커스 가능 영역이 아닌 요소가. 이러한 경우는 포커스 가능한 영역 가져오기 알고리즘에서 처리되는 특별한 경우 외에도, 포커스 가능한 영역이 아닌 요소가 문서에 삽입되었으며 포커스 가능 상태로 전환되지 않았거나, 요소가 포커스 가능했으나 자동 포커스 후보에 저장되어 있는 동안 상태가 변경된 경우에 발생할 수 있습니다.

    11. target이 null이 아닌 경우 다음을 실행합니다:

      1. 비웁니다 candidates.

      2. topDocument자동 포커스 처리 플래그를 true로 설정합니다.

      3. 포커싱 단계를 실행합니다 target에 대해.

이는 문서 로드 중 자동 포커싱을 처리합니다. show()showModal() 메서드는 dialog 요소의 자동 포커스 속성도 처리합니다.

요소에 포커스가 맞춰졌다고 해서 사용자가 브라우저 창에 포커스를 다시 맞춰야 한다는 의미는 아닙니다.

Global_attributes/autofocus

한 엔진에서만 지원.

Firefox🔰 1+🔰 4+Chrome79+
Opera66+Edge79+
Edge (Legacy)아니요Internet Explorer🔰 10+
Firefox Android?Safari iOS?Chrome Android?WebView Android79+Samsung Internet?Opera Android57+

autofocus IDL 속성은 동일한 이름의 콘텐츠 속성을 반영해야 합니다.

다음 예제에서, 텍스트 컨트롤은 문서가 로드될 때 포커스됩니다.

<input maxlength="256" name="q" value="" autofocus>
<input type="submit" value="Search">

autofocus 속성은 폼 컨트롤뿐만 아니라 모든 요소에 적용됩니다. 다음과 같은 예제도 가능합니다:

<div contenteditable autofocus>Edit <strong>me!</strong><div>

6.7 키보드 단축키 할당

6.7.1 소개

이 섹션은 비규범적입니다.

활성화되거나 포커스될 수 있는 각 요소는 accesskey 속성을 사용하여 요소를 활성화하는 단일 키 조합에 할당될 수 있습니다.

정확한 단축키는 사용자의 키보드 정보, 플랫폼에서 이미 존재하는 키보드 단축키, 페이지에 지정된 다른 단축키에 대한 정보를 기반으로 사용자 에이전트에 의해 결정되며, accesskey 속성에 제공된 정보를 가이드로 사용합니다.

다양한 입력 장치에서 관련 키보드 단축키를 사용할 수 있도록 하기 위해, 작성자는 accesskey 속성에서 여러 가지 대안을 제공할 수 있습니다.

각 대안은 문자 또는 숫자와 같은 단일 문자로 구성됩니다.

사용자 에이전트는 사용자에게 키보드 단축키 목록을 제공할 수 있지만, 작성자도 이를 제공하는 것이 좋습니다. accessKeyLabel IDL 속성은 사용자 에이전트에 의해 할당된 실제 키 조합을 나타내는 문자열을 반환합니다.

이 예제에서 작성자는 단축키를 사용하여 호출할 수 있는 버튼을 제공했습니다. 전체 키보드를 지원하기 위해 "C"를 가능한 키로 제공했습니다. 숫자 키패드만 장착된 장치를 지원하기 위해 "1"을 또 다른 가능한 키로 제공했습니다.

<input type=button value=Collect onclick="collect()"
       accesskey="C 1" id=c>

사용자에게 단축키가 무엇인지 알려주기 위해, 작성자는 이 스크립트를 사용하여 버튼의 레이블에 키 조합을 명시적으로 추가하는 방법을 선택했습니다:

function addShortcutKeyLabel(button) {
  if (button.accessKeyLabel != '')
    button.value += ' (' + button.accessKeyLabel + ')';
}
addShortcutKeyLabel(document.getElementById('c'));

다른 플랫폼의 브라우저들은 동일한 키 조합에 대해서도 그 플랫폼에서 널리 사용되는 관례에 따라 서로 다른 레이블을 표시합니다. 예를 들어, 키 조합이 Control 키, Shift 키, C 문자일 경우, Windows 브라우저는 "Ctrl+Shift+C"를 표시할 수 있고, Mac 브라우저는 "^⇧C"를 표시할 수 있으며, Emacs 브라우저는 "C-C"를 표시할 수 있습니다. 유사하게, 키 조합이 Alt 키와 Escape 키일 경우, Windows는 "Alt+Esc"를 사용하고, Mac은 "⌥⎋"를 사용하며, Emacs 브라우저는 "M-ESC" 또는 "ESC ESC"를 사용할 수 있습니다.

따라서 일반적으로 accessKeyLabel IDL 속성에서 반환된 값을 구문 분석하려고 시도하는 것은 현명하지 않습니다.

6.7.2 accesskey 속성

Global_attributes/accesskey

모든 현재 엔진에서 지원됨.

Firefox1+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

모든 HTML 요소accesskey 콘텐츠 속성을 설정할 수 있습니다. accesskey 속성의 값은 요소를 활성화하거나 포커스하는 키보드 단축키를 만드는 가이드로 사용자 에이전트에 의해 사용됩니다.

지정된 경우, 값은 고유한 공백으로 구분된 토큰의 순서 있는 집합이어야 하며, 각 토큰은 다른 토큰과 동일하지 않고 각각 정확히 한 코드 포인트 길이여야 합니다.

다음 예제에서는 다양한 링크에 액세스 키가 지정되어 있어 키보드 사용자가 사이트에 익숙한 경우 관련 페이지로 더 빠르게 탐색할 수 있습니다:

<nav>
 <p>
  <a title="Consortium Activities" accesskey="A" href="/Consortium/activities">Activities</a> |
  <a title="Technical Reports and Recommendations" accesskey="T" href="/TR/">Technical Reports</a> |
  <a title="Alphabetical Site Index" accesskey="S" href="/Consortium/siteindex">Site Index</a> |
  <a title="About This Site" accesskey="B" href="/Consortium/">About Consortium</a> |
  <a title="Contact Consortium" accesskey="C" href="/Consortium/contact">Contact</a>
 </p>
</nav>

다음 예제에서는 검색 필드에 "s"와 "0"(그 순서로) 두 가지 액세스 키가 제공됩니다. 전체 키보드가 있는 장치의 사용자 에이전트는 Ctrl + Alt + S를 단축키로 선택할 수 있고, 숫자 키패드만 있는 소형 장치의 사용자 에이전트는 단순히 0 키를 선택할 수 있습니다:

<form action="/search">
 <label>Search: <input type="search" name="q" accesskey="s 0"></label>
 <input type="submit">
</form>

다음 예제에서는 버튼에 대한 가능한 액세스 키가 설명되어 있습니다. 스크립트는 사용자 에이전트가 선택한 키 조합을 알리기 위해 버튼의 레이블을 업데이트하려고 시도합니다.

<input type=submit accesskey="N @ 1" value="Compose">
...
<script>
 function labelButton(button) {
   if (button.accessKeyLabel)
     button.value += ' (' + button.accessKeyLabel + ')';
 }
 var inputs = document.getElementsByTagName('input');
 for (var i = 0; i < inputs.length; i += 1) {
   if (inputs[i].type == "submit")
     labelButton(inputs[i]);
 }
</script>

한 사용자 에이전트에서는 버튼의 레이블이 "Compose (⌘N)"로 바뀔 수 있습니다. 다른 에이전트에서는 "Compose (Alt+⇧+1)"로 바뀔 수 있습니다. 사용자 에이전트가 키를 할당하지 않은 경우, "Compose"로만 표시됩니다. 정확한 문자열은 할당된 액세스 키와 사용자 에이전트가 해당 키 조합을 어떻게 표현하는지에 따라 다릅니다.

6.7.3 처리 모델

요소의 할당된 액세스 키는 요소의 accesskey 콘텐츠 속성에서 파생된 키 조합입니다. 처음에는 요소가 할당된 액세스 키를 갖지 않아야 합니다.

요소의 accesskey 속성이 설정, 변경 또는 제거될 때마다, 사용자 에이전트는 다음 단계를 수행하여 요소의 할당된 액세스 키를 업데이트해야 합니다:

  1. 요소에 accesskey 속성이 없으면, 아래의 대체 단계로 건너뜁니다.

  2. 그렇지 않으면, 속성 값을 ASCII 공백으로 분할하고, keys를 결과 토큰으로 설정합니다.

  3. 속성 값에서 토큰이 나타난 순서대로 keys의 각 값을 차례로 실행하여 다음 하위 단계를 실행합니다:

    1. 값이 정확히 한 코드 포인트 길이의 문자열이 아닌 경우, 이 값에 대한 나머지 단계를 건너뜁니다.

    2. 값이 시스템 키보드의 키에 해당하지 않으면, 이 값에 대한 나머지 단계를 건너뜁니다.

    3. (이것은 추적 벡터입니다.) 사용자 에이전트가 속성에 지정된 값에 해당하는 키와 함께 사용할 수 있는 수정 키 조합을 찾을 수 있다면, 사용자 에이전트는 그 조합을 요소의 할당된 액세스 키로 지정하고 반환할 수 있습니다.

  4. 대체: 선택적으로, 사용자 에이전트는 선택한 키 조합을 요소의 할당된 액세스 키로 지정하고 반환할 수 있습니다.

  5. 이 단계에 도달하면, 해당 요소는 할당된 액세스 키를 갖지 않습니다.

사용자 에이전트가 요소에 대한 액세스 키를 선택하고 할당한 후에는 요소의 할당된 액세스 키를 변경해서는 안 됩니다. 단, accesskey 콘텐츠 속성이 변경되거나 요소가 다른 Document로 이동되는 경우는 예외입니다.

사용자가 요소에 대한 할당된 액세스 키에 해당하는 키 조합을 누르면, 해당 요소가 명령을 정의하고, 명령의 숨김 상태 측면이 false(보이는 상태)이며, 명령의 비활성 상태 측면도 false(활성화된 상태)이며, 요소가 문서에 포함되어 있고, 요소 및 그 조상 중 어느 것도 hidden 속성이 지정되지 않은 경우, 사용자 에이전트는 명령의 동작을 트리거해야 합니다.

사용자 에이전트는 다른 방법으로도 accesskey 속성이 있는 요소를 노출할 수 있으며, 예를 들어 특정 키 조합에 응답하여 표시되는 메뉴에서 이를 노출할 수 있습니다.


HTMLElement/accessKey

모든 현재 엔진에서 지원됨.

Firefox5+Safari6+Chrome17+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

accessKey IDL 속성은 반영해야 합니다. accesskey 콘텐츠 속성을 반영해야 합니다.

HTMLElement/accessKeyLabel

Firefox8+Safari14+Chrome아니오
Opera?Edge아니오
Edge (Legacy)?Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

accessKeyLabel IDL 속성은 요소의 할당된 액세스 키를 나타내는 문자열을 반환해야 합니다(있는 경우). 요소에 할당된 액세스 키가 없으면 IDL 속성은 빈 문자열을 반환해야 합니다.

6.8 편집

6.8.1 문서 영역을 편집 가능하게 만들기: contenteditable 콘텐츠 속성

HTMLElement/contentEditable

모든 현재 엔진에서 지원됨.

Firefox3+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
interface mixin ElementContentEditable {
  [CEReactions] attribute DOMString contentEditable;
  [CEReactions] attribute DOMString enterKeyHint;
  readonly attribute boolean isContentEditable;
  [CEReactions] attribute DOMString inputMode;
};

Global_attributes/contenteditable

모든 현재 엔진에서 지원됨.

Firefox3+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

contenteditable 콘텐츠 속성은 다음 키워드와 상태를 가진 열거된 속성입니다:

키워드 상태 간단한 설명
true true 요소는 편집 가능합니다.
(빈 문자열)
false false 요소는 편집할 수 없습니다.
plaintext-only plaintext-only 요소의 원시 텍스트 콘텐츠만 편집 가능하며, 리치 포맷팅은 비활성화됩니다.

속성의 값이 누락된 경우 기본값잘못된 값 기본값은 모두 상속 상태입니다. 상속 상태는 부모 요소의 상태에 따라 요소가 편집 가능한지 여부를 나타냅니다.

예를 들어, 사용자가 HTML을 사용하여 새 기사를 작성하도록 예상되는 formtextarea가 있는 페이지를 고려해 보십시오:

<form method=POST>
 <fieldset>
  <legend>새 기사</legend>
  <textarea name=article>&lt;p>안녕하세요 세계.&lt;/p></textarea>
 </fieldset>
 <p><button>게시</button></p>
</form>

스크립팅이 활성화되면, textarea 요소는 대신 contenteditable 속성을 사용하여 리치 텍스트 컨트롤로 교체할 수 있습니다:

<form method=POST>
 <fieldset>
  <legend>새 기사</legend>
  <textarea id=textarea name=article>&lt;p>안녕하세요 세계.&lt;/p></textarea>
  <div id=div style="white-space: pre-wrap" hidden><p>안녕하세요 세계.</p></div>
  <script>
   let textarea = document.getElementById("textarea");
   let div = document.getElementById("div");
   textarea.hidden = true;
   div.hidden = false;
   div.contentEditable = "true";
   div.oninput = (e) => {
     textarea.value = div.innerHTML;};
  </script>
 </fieldset>
 <p><button>게시</button></p>
</form>

예를 들어, 링크 삽입과 같은 기능은 document.execCommand() API 또는 Selection API 및 기타 DOM API를 사용하여 구현할 수 있습니다. [EXECCOMMAND] [SELECTION] [DOM]

contenteditable 속성도 효과적으로 사용할 수 있습니다:

<!doctype html>
<html lang=en>
<title>실시간 CSS 편집!</title>
<style style=white-space:pre contenteditable>
html { margin:.2em; font-size:2em; color:lime; background:purple }
head, title, style { display:block }
body { display:none }
</style>
element.contentEditable [ = value ]

요소의 contenteditable 속성의 상태에 따라 "true", "plaintext-only", "false" 또는 "inherit"을 반환합니다.

설정을 통해 해당 상태를 변경할 수 있습니다.

새 값이 이러한 문자열 중 하나가 아니면 "SyntaxError" DOMException을 발생시킵니다.

element.isContentEditable

HTMLElement/isContentEditable

모든 현재 엔진에서 지원됨.

Firefox4+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

요소가 편집 가능하면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

contentEditable IDL 속성은 가져올 때, 콘텐츠 속성이 true 상태로 설정되어 있으면 문자열 "true"를 반환하고, 콘텐츠 속성이 plaintext-only 상태로 설정되어 있으면 "plaintext-only", 콘텐츠 속성이 false 상태로 설정되어 있으면 "false", 그렇지 않으면 "inherit"을 반환해야 합니다. 설정할 때, 새 값이 "inherit" 문자열과 ASCII 대소문자 구분 없음 매칭이면 콘텐츠 속성이 제거되어야 합니다. 새 값이 "true" 문자열과 ASCII 대소문자 구분 없음 매칭이면 콘텐츠 속성은 "true" 문자열로 설정되어야 하고, 새 값이 "plaintext-only" 문자열과 ASCII 대소문자 구분 없음 매칭이면 콘텐츠 속성은 "plaintext-only" 문자열로 설정되어야 하며, 새 값이 "false" 문자열과 ASCII 대소문자 구분 없음 매칭이면 콘텐츠 속성은 "false" 문자열로 설정되어야 하며, 그렇지 않으면 속성 설정자는 "SyntaxError" DOMException을 발생시켜야 합니다.

isContentEditable IDL 속성은 가져올 때, 요소가 편집 호스트 또는 편집 가능하면 true를 반환하고, 그렇지 않으면 false를 반환해야 합니다.

6.8.2 문서 전체를 편집 가능하게 만들기: designMode getter 및 setter

document.designMode [ = value ]

Document/designMode

모든 현재 엔진에서 지원됨.

Firefox1+Safari1.2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

문서가 편집 가능하면 "on"을 반환하고, 그렇지 않으면 "off"를 반환합니다.

문서의 현재 상태를 변경하기 위해 설정할 수 있습니다. 이렇게 하면 문서에 포커스가 맞춰지고 문서 내의 선택 영역이 재설정됩니다.

Document 객체는 디자인 모드 활성화라는 부울 값을 가지며, 초기 값은 false입니다.

designMode getter 단계는 this디자인 모드 활성화가 true일 때 "on"을 반환하고, 그렇지 않으면 "off"를 반환합니다.

designMode setter 단계는 다음과 같습니다:

  1. 주어진 값을 ASCII 소문자로 변환value로 설정합니다.

  2. value가 "on"이고, this디자인 모드 활성화가 false인 경우:

    1. this디자인 모드 활성화를 true로 설정합니다.

    2. this활성 범위의 시작 및 종료 경계 지점을 this의 시작 부분으로 재설정합니다.

    3. 비어 있지 않은 경우 포커싱 단계this문서 요소에 대해 실행합니다.

  3. value가 "off"인 경우, this디자인 모드 활성화를 false로 설정합니다.

6.8.3 페이지 내 편집기 사용을 위한 모범 사례

저자는 'white-space' 속성을 편집 호스트와 이러한 편집 메커니즘을 통해 처음 생성된 마크업에 대해 'pre-wrap' 값으로 설정할 것을 권장합니다. 기본 HTML 공백 처리 방식은 WYSIWYG 편집에 적합하지 않으며, 'white-space'를 기본 값으로 두면 일부 경계 사례에서 줄 바꿈이 제대로 작동하지 않을 수 있습니다.

기본 'normal' 값이 대신 사용될 경우 발생하는 문제의 예로, 사용자가 "yellow␣␣ball"을 두 개의 공백(여기서 "␣"으로 표시됨)으로 단어 사이에 입력한 경우를 고려해 보세요. 'white-space'('normal')의 기본값에 대한 편집 규칙이 적용된 경우, 결과 마크업은 "yellow&nbsp; ball" 또는 "yellow &nbsp;ball"로 구성됩니다. 즉, 일반 공백 외에도 두 단어 사이에 비공개 공백이 추가됩니다. 이는 'normal' 값의 'white-space'가 인접한 일반 공백을 함께 축소해야 하기 때문에 필요합니다.

첫 번째 경우에는 "yellow⍽"이 다음 줄로 넘어갈 수 있으며("⍽"은 여기서 비공개 공백을 나타냄), "yellow" 단어가 줄 끝에 들어갈 수 있음에도 불구하고 줄 바꿈이 발생할 수 있습니다. 두 번째 경우에는 "⍽ball"이 줄 시작에 래핑되면 비공개 공백으로 인해 가시적인 들여쓰기가 발생할 수 있습니다.

그러나 'white-space'가 'pre-wrap'으로 설정되면, 편집 규칙은 단순히 두 단어 사이에 두 개의 일반 공백을 삽입하며, 줄 끝에서 두 단어가 나뉘는 경우 공백이 깔끔하게 렌더링에서 제거됩니다.

6.8.4 편집 API

편집 호스트contenteditable 속성이 true 상태 또는 plaintext-only 상태인 HTML 요소이거나, 자식 HTML 요소로서 디자인 모드가 활성화된 Document의 일부입니다.

활성 범위, 편집 호스트, 편집 가능이라는 용어의 정의와 편집 호스트 또는 편집 가능 요소에 대한 사용자 인터페이스 요구 사항, execCommand(), queryCommandEnabled(), queryCommandIndeterm(), queryCommandState(), queryCommandSupported(), 그리고 queryCommandValue() 메서드, 텍스트 선택 및 선택 삭제 알고리즘은 execCommand에서 정의됩니다. [EXECCOMMAND]

6.8.5 맞춤법 및 문법 검사

사용자 에이전트는 편집 가능한 텍스트에 대한 맞춤법 및 문법 검사를 지원할 수 있습니다. 이는 textarea 요소와 같은 폼 컨트롤이나 contenteditable 속성을 사용하여 편집 호스트에 있는 요소에서 가능합니다.

각 요소에 대해, 사용자 에이전트는 기본 동작을 설정해야 합니다. 이 기본 동작은 기본값 또는 사용자가 표현한 기본 설정을 통해 설정됩니다. 각 요소에는 세 가지 가능한 기본 동작이 있습니다:

기본값으로 true
요소의 내용이 편집 가능하고 spellcheck 속성을 통해 맞춤법 검사가 명시적으로 비활성화되지 않은 경우, 요소는 맞춤법 및 문법 검사를 받습니다.
기본값으로 false
맞춤법 검사는 spellcheck 속성을 통해 명시적으로 활성화되지 않는 한, 요소는 맞춤법 및 문법 검사를 받지 않습니다.
기본값으로 상속
요소의 기본 동작은 부모 요소의 기본 동작과 동일합니다. 부모 요소가 없는 요소는 이 기본 동작을 가질 수 없습니다.

Global_attributes/spellcheck

모든 현재 엔진에서 지원됩니다.

FirefoxYesSafariYesChrome9+
OperaYesEdge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android57+Safari iOS9.3+Chrome Android47+WebView Android?Samsung Internet?Opera Android37+

spellcheck 속성은 열거형 속성으로, 다음과 같은 키워드와 상태를 가집니다:

키워드 상태 간략한 설명
true true 맞춤법 및 문법이 검사됩니다.
(빈 문자열)
false false 맞춤법 및 문법이 검사되지 않습니다.

속성의 누락된 값의 기본값잘못된 값의 기본값은 모두 기본 상태입니다. 기본 상태는 요소가 아래에 정의된 대로 기본 동작에 따라 작동하도록 지정합니다.


element.spellcheck [ = value ]

요소의 맞춤법 및 문법 검사를 수행해야 하는 경우 true를 반환하고, 그렇지 않은 경우 false를 반환합니다.

설정할 수 있으며, 이를 통해 기본 동작을 무시하고 spellcheck 콘텐츠 속성을 설정할 수 있습니다.

spellcheck IDL 속성은, 조회 시, 요소의 spellcheck 콘텐츠 속성이 true 상태이거나, 기본 상태이고 요소의 기본 동작true-by-default 상태이거나, 요소의 부모 요소의 spellcheck IDL 속성이 true를 반환하는 경우 true를 반환합니다. 그렇지 않으면 false를 반환해야 합니다.

spellcheck IDL 속성은 spellcheck 콘텐츠 속성을 무시하는 사용자 기본 설정에 의해 영향을 받지 않으므로 실제 맞춤법 검사 상태를 반영하지 않을 수 있습니다.

설정 시, 새 값이 true이면 요소의 spellcheck 콘텐츠 속성을 "true"로 설정해야 하며, 그렇지 않은 경우 "false"로 설정해야 합니다.


사용자 에이전트는 이 기능을 위해 다음 텍스트 조각만 검사 대상으로 고려해야 합니다:

텍스트가 Text 노드의 일부인 경우, 텍스트와 연결된 요소는 단어, 문장 또는 다른 텍스트 조각의 첫 번째 문자의 즉각적인 부모 요소입니다. 속성에 포함된 텍스트의 경우, 속성의 요소가 연결된 요소입니다. inputtextarea 요소의 값의 경우, 요소 자체가 연결된 요소입니다.

적용 가능한 요소(위에서 정의됨)에서 단어, 문장 또는 다른 텍스트 조각에 대해 맞춤법 및 문법 검사를 활성화할지 여부를 결정하기 위해, 사용자 에이전트는 다음 알고리즘을 사용해야 합니다:

  1. 사용자가 이 텍스트에 대한 검사를 비활성화한 경우, 검사는 비활성화됩니다.
  2. 그렇지 않은 경우, 사용자가 이 텍스트에 대한 검사를 항상 활성화하도록 강제한 경우, 검사는 활성화됩니다.
  3. 그렇지 않은 경우, 텍스트와 연결된 요소에 spellcheck 콘텐츠 속성이 있는 경우: 해당 속성이 true 상태인 경우 검사가 활성화됩니다. 그렇지 않으면, 해당 속성이 false 상태인 경우 검사가 비활성화됩니다.
  4. 그렇지 않은 경우, 기본 상태가 아닌 spellcheck 콘텐츠 속성을 가진 조상 요소가 있는 경우: 가장 가까운 그러한 조상의 spellcheck 콘텐츠 속성이 true 상태인 경우 검사가 활성화됩니다. 그렇지 않으면, 검사가 비활성화됩니다.
  5. 그렇지 않은 경우, 요소의 기본 동작true-by-default 상태인 경우 검사가 활성화됩니다.
  6. 그렇지 않은 경우, 요소의 기본 동작false-by-default 상태인 경우 검사가 비활성화됩니다.
  7. 그렇지 않은 경우, 요소의 부모 요소에 검사가 활성화되어 있으면, 검사가 활성화됩니다.
  8. 그렇지 않으면, 검사가 비활성화됩니다.

단어/문장/텍스트에 대해 검사가 활성화된 경우, 사용자 에이전트는 해당 텍스트의 맞춤법 및 문법 오류를 표시해야 합니다. 사용자 에이전트는 맞춤법 및 문법 수정 제안 시 문서에 제공된 다른 의미를 고려해야 합니다. 사용자 에이전트는 요소의 언어를 사용하여 맞춤법 및 문법 규칙을 결정할 수 있으며, 사용자의 선호 언어 설정을 사용할 수도 있습니다. 사용자 에이전트는 input 요소의 pattern 속성과 같은 속성을 사용하여 가능한 경우 결과 값이 유효한지 확인해야 합니다.

검사가 비활성화된 경우, 사용자 에이전트는 해당 텍스트에 대해 맞춤법 또는 문법 오류를 표시하지 않아야 합니다.

다음 예에서 "a" ID를 가진 요소는 "Hello" 단어가 맞춤법 오류로 검사되는지 여부를 결정하는 데 사용됩니다. 이 예에서는 맞춤법 검사가 이루어지지 않습니다.

<div contenteditable="true">
 <span spellcheck="false" id="a">Hell</span><em>o!</em>
</div>

다음 예에서 "b" ID를 가진 요소는 검사가 활성화됩니다(속성 값 앞의 공백 문자로 인해 input 요소에서 속성이 무시되므로 기본값 대신 조상 요소의 값이 사용됩니다).

<p spellcheck="true">
 <label>Name: <input spellcheck=" false" id="b"></label>
</p>

이 명세서는 맞춤법 및 문법 검사기의 사용자 인터페이스를 정의하지 않습니다. 사용자 에이전트는 요청 시 검사를 제공하거나, 검사가 활성화된 동안 연속적인 검사를 수행하거나, 다른 인터페이스를 사용할 수 있습니다.

6.8.6 쓰기 제안

사용자 에이전트는 사용자가 편집 가능한 영역에 입력할 때 쓰기 제안을 제공합니다. 이러한 영역은 폼 컨트롤(예: textarea 요소) 또는 편집 호스트의 요소일 수 있습니다.

writingsuggestions 콘텐츠 속성은 다음과 같은 키워드와 상태를 가진 열거형 속성입니다:

키워드 상태 간단한 설명
true true 이 요소에서 쓰기 제안을 제공해야 합니다.
(빈 문자열)
false false 이 요소에서 쓰기 제안을 제공하지 않아야 합니다.

속성의 누락된 값 기본값기본 상태입니다. 기본 상태는 요소가 부모 요소의 writingsuggestions 상태에 따라 행동해야 한다는 것을 나타냅니다.

속성의 유효하지 않은 값 기본값true 상태입니다.

element.writingSuggestions [ = value ]

사용자 에이전트가 요소의 범위 내에서 쓰기 제안을 제공해야 하는 경우 "true"를 반환합니다. 그렇지 않으면 "false"를 반환합니다.

기본값을 무시하고 writingsuggestions 콘텐츠 속성을 설정하도록 설정할 수 있습니다.

계산된 쓰기 제안 값은 다음 단계를 실행하여 결정됩니다:

  1. elementwritingsuggestions 콘텐츠 속성이 false 상태인 경우 "false"를 반환합니다.
  2. elementwritingsuggestions 콘텐츠 속성이 기본 상태이며, element에 부모 요소가 있고 부모 요소의 계산된 쓰기 제안 값이 "false"인 경우 "false"를 반환합니다.
  3. "true"를 반환합니다.

writingSuggestions getter 단계는 다음과 같습니다:

  1. this계산된 쓰기 제안 값을 반환합니다.

writingSuggestions IDL 속성은 사용자 설정에 의해 무시될 수 있으며, 실제 쓰기 제안 상태를 반영하지 않을 수 있습니다.

writingSuggestions setter 단계는 다음과 같습니다:

  1. thiswritingsuggestions 콘텐츠 속성을 주어진 값으로 설정합니다.

사용자 에이전트는 다음 알고리즘을 실행한 결과가 true일 경우에만 요소의 범위 내에서 제안을 제공해야 합니다:

  1. 사용자가 쓰기 제안을 비활성화한 경우 false를 반환합니다.
  2. 다음 조건이 모두 false일 경우 false를 반환합니다:
  3. element포함 조상이 있고, 해당 조상의 writingsuggestions 콘텐츠 속성이 기본 상태가 아닐 경우, 가장 가까운 조상의 writingsuggestions 콘텐츠 속성이 false 상태에 있으면 false를 반환합니다.
  4. 그렇지 않으면 true를 반환합니다.

이 사양은 쓰기 제안에 대한 사용자 인터페이스를 정의하지 않습니다. 사용자 에이전트는 사용자가 입력할 때 요청 시 제안을 제공하거나, 연속적으로 제안을 제공하거나, 인라인 제안을 제공하거나, 팝업에서 자동 완성과 유사한 제안을 제공할 수 있으며, 다른 인터페이스를 사용할 수도 있습니다.

6.8.7 자동 대문자 전환

텍스트를 입력하는 몇 가지 방법, 예를 들어 모바일 장치의 가상 키보드나 음성 입력 등은 종종 사용자가 문장의 첫 글자를 자동으로 대문자로 전환하는 것을 돕습니다(이 규칙을 따르는 언어에서 텍스트를 작성할 때). 자동 대문자 전환을 구현한 가상 키보드는 대문자로 자동 전환되지만 사용자가 다시 소문자로 전환할 수 있도록 허용할 수 있습니다. 음성 입력과 같은 다른 유형의 입력은 사용자가 먼저 개입할 수 있는 옵션을 제공하지 않고 자동 대문자 전환을 수행할 수 있습니다. autocapitalize 속성은 이러한 행동을 제어할 수 있게 해줍니다.

일반적으로 구현된 autocapitalize 속성은 물리적 키보드로 타이핑할 때의 동작에 영향을 주지 않습니다. (이러한 이유와 더불어, 사용자가 일부 경우 자동 대문자 전환 동작을 무시하거나 초기 입력 후 텍스트를 편집할 수 있는 능력이 있기 때문에, 이 속성은 입력 유효성 검사에 의존해서는 안 됩니다.)

autocapitalize 속성은 편집 호스트에서 호스팅된 편집 가능한 영역의 자동 대문자 전환 동작을 제어하기 위해, input 또는 textarea 요소에서 해당 요소에 텍스트를 입력할 때의 동작을 제어하기 위해, 또는 form 요소에서 해당 폼에 연결된 모든 자동 대문자 전환 상속 요소의 기본 동작을 제어하기 위해 사용될 수 있습니다.

autocapitalize 속성은 input 요소의 type 속성이 URL, 이메일, 또는 비밀번호 상태에 있는 경우, 자동 대문자 전환을 활성화하지 않습니다. (이 동작은 아래의 사용된 자동 대문자 전환 힌트 알고리즘에 포함되어 있습니다.)

자동 대문자 전환 처리 모델은 다음과 같이 정의된 다섯 가지 자동 대문자 전환 힌트 중 하나를 선택하는 것을 기반으로 합니다:

기본값

사용자 에이전트와 입력 방법은 자동 대문자 전환을 활성화할지 여부를 스스로 결정해야 합니다.

없음

자동 대문자 전환이 적용되지 않아야 하며(모든 글자는 기본적으로 소문자가 되어야 합니다).

문장

각 문장의 첫 글자는 기본적으로 대문자가 되어야 하며, 모든 다른 글자는 기본적으로 소문자가 되어야 합니다.

단어

각 단어의 첫 글자는 기본적으로 대문자가 되어야 하며, 모든 다른 글자는 기본적으로 소문자가 되어야 합니다.

문자

모든 글자는 기본적으로 대문자가 되어야 합니다.

Global_attributes/autocapitalize

모든 현재 엔진에서 지원됩니다.

Firefox111+Safari아니요Chrome43+
Opera?Edge79+
Edge (Legacy)?Internet Explorer?
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android?

autocapitalize 속성은 열거형 속성으로, 상태는 가능한 자동 대문자 전환 힌트입니다. 이 속성의 상태에 따라 지정된 자동 대문자 전환 힌트는 다른 요소들과 결합되어 사용자 에이전트의 동작을 알리는 사용된 자동 대문자 전환 힌트를 형성합니다. 이 속성의 키워드와 상태 매핑은 다음과 같습니다:

키워드 상태
off none
none
on sentences
sentences
words words
characters characters

이 속성의 값이 누락된 경우 기본값기본값 상태이며, 잘못된 값의 기본값sentences 상태입니다.

element.autocapitalize [ = value ]

요소의 현재 자동 대문자 전환 상태를 반환하거나 설정되지 않은 경우 빈 문자열을 반환합니다. inputtextarea 요소가 form 요소로부터 상태를 상속하는 경우, 이것은 form 요소의 자동 대문자 전환 상태를 반환하지만, 편집 가능한 영역의 요소에 대해서는 해당 편집 호스트의 자동 대문자 전환 상태를 반환하지 않습니다(해당 요소가 실제로 편집 호스트인 경우가 아니면).

설정할 수 있으며, autocapitalize 콘텐츠 속성을 설정하여 요소의 자동 대문자 전환 동작을 변경할 수 있습니다.

요소 element고유 자동 대문자 전환 힌트를 계산하려면 다음 단계를 수행하십시오:

  1. autocapitalize 콘텐츠 속성이 element에 존재하고, 값이 빈 문자열이 아닌 경우, 해당 속성의 상태를 반환합니다.

  2. element자동 대문자 전환 상속 요소이며 비어 있지 않은 폼 소유자가 있는 경우, element고유 자동 대문자 전환 힌트를 반환합니다.

  3. 기본값을 반환합니다.

autocapitalize getter 단계는 다음과 같습니다:

  1. state고유 자동 대문자 전환 힌트로 설정합니다.

  2. state기본값인 경우, 빈 문자열을 반환합니다.

  3. state없음인 경우, "none"을 반환합니다.

  4. statesentences인 경우, "sentences"를 반환합니다.

  5. state에 해당하는 키워드 값을 반환합니다.

autocapitalize setter 단계는 autocapitalize 콘텐츠 속성을 주어진 값으로 설정하는 것입니다.


텍스트 입력 방법에 대해 사용자 지정 가능한 자동 대문자 전환 기능을 지원하고 웹 개발자가 이 기능을 제어할 수 있도록 허용하려는 사용자 에이전트는 요소에 텍스트를 입력할 때 요소에 대한 사용된 자동 대문자 전환 힌트를 계산해야 합니다. 이는 요소에 텍스트를 입력할 때 권장되는 자동 대문자 전환 동작을 설명하는 자동 대문자 전환 힌트가 됩니다.

사용자 에이전트나 입력 방법은 특정 상황에서 사용된 자동 대문자 전환 힌트를 무시하거나 재정의할 수 있습니다.

요소 element에 대한 사용된 자동 대문자 전환 힌트는 다음 알고리즘을 사용하여 계산됩니다:

  1. 만약 elementinput 요소이며, 그 type 속성이 URL, 이메일 또는 비밀번호 상태 중 하나에 해당한다면 기본값을 반환합니다.

  2. 만약 elementinput 요소이거나 textarea 요소라면, element고유 자동 대문자 전환 힌트를 반환합니다.

  3. 만약 element편집 호스트이거나 편집 가능한 요소라면, element고유 자동 대문자 전환 힌트를 반환합니다.

  4. 확인: 이 단계는 절대 도달하지 않으며, 텍스트 입력은 위의 기준 중 하나에 해당하는 요소에서만 발생합니다.

6.8.8 입력 방식: inputmode 속성

사용자 에이전트는 inputmode 속성을 양식 컨트롤(예: textarea 요소의 값)에서 지원할 수 있으며, 편집 호스트 내의 요소들에서도 사용할 수 있습니다(예: contenteditable 사용).

Global_attributes/inputmode

모든 현재 엔진에서 지원됨.

Firefox95+SafariNoChrome66+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android79+Safari iOS12.2+Chrome Android?WebView Android?Samsung Internet?Opera Android?

inputmode 콘텐츠 속성은 사용자가 내용을 입력할 때 가장 도움이 될 입력 메커니즘을 지정하는 열거형 속성입니다.

키워드 설명
none 사용자 에이전트는 가상 키보드를 표시하지 않아야 합니다. 이 키워드는 자체 키보드 제어를 렌더링하는 콘텐츠에 유용합니다.
text 사용자 에이전트는 사용자의 로케일에서 텍스트 입력이 가능한 가상 키보드를 표시해야 합니다.
tel 사용자 에이전트는 전화번호 입력이 가능한 가상 키보드를 표시해야 합니다. 여기에는 0에서 9까지의 숫자 키, "#" 문자, "*" 문자가 포함되어야 합니다. 일부 로케일에서는 알파벳 기억법 레이블(예: 미국에서는 "2" 키에 A, B, C가 레이블됨)이 포함될 수 있습니다.
url 사용자 에이전트는 사용자의 로케일에서 텍스트 입력이 가능한 가상 키보드를 표시해야 하며, "/" 및 "." 문자, "www." 또는 ".com"과 같은 문자열의 빠른 입력을 돕는 키를 제공해야 합니다.
email 사용자 에이전트는 사용자의 로케일에서 텍스트 입력이 가능한 가상 키보드를 표시해야 하며, "@" 문자와 "." 문자의 입력을 돕는 키를 제공해야 합니다.
numeric 사용자 에이전트는 숫자 입력이 가능한 가상 키보드를 표시해야 합니다. 이 키워드는 PIN 입력에 유용합니다.
decimal 사용자 에이전트는 분수 숫자 입력이 가능한 가상 키보드를 표시해야 합니다. 숫자 키와 로케일의 형식 구분자가 표시되어야 합니다.
search 사용자 에이전트는 검색에 최적화된 가상 키보드를 표시해야 합니다.

HTMLElement/inputMode

모든 현재 엔진에서 지원됨.

Firefox95+Safari12.1+Chrome66+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android79+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

inputMode IDL 속성은 inputmode 콘텐츠 속성을 알려진 값으로만 제한하여 반영해야 합니다.

inputmode가 명시되지 않았거나 사용자 에이전트에서 지원되지 않는 상태인 경우, 사용자 에이전트는 표시할 기본 가상 키보드를 결정해야 합니다. 입력 type 또는 pattern 속성과 같은 맥락 정보를 사용하여 어떤 유형의 가상 키보드를 사용자에게 표시할지 결정해야 합니다.

6.8.9 입력 방식: enterkeyhint 속성

사용자 에이전트는 enterkeyhint 속성을 양식 컨트롤(예: textarea 요소의 값)에서 지원할 수 있으며, 편집 호스트 내의 요소들에서도 사용할 수 있습니다(예: contenteditable 사용).

Global_attributes/enterkeyhint

모든 현재 엔진에서 지원됨.

Firefox94+Safari13.1+Chrome77+
Opera66+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android57+

enterkeyhint 콘텐츠 속성은 가상 키보드에서 Enter 키에 대해 어떤 작업 레이블(또는 아이콘)을 표시할지를 지정하는 열거형 속성입니다. 이를 통해 작성자는 Enter 키의 표시를 사용자에게 더 유용하게 만들기 위해 사용자화할 수 있습니다.

키워드 설명
enter 사용자 에이전트는 '입력' 작업에 대한 큐를 표시해야 하며, 일반적으로 새 줄을 삽입합니다.
done 사용자 에이전트는 '완료' 작업에 대한 큐를 표시해야 하며, 일반적으로 더 이상 입력할 것이 없으며 입력 방법 편집기(IME)가 닫힙니다.
go 사용자 에이전트는 '이동' 작업에 대한 큐를 표시해야 하며, 일반적으로 사용자가 입력한 텍스트의 대상 위치로 이동합니다.
next 사용자 에이전트는 '다음' 작업에 대한 큐를 표시해야 하며, 일반적으로 사용자를 다음 텍스트 입력 필드로 이동시킵니다.
previous 사용자 에이전트는 '이전' 작업에 대한 큐를 표시해야 하며, 일반적으로 사용자를 이전 텍스트 입력 필드로 이동시킵니다.
search 사용자 에이전트는 '검색' 작업에 대한 큐를 표시해야 하며, 일반적으로 사용자가 입력한 텍스트를 검색한 결과로 이동시킵니다.
send 사용자 에이전트는 '보내기' 작업에 대한 큐를 표시해야 하며, 일반적으로 텍스트를 대상 위치로 전송합니다.

HTMLElement/enterKeyHint

모든 현재 엔진에서 지원됨.

Firefox94+Safari13.1+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android57+

enterKeyHint IDL 속성은 enterkeyhint 콘텐츠 속성을 알려진 값으로만 제한하여 반영해야 합니다.

enterkeyhint가 명시되지 않았거나 사용자 에이전트에서 지원되지 않는 상태인 경우, 사용자 에이전트는 표시할 기본 작업 레이블(또는 아이콘)을 결정해야 합니다. inputmode, type 또는 pattern 속성과 같은 맥락 정보를 사용하여 가상 키보드에 표시할 작업 레이블(또는 아이콘)을 결정해야 합니다.

6.9 페이지 내 검색

6.9.1 소개

이 섹션에서는 페이지 내 검색(find-in-page)에 대해 정의합니다. 페이지 내 검색은 사용자 에이전트가 제공하는 일반적인 메커니즘으로, 사용자가 페이지의 콘텐츠에서 특정 정보를 검색할 수 있도록 합니다.

페이지 내 검색 기능에 대한 접근은 페이지 내 검색 인터페이스를 통해 제공됩니다. 이 인터페이스는 사용자 에이전트가 제공하는 사용자 인터페이스로, 사용자가 검색할 입력과 매개변수를 지정할 수 있도록 합니다. 이 인터페이스는 단축키 또는 메뉴 선택의 결과로 나타날 수 있습니다.

페이지 내 검색 인터페이스에서 텍스트 입력과 설정의 조합이 사용자의 쿼리를 나타냅니다. 이는 일반적으로 사용자가 검색하고자 하는 텍스트와 선택적 설정(예: 검색을 전체 단어로만 제한하는 기능)을 포함합니다.

사용자 에이전트는 주어진 쿼리에 대해 페이지 콘텐츠를 처리하고, 사용자의 쿼리를 만족하는 하나 이상의 일치 항목을 식별합니다.

일치 항목 중 하나는 사용자에게 활성 일치 항목으로 식별됩니다. 이는 강조 표시되고 화면에 보이도록 스크롤됩니다. 사용자는 페이지 내 검색 인터페이스를 사용하여 활성 일치 항목을 순차적으로 탐색할 수 있습니다.

이슈 #3539는 현재 명시되지 않은 window.find() API가 페이지 내 검색(find-in-page)을 어떻게 표준화할지에 대한 논의를 추적합니다.

6.9.2 detailshidden=until-found과의 상호작용

페이지 내 검색이 일치 항목을 찾기 시작할 때, details 요소 중 open 속성이 설정되지 않은 모든 요소는 open 속성을 수정하지 않고도 두 번째 슬롯의 건너뛴 콘텐츠가 접근 가능해져야 합니다. 이를 통해 페이지 내 검색이 그 내용을 검색할 수 있게 됩니다. 마찬가지로, hidden 속성이 hidden until found 상태에 있는 모든 HTML 요소는 hidden 속성을 수정하지 않고도 건너뛴 콘텐츠가 접근 가능해져야 하며, 이를 통해 페이지 내 검색이 그 내용을 검색할 수 있게 됩니다. 페이지 내 검색이 일치 항목 검색을 마치면, details 요소 및 hidden 속성이 hidden until found 상태에 있는 요소의 콘텐츠는 다시 건너뛰어야 합니다. 이 전체 과정은 동기적으로 이루어져야 하며, 사용자가나 작성자의 코드에서 이를 관찰할 수 없습니다. [CSSCONTAIN]

페이지 내 검색이 새로운 활성 일치 항목을 선택할 때 다음 단계를 수행하십시오:

  1. node활성 일치 항목의 첫 번째 노드로 설정하십시오.

  2. node관련 글로벌 객체에 대해 전역 작업을 큐에 추가하고 다음 단계를 실행하십시오:

    1. node에 대해 상위 details 요소 표시 알고리즘을 실행하십시오.

    2. node에 대해 상위 hidden-until-found 요소 표시 알고리즘을 실행하십시오.

(이것은 추적 벡터입니다.) 페이지 내 검색이 details 요소를 자동으로 확장할 때, toggle 이벤트가 발생합니다. 페이지 내 검색에서 발생하는 별도의 scroll 이벤트와 마찬가지로, 이 이벤트는 사용자가 페이지 내 검색 대화 상자에 입력하는 내용을 페이지에서 알아내는 데 사용될 수 있습니다. 페이지가 현재 검색어와 사용자가 입력할 수 있는 모든 가능한 다음 문자를 포함하는 작은 스크롤 가능한 영역을 만들고, 브라우저가 스크롤하는 항목을 관찰하여 그 문자를 검색어에 추가하고 스크롤 가능한 영역을 업데이트하여 점진적으로 검색어를 구축할 수 있습니다. 각 가능한 다음 일치 항목을 닫힌 details 요소에 래핑하면, 페이지는 scroll 이벤트 대신 toggle 이벤트를 청취할 수 있습니다. 이 공격은 페이지 내 검색 대화 상자에 사용자가 입력하는 모든 문자를 기반으로 조치를 취하지 않음으로써 두 이벤트 모두에서 해결할 수 있습니다.

6.9.3 선택과의 상호작용

페이지 내 검색 프로세스는 문서의 컨텍스트에서 호출되며, 해당 문서의 선택 영역에 영향을 미칠 수 있습니다. 특히, 활성 일치 항목을 정의하는 범위는 현재 선택 영역을 지시할 수 있습니다. 그러나 이러한 선택 업데이트는 페이지 내 검색 프로세스 중에 다른 시간(예: 페이지 내 검색 인터페이스가 해제될 때 또는 활성 일치 항목 범위가 변경될 때)에 발생할 수 있습니다.

6.10 닫기 요청과 닫기 감시자

6.10.1 닫기 요청

사용자는 구현 정의(및 장치별) 방식으로 사용자 에이전트에 닫기 요청을 보낼 수 있습니다. 이는 사용자가 현재 화면에 표시되고 있는 팝오버, 메뉴, 대화 상자, 선택기 또는 표시 모드 등을 닫고자 한다는 것을 나타냅니다.

닫기 요청의 예시는 다음과 같습니다:

사용자 에이전트가 document document를 대상으로 하는 잠재적 닫기 요청을 받을 때, document관련 글로벌 객체에 대해 전역 작업을 큐에 추가하고 다음 닫기 요청 단계을 수행해야 합니다:

  1. 만약 document전체 화면 요소가 null이 아니면:

    1. document노드 네비게이블최상위 탐색 가능 객체활성 문서에 대해 완전히 전체 화면 종료를 실행하십시오.

    2. 반환하십시오.

    이 과정은 keydown과 같은 관련 이벤트를 트리거하지 않으며, 단지 fullscreenchange 이벤트가 나중에 발생하도록 합니다.

  2. 선택적으로, 대체 처리로 넘어갑니다.

    예를 들어, 사용자 에이전트가 현재 웹 페이지에서 반복적인 닫기 요청 인터셉션으로 인한 사용자 좌절을 감지하면 이 경로를 따를 수 있습니다.

  3. UI Events 또는 기타 관련 명세에 따라 관련 이벤트를 트리거하십시오. [UIEVENTS]

    UI Events 모델에서 관련 이벤트의 예는 사용자가 키보드에서 Esc 키를 눌렀을 때 UI Events가 트리거하는 keydown 이벤트입니다. 대부분의 키보드가 있는 플랫폼에서는 이것이 닫기 요청으로 처리되며, 이로 인해 이 닫기 요청 단계가 실행됩니다.

    모델 외부의 관련 이벤트의 예는 보조 기술이 닫기 제스처를 통해 사용자가 닫기 요청을 보낼 때 Esc keydown 이벤트를 생성하는 경우입니다.

  4. 이러한 이벤트가 발생하지 않은 경우 event를 null로 설정하거나, 발생한 이벤트를 나타내는 Event 객체를 설정합니다. 여러 이벤트가 발생한 경우, 어떤 이벤트를 선택할지는 구현 정의에 따릅니다.

  5. 만약 event가 null이 아니고, 그 취소된 플래그가 설정되어 있으면, 반환하십시오.

  6. 만약 document완전히 활성화된 상태가 아니라면, 반환하십시오.

    이 단계는 필요합니다. event가 null이 아닌 경우 이벤트 리스너가 document를 더 이상 완전히 활성화된 상태로 만들지 않았을 수 있기 때문입니다.

  7. document관련 글로벌 객체에 대해 닫기 감시자 처리의 결과로 closedSomething을 설정하십시오.

  8. 만약 closedSomething이 true이면, 반환하십시오.

  9. 대체 처리: 다른 경우에는 닫기 요청을 감시하는 것이 없었습니다. 사용자 에이전트는 이 상호작용을 닫기 요청으로 해석하는 대신 다른 작업으로 해석할 수 있습니다.

플랫폼에서 Esc 키를 누르는 것이 닫기 요청으로 해석되는 경우, 사용자 에이전트는 키가 눌려질 때 이를 닫기 요청으로 해석해야 하며, 키가 해제될 때가 아닙니다. 따라서 위 알고리즘에서 발생하는 "관련 이벤트"는 단일 keydown 이벤트여야 합니다.

Esc닫기 요청인 플랫폼에서는 사용자 에이전트가 먼저 적절히 초기화된 keydown 이벤트를 트리거합니다. 웹 개발자가 preventDefault()를 호출하여 이벤트를 취소하면 아무 일도 일어나지 않습니다. 하지만 이벤트가 취소되지 않고 발생하면 사용자 에이전트는 닫기 감시자 처리를 계속 진행합니다.

뒤로 가기 버튼이 잠재적인 닫기 요청인 플랫폼에서는 이벤트가 발생하지 않으므로, 뒤로 가기 버튼이 눌리면 사용자 에이전트는 닫기 감시자 처리를 바로 진행합니다. 만약 활성화된 닫기 감시자가 있으면 해당 감시자가 트리거됩니다. 없다면 사용자 에이전트는 뒤로 가기 버튼을 다른 방식으로 해석할 수 있습니다. 예를 들어, 히스토리를 −1만큼 탐색하는 요청으로 해석할 수 있습니다.

6.10.2 닫기 감시자 인프라

Window닫기 감시자 관리자를 가지고 있으며, 이는 다음과 같은 구조체항목들로 구성됩니다:

닫기 감시자 관리자의 복잡성 대부분은 닫기 요청대체 작업이 기록 탐색의 주요 메커니즘인 플랫폼에서 개발자가 사용자의 기록 탐색 능력을 비활성화하는 것을 방지하기 위한 악용 방지 보호 장치에서 비롯됩니다. 특히:

닫기 감시자의 그룹화는 기록 작업 활성화 없이 여러 닫기 감시자가 생성될 경우, 이들이 함께 그룹화되어 사용자에 의해 트리거된 닫기 요청이 그룹 내 모든 닫기 감시자를 닫도록 설계되었습니다. 이를 통해 웹 개발자가 닫기 감시자를 생성하여 무제한의 닫기 요청을 가로채지 못하게 합니다. 대신, 최대 1 + 사용자가 페이지를 활성화한 횟수만큼 닫기 감시자를 생성할 수 있습니다.

다음 사용자 상호작용은 새로운 그룹을 허용합니다 boolean은 웹 개발자가 개별 사용자 활성화와 연결된 방식으로 닫기 감시자를 생성하도록 유도합니다. 그렇지 않으면, 각 사용자 활성화는 허용된 그룹 수를 증가시킵니다. 요약하면:

이 보호 장치는 최대 사용자가 페이지를 활성화한 횟수 + 1개의 그룹만 생성하는 데 중요한 것은 아닙니다. 악용하려는 의도를 가진 사람은 단순히 각 사용자 상호작용마다 하나의 닫기 감시자를 생성하여 "저장"해 둘 것입니다. 그러나 이 시스템은 일반적인 경우에 더 예측 가능한 동작을 생성하고, 악용하지 않는 개발자들이 사용자 상호작용에 직접 반응하여 닫기 감시자를 생성하도록 유도합니다.

닫기 감시자 관리자에게 사용자 활성화에 대해 알리기 위해 Window window를 사용하여:

  1. managerwindow닫기 감시자 관리자로 설정하십시오.

  2. 만약 manager다음 사용자 상호작용은 새로운 그룹을 허용합니다가 true이면, manager허용된 그룹 수를 증가시키십시오.

  3. manager다음 사용자 상호작용은 새로운 그룹을 허용합니다를 false로 설정하십시오.


닫기 감시자는 다음 항목들을 가진 구조체입니다:

닫기 감시자 closeWatchercloseWatcherwindow닫기 감시자 관리자가 어떤 목록이라도 포함할 때 활성화된 상태입니다.


Window window를 사용하여 닫기 감시자처리하려면:

  1. processedACloseWatcher를 false로 설정하십시오.

  2. 만약 window닫기 감시자 관리자그룹이 비어 있지 않다면:

    1. window닫기 감시자 관리자그룹에서 마지막 항목group을 설정하십시오.

    2. 역순으로 group의 각 closeWatcher에 대해:

      1. processedACloseWatcher를 true로 설정하십시오.

      2. 닫기를 요청하여 closeWatcher의 결과를 shouldProceed로 설정하십시오.

      3. 만약 shouldProceed가 false이면 중단하십시오.

  3. 만약 window닫기 감시자 관리자허용된 그룹 수가 1보다 크면, 1을 차감하십시오.

  4. processedACloseWatcher를 반환하십시오.

6.10.3 CloseWatcher 인터페이스

[Exposed=Window]
interface CloseWatcher : EventTarget {
  constructor(optional CloseWatcherOptions options = {});

  undefined requestClose();
  undefined close();
  undefined destroy();

  attribute EventHandler oncancel;
  attribute EventHandler onclose;
};

dictionary CloseWatcherOptions {
  AbortSignal signal;
};
watcher = new CloseWatcher()
watcher = new CloseWatcher({ signal })

CloseWatcher 인스턴스를 생성합니다.

signal 옵션이 제공된 경우, 주어진 AbortSignal이 중단되면 watcher는 마치 watcher.destroy()에 의해 파괴된 것처럼 됩니다.

이미 닫기 감시자가 활성화되어 있고, Window기록 작업 활성화가 없다면, 새롭게 생성된 CloseWatcher는 이미 활성화된 닫기 감시자와 함께 닫히게 됩니다. (이 이미 활성화된 닫기 감시자는 반드시 CloseWatcher 객체일 필요는 없으며, dialog 요소나 popover 속성을 가진 요소에서 생성된 팝오버일 수도 있습니다.)

watcher.requestClose()

watcher를 대상으로 닫기 요청이 보내진 것처럼 동작합니다. 먼저 cancel 이벤트를 발생시키고, 해당 이벤트가 preventDefault()에 의해 취소되지 않은 경우 close 이벤트를 발생시키고, 마치 watcher.destroy()가 호출된 것처럼 닫기 감시자를 비활성화합니다.

이는 모든 닫기 요청이 이 메서드를 호출하도록 하여 cancelclose 이벤트 핸들러에 취소 및 닫기 로직을 통합할 수 있는 유틸리티입니다.

watcher.close()

즉시 close 이벤트를 발생시키고, 마치 watcher.destroy()가 호출된 것처럼 닫기 감시자를 비활성화합니다.

이는 close 이벤트 핸들러에서 닫기 로직을 트리거하기 위해 사용할 수 있는 유틸리티로, cancel 이벤트 핸들러의 로직을 건너뜁니다.

watcher.destroy()

watcher를 비활성화하여 더 이상 close 이벤트를 수신하지 않으며, 새로운 독립적인 CloseWatcher 인스턴스를 생성할 수 있도록 합니다.

이것은 관련 UI 요소가 다른 방식으로 닫히는 경우 호출하도록 설계되었습니다.

CloseWatcher 인스턴스는 내부 닫기 감시자를 가지고 있으며, 이는 닫기 감시자입니다.

new CloseWatcher(options) 생성자 단계는 다음과 같습니다:

  1. this관련 전역 객체연결된 문서완전히 활성화되지 않은 경우, "InvalidStateError" DOMException을 throw합니다.

  2. closeWatcher닫기 감시자 설정의 결과로 설정하며, 이는 this관련 전역 객체를 사용하여 다음을 포함합니다:

  3. options["signal"]이 존재하면:

    1. 만약 options["signal"]이 중단됨 상태라면, closeWatcher파괴합니다.

    2. options["signal"]에 다음 단계를 추가하십시오:

      1. closeWatcher파괴하십시오.

  4. this내부 닫기 감시자closeWatcher로 설정합니다.

requestClose() 메서드 단계는 닫기를 요청하여 this내부 닫기 감시자를 요청합니다.

close() 메서드 단계는 닫기하여 this내부 닫기 감시자를 닫습니다.

destroy() 메서드 단계는 파괴하여 this내부 닫기 감시자를 파괴합니다.

다음은 이벤트 핸들러와 해당 이벤트 핸들러 이벤트 유형이며, 모든 CloseWatcher 인터페이스를 구현하는 객체에 의해 지원되어야 합니다:

이벤트 핸들러 이벤트 핸들러 이벤트 유형
oncancel cancel
onclose close

사용자 제공의 닫기 요청과 닫기 버튼을 눌렀을 때 자동으로 닫히는 커스텀 피커 컨트롤을 구현하려면, 다음 코드에서 CloseWatcher API를 사용하여 닫기 요청을 처리하는 방법을 보여줍니다:

const watcher = new CloseWatcher();
const picker = setUpAndShowPickerDOMElement();

let chosenValue = null;

watcher.onclose = () => {
  chosenValue = picker.querySelector('input').value;
  picker.remove();
};

picker.querySelector('.close-button').onclick = () => watcher.requestClose();

선택된 값을 수집하는 로직이 CloseWatcher 객체의 close 이벤트 핸들러에 집중되어 있으며, 닫기 버튼의 클릭 이벤트 핸들러는 해당 로직을 호출하여 requestClose() 메서드를 호출합니다.

취소 이벤트는 CloseWatcher 객체에서 close 이벤트 발생을 막고 객체가 파괴되는 것을 방지하는 데 사용할 수 있습니다. 일반적인 사용 사례는 다음과 같습니다:

watcher.oncancel = async (e) => {
  if (hasUnsavedData && e.cancelable) {
    e.preventDefault();

    const userReallyWantsToClose = await askForConfirmation("정말로 닫으시겠습니까?");
    if (userReallyWantsToClose) {
      hasUnsavedData = false;
      watcher.close();
    }
  }
};

오용 방지 목적으로, 이 이벤트는 페이지에 히스토리 액션 활성화가 있는 경우에만 취소 가능합니다. 이는 사용자가 중간 사용자 활성화 없이 두 번 연속으로 닫기 요청을 보내면 첫 번째 요청 후 두 번째 요청이 취소 이벤트 핸들러의 preventDefault() 호출을 무시하고 닫기 요청을 처리하게 됩니다.

위의 두 예시는 requestClose() close()의 차이점을 보여줍니다. 닫기 버튼의 클릭 이벤트 핸들러에서 requestClose()를 사용했기 때문에, 이 버튼을 클릭하면 CloseWatcher 취소 이벤트가 트리거되며, 저장되지 않은 데이터가 있을 경우 사용자의 확인을 요청할 수 있습니다. 만약 close()를 사용했다면 이 확인 과정이 건너뛰어질 것입니다. 때로는 이것이 적절할 수 있지만, 보통 requestClose()가 사용자 트리거 닫기 요청에 대해 더 나은 선택입니다.

취소 이벤트의 사용자 활성화 제한 외에도, CloseWatcher 생성에 대한 더 미묘한 사용자 활성화 게이팅이 있습니다. 사용자 활성화 없이 여러 CloseWatcher를 생성하면, 새로 생성된 객체가 가장 최근에 생성된 닫기 감시자와 그룹화되어 단일 닫기 요청으로 두 객체를 모두 닫을 수 있게 됩니다:

window.onload = () => {
  // 이것은 정상적으로 작동할 것입니다: 사용자 활성화 없이 생성된 첫 번째 닫기 감시자입니다.
  (new CloseWatcher()).onclose = () => { /* ... */ };
};

button1.onclick = () => {
  // 이것은 정상적으로 작동할 것입니다: 버튼 클릭이 사용자 활성화로 간주됩니다.
  (new CloseWatcher()).onclose = () => { /* ... */ };
};

button2.onclick = () => {
  // 이들은 함께 그룹화되며, 단일 닫기 요청에 모두 응답하여 닫힙니다.
  (new CloseWatcher()).onclose = () => { /* ... */ };
  (new CloseWatcher()).onclose = () => { /* ... */ };
};

이로 인해 destroy(), close(), 또는 requestClose()를 적절하게 호출하는 것이 중요합니다. 이렇게 해야만 "자유로운" 비그룹화된 닫기 감시자 슬롯을 다시 얻을 수 있습니다. 사용자 활성화 없이 생성된 닫기 감시자는 세션 비활성화 타임아웃 대화 상자나 서버에서 발생한 긴급 알림과 같은 경우에 유용합니다.

6.11 드래그 앤 드롭

HTML_Drag_and_Drop_API

모든 현재 엔진에서 지원합니다.

Firefox3.5+ Safari3.1+ Chrome4+
Opera12+ Edge79+
Edge (Legacy)18 Internet Explorer5.5+
Firefox Android4+ Safari iOS2+ Chrome Android18+ WebView Android4.4+ Samsung Internet1.5+ Opera Android14+

이 섹션은 이벤트 기반의 드래그 앤 드롭 메커니즘을 정의합니다.

이 명세는 드래그 앤 드롭 작업이 정확히 무엇인지에 대해 정의하지 않습니다.

포인팅 장치가 있는 시각적 매체에서 드래그 작업은 마우스다운 이벤트의 기본 동작이 될 수 있으며, 이는 일련의 마우스무브 이벤트가 뒤따르고, 드롭은 마우스 버튼을 놓음으로써 트리거될 수 있습니다.

포인팅 장치 외의 입력 방식을 사용하는 경우, 사용자는 드래그 앤 드롭 작업을 수행하려는 의도를 명시적으로 나타내어 무엇을 드래그하고 어디에 드롭할 것인지 각각 명시해야 할 것입니다.

어떻게 구현되든, 드래그 앤 드롭 작업은 시작점(예: 마우스를 클릭한 위치, 선택된 드래그 요소 또는 요소의 시작 부분)을 가지고 있어야 하며, 중간 단계(드래그 중에 마우스가 지나가는 요소들 또는 사용자가 가능한 드롭 지점으로 선택하는 요소들)가 있을 수 있고, 종료 지점(마우스 버튼을 놓은 요소 또는 최종적으로 선택된 요소)이 있어야 하거나, 작업이 취소될 수 있습니다. 종료 지점은 드롭이 발생하기 전에 마지막으로 선택된 드롭 지점이어야 합니다(따라서 작업이 취소되지 않는 한, 중간 단계에 적어도 하나의 요소가 있어야 합니다).

6.11.1 소개

이 섹션은 규범적이지 않습니다.

요소를 드래그 가능하게 만들려면, 요소에 draggable 속성을 추가하고, 드래그 중인 데이터를 저장하는 dragstart 이벤트 리스너를 설정하세요.

이벤트 핸들러는 일반적으로 드래그되는 것이 텍스트 선택이 아닌지 확인한 후 DataTransfer 객체에 데이터를 저장하고, 허용된 효과(복사, 이동, 링크 또는 이들의 조합)를 설정해야 합니다.

예를 들어:

<p>당신이 좋아하는 과일은 무엇입니까?</p>
<ol ondragstart="dragStartHandler(event)">
 <li draggable="true" data-value="fruit-apple">사과</li>
 <li draggable="true" data-value="fruit-orange">오렌지</li>
 <li draggable="true" data-value="fruit-pear"></li>
</ol>
<script>
  var internalDNDType = 'text/x-example'; // 사이트에 맞는 값으로 설정
  function dragStartHandler(event) {
    if (event.target instanceof HTMLLIElement) {
      // 요소의 data-value="" 속성을 이동하려는 값으로 사용:
      event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
      event.dataTransfer.effectAllowed = 'move'; // 이동만 허용
    } else {
      event.preventDefault(); // 선택 항목이 드래그되지 않도록 방지
    } 
  } 
</script>

드롭을 허용하려면, 드롭 대상은 다음 이벤트들을 수신해야 합니다:

  1. dragenter 이벤트 핸들러는 드롭 대상이 드롭을 수락할 의사가 있는지 없는지를 이벤트를 취소함으로써 보고합니다.
  2. dragover 이벤트 핸들러는 이벤트와 연관된 dropEffect 속성을 설정하여 사용자에게 보여줄 피드백을 지정합니다. 이 이벤트도 취소해야 합니다.
  3. drop 이벤트 핸들러는 드롭을 수락하거나 거부할 수 있는 마지막 기회를 제공합니다. 드롭이 수락되면, 이벤트 핸들러는 대상에서 드롭 작업을 수행해야 합니다. 이 이벤트는 취소해야 하며, 이를 통해 dropEffect 속성의 값이 소스에서 사용될 수 있도록 해야 합니다. 그렇지 않으면 드롭 작업이 거부됩니다.

예를 들어:

<p>좋아하는 과일을 아래에 드롭하세요:</p>
<ol ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
</ol>
<script>
  var internalDNDType = 'text/x-example'; // 사이트에 맞는 값으로 설정
  function dragEnterHandler(event) {
    var items = event.dataTransfer.items;
    for (var i = 0; i < items.length; ++i) {
      var item = items[i];
      if (item.kind == 'string' && item.type == internalDNDType) {
        event.preventDefault();
        return; 
      }
    }
  }
  function dragOverHandler(event) {
    event.dataTransfer.dropEffect = 'move'; 
    event.preventDefault(); 
  } 
  function dropHandler(event) {
    var li = document.createElement('li');
    var data = event.dataTransfer.getData(internalDNDType);
    if (data == 'fruit-apple') {
      li.textContent = '사과';
    } else if (data == 'fruit-orange') {
      li.textContent = '오렌지';
    } else if (data == 'fruit-pear') {
      li.textContent = '배';
    } else {
      li.textContent = '알 수 없는 과일';
    } 
    event.target.appendChild(li); 
  } 
</script>

원본 요소(드래그된 요소)를 화면에서 제거하려면 dragend 이벤트를 사용할 수 있습니다.

여기 예제에서는 이 이벤트를 처리하기 위해 원본 마크업을 업데이트해야 합니다:

<p>당신이 좋아하는 과일은 무엇입니까?</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)">
 ...이전과 동일...
</ol>
<script> 
  function dragStartHandler(event) {
    // ...이전과 동일...
  } 
  function dragEndHandler(event) {
    if (event.dataTransfer.dropEffect == 'move') {
      // 드래그된 요소 제거
      event.target.parentNode.removeChild(event.target);
    } 
  } 
</script>

6.11.2 드래그 데이터 저장소

드래그 앤 드롭 작업의 기초가 되는 데이터, 즉 드래그 데이터 저장소는 다음 정보를 포함합니다:

드래그 데이터 저장소생성될 때, 드래그 데이터 저장소 항목 목록이 비어 있고, 드래그 데이터 저장소 기본 피드백이 없으며, 드래그 데이터 저장소 비트맵드래그 데이터 저장소 핫스팟 좌표가 없고, 드래그 데이터 저장소 모드보호 모드이며, 드래그 데이터 저장소 허용 효과 상태가 문자열 "uninitialized"로 초기화되어야 합니다.

6.11.3 DataTransfer 인터페이스

DataTransfer

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12+

DataTransfer 객체는 드래그 앤 드롭 작업을 위한 드래그 데이터 저장소를 노출하는 데 사용됩니다.

[Exposed=Window]
interface DataTransfer {
  constructor();

  attribute DOMString dropEffect;
  attribute DOMString effectAllowed;

  [SameObject] readonly attribute DataTransferItemList items;

  undefined setDragImage(Element image, long x, long y);

  /* old interface */
  readonly attribute FrozenArray<DOMString> types;
  DOMString getData(DOMString format);
  undefined setData(DOMString format, DOMString data);
  undefined clearData(optional DOMString format);
  [SameObject] readonly attribute FileList files;
};
dataTransfer = new DataTransfer()

DataTransfer/DataTransfer

모든 최신 엔진에서 지원됩니다.

Firefox62+Safari14.1+Chrome59+
Opera?Edge79+
Edge (Legacy)17+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet8.0+Opera Android44+

드래그 데이터 저장소를 사용하여 새로운 DataTransfer 객체를 생성합니다.

dataTransfer.dropEffect [ = value ]

DataTransfer/dropEffect

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

현재 선택된 작업 유형을 반환합니다. 만약 effectAllowed 속성에서 허용된 작업이 아니라면, 작업이 실패할 것입니다.

선택된 작업을 변경할 수 있습니다.

가능한 값은 "none", "copy", "link", 그리고 "move"입니다.

dataTransfer.effectAllowed [ = value ]

DataTransfer/effectAllowed

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

허용되는 작업 유형을 반환합니다.

드래그 시작(dragstart) 이벤트 동안 허용되는 작업 유형을 변경할 수 있습니다.

가능한 값은 "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", 그리고 "uninitialized"입니다.

dataTransfer.items

DataTransfer/items

모든 최신 엔진에서 지원됩니다.

Firefox50+Safari11.1+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android52+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12+

드래그 데이터를 포함한 DataTransferItemList 객체를 반환합니다.

dataTransfer.setDragImage(element, x, y)

DataTransfer/setDragImage

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 요소를 사용하여 드래그 피드백을 업데이트하며, 이전에 지정된 피드백을 대체합니다.

dataTransfer.types

DataTransfer/types

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

드래그 시작(dragstart) 이벤트에서 설정된 형식을 나열하는 고정 배열(frozen array)을 반환합니다. 또한, 파일이 드래그되고 있다면 형식 중 하나는 "Files" 문자열이 될 것입니다.

data = dataTransfer.getData(format)

DataTransfer/getData

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 데이터를 반환합니다. 해당 데이터가 없으면 빈 문자열을 반환합니다.

dataTransfer.setData(format, data)

DataTransfer/setData

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari5+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android12+

지정된 데이터를 추가합니다.

dataTransfer.clearData([ format ])

DataTransfer/clearData

모든 최신 엔진에서 지원됩니다.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

지정된 형식의 데이터를 제거합니다. 인수가 생략된 경우, 모든 데이터를 제거합니다.

dataTransfer.files

DataTransfer/files

모든 최신 엔진에서 지원됩니다.

Firefox3.6+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

드래그 중인 파일의 FileList를 반환합니다.

DataTransfer 객체는 드래그 앤 드롭 이벤트의 일부로 생성된 경우, 해당 이벤트가 발생하는 동안에만 유효합니다.

DataTransfer 객체는 유효한 동안 드래그 데이터 저장소와 연관됩니다.

DataTransfer 객체는 types 배열을 가지며, 이는 FrozenArray<DOMString>입니다. 이 배열은 초기에는 비어 있으며, DataTransfer 객체의 드래그 데이터 저장소 항목 목록의 내용이 변경되거나, 드래그 데이터 저장소와 더 이상 연관되지 않게 되면, 다음 단계를 실행합니다:

  1. L을 빈 시퀀스로 설정합니다.

  2. 만약 DataTransfer 객체가 여전히 드래그 데이터 저장소와 연관되어 있다면:

    1. DataTransfer 객체의 드래그 데이터 저장소 항목 목록에서 kindtext인 각 항목에 대해, 항목의 유형 문자열로 구성된 항목을 L에 추가합니다.

    2. 만약 DataTransfer 객체의 드래그 데이터 저장소 항목 목록kindFile인 항목이 있다면, 문자열 "Files"로 구성된 항목을 L에 추가합니다. (이 값은 다른 값들과 구분될 수 있습니다. 왜냐하면 소문자가 아니기 때문입니다.)

  3. DataTransfer 객체의 types 배열L로부터 고정 배열을 생성한 결과로 설정합니다.

DataTransfer() 생성자는 호출될 때, 다음과 같이 초기화된 새로 생성된 DataTransfer 객체를 반환해야 합니다:

  1. 드래그 데이터 저장소항목 목록을 빈 목록으로 설정합니다.

  2. 드래그 데이터 저장소모드읽기/쓰기 모드로 설정합니다.

  3. dropEffecteffectAllowed를 "none"으로 설정합니다.

dropEffect 속성은 드래그 앤 드롭 작업 중 사용자가 받는 피드백을 제어합니다. DataTransfer 객체가 생성될 때, dropEffect 속성은 문자열 값으로 설정됩니다. 가져올 때는 현재 값을 반환해야 합니다. 설정할 때, 새 값이 "none", "copy", "link", 또는 "move" 중 하나라면, 속성의 현재 값을 새 값으로 설정해야 합니다. 다른 값은 무시되어야 합니다.

effectAllowed 속성은 드래그 앤 드롭 처리 모델에서 dropEffect 속성을 dragenterdragover 이벤트 동안 초기화하는 데 사용됩니다. DataTransfer 객체가 생성될 때, effectAllowed 속성은 문자열 값으로 설정됩니다. 가져올 때는 현재 값을 반환해야 합니다. 설정할 때, 드래그 데이터 저장소모드읽기/쓰기 모드이며 새 값이 "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", 또는 "uninitialized" 중 하나라면, 속성의 현재 값을 새 값으로 설정해야 합니다. 그렇지 않으면 변경되지 않아야 합니다.

items 속성은 DataTransferItemList 객체를 DataTransfer 객체와 연관하여 반환해야 합니다.

setDragImage(image, x, y) 메서드는 다음 단계를 실행해야 합니다:

  1. DataTransfer 객체가 더 이상 드래그 데이터 저장소와 연관되지 않는 경우, 아무 일도 일어나지 않고 반환합니다.

  2. 드래그 데이터 저장소모드읽기/쓰기 모드가 아닌 경우, 아무 일도 일어나지 않고 반환합니다.

  3. imageimg 요소인 경우, 드래그 데이터 저장소 비트맵을 요소의 이미지(자연 크기에서)로 설정합니다; 그렇지 않으면, 주어진 요소로부터 생성된 이미지로 드래그 데이터 저장소 비트맵을 설정합니다 (이 메커니즘에 대한 정확한 명세는 현재 지정되지 않았습니다).

  4. 드래그 데이터 저장소 핫스팟 좌표를 주어진 x, y 좌표로 설정합니다.

types 속성은 이 DataTransfer 객체의 types 배열을 반환해야 합니다.

getData(format) 메서드는 다음 단계를 실행해야 합니다:

  1. DataTransfer 객체가 더 이상 드래그 데이터 저장소와 연관되지 않은 경우, 빈 문자열을 반환합니다.

  2. 드래그 데이터 저장소모드보호 모드인 경우, 빈 문자열을 반환합니다.

  3. 첫 번째 인수 formatASCII 소문자로 변환합니다.

  4. convert-to-URL을 false로 설정합니다.

  5. format이 "text"와 같으면 "text/plain"으로 변경합니다.

  6. format이 "url"과 같으면 "text/uri-list"로 변경하고 convert-to-URL을 true로 설정합니다.

  7. 드래그 데이터 저장소 항목 목록kindtext이고 유형 문자열format과 같은 항목이 없으면, 빈 문자열을 반환합니다.

  8. 드래그 데이터 저장소 항목 목록kindPlain Unicode string이고 유형 문자열format과 같은 항목의 데이터를 result로 설정합니다.

  9. convert-to-URL이 true인 경우, resulttext/uri-list 데이터에 적합하게 파싱한 다음, 목록에서 첫 번째 URL로 result를 설정하고, 그렇지 않으면 빈 문자열로 설정합니다. [RFC2483]

  10. result를 반환합니다.

setData(format, data) 메서드는 다음 단계를 실행해야 합니다:

  1. DataTransfer 객체가 더 이상 드래그 데이터 저장소와 연관되지 않은 경우, 아무 일도 일어나지 않고 반환합니다.

  2. 드래그 데이터 저장소모드읽기/쓰기 모드가 아닌 경우, 아무 일도 일어나지 않고 반환합니다.

  3. 첫 번째 인수 formatASCII 소문자로 변환합니다.

  4. format이 "text"와 같으면 "text/plain"으로 변경합니다.

    format이 "url"와 같으면 "text/uri-list"로 변경합니다.

  5. 드래그 데이터 저장소 항목 목록에서 kindtext이고 유형 문자열format과 같은 항목을 제거합니다.

  6. 드래그 데이터 저장소 항목 목록kindtext이고 유형 문자열format과 같으며, 메서드의 두 번째 인수로 주어진 문자열 데이터로 구성된 항목을 추가합니다.

clearData(format) 메서드는 다음 단계를 실행해야 합니다:

  1. DataTransfer 객체가 더 이상 드래그 데이터 저장소와 연관되지 않은 경우, 아무 일도 일어나지 않고 반환합니다.

  2. 드래그 데이터 저장소모드읽기/쓰기 모드가 아닌 경우, 아무 일도 일어나지 않고 반환합니다.

  3. 만약 메서드가 인수 없이 호출된 경우, 드래그 데이터 저장소 항목 목록에서 kindPlain Unicode string인 각 항목을 제거하고 반환합니다.

  4. formatformat으로 설정하고, ASCII 소문자로 변환합니다.

  5. format이 "text"와 같으면 "text/plain"으로 변경합니다.

    format이 "url"와 같으면 "text/uri-list"로 변경합니다.

  6. 드래그 데이터 저장소 항목 목록에서 kindtext이고 유형 문자열format과 같은 항목을 제거합니다.

clearData() 메서드는 드래그에 포함된 파일 여부에 영향을 미치지 않으므로, types 속성의 목록이 clearData() 호출 후에도 여전히 비어 있지 않을 수 있습니다 (드래그에 파일이 포함된 경우 여전히 "Files" 문자열을 포함할 것입니다).

files 속성은 실시간 FileList 시퀀스를 반환해야 하며, 이는 다음 단계에서 발견된 파일을 나타내는 File 객체들로 구성됩니다. 또한, 주어진 FileList 객체 및 주어진 기본 파일에 대해 매번 동일한 File 객체를 사용해야 합니다.

  1. 빈 목록 L로 시작합니다.

  2. DataTransfer 객체가 더 이상 드래그 데이터 저장소와 연관되지 않으면, FileList는 비어 있습니다. 빈 목록 L을 반환합니다.

  3. 드래그 데이터 저장소모드보호 모드인 경우, 빈 목록 L을 반환합니다.

  4. 드래그 데이터 저장소 항목 목록에서 kindFile인 각 항목에 대해, 해당 항목의 데이터(파일, 특히 그 이름과 내용, 그리고 유형)를 목록 L에 추가합니다.

  5. 이 단계에서 발견된 파일들이 목록 L에 있는 파일들입니다.

이 API 버전에서는 드래그 중 파일의 유형을 노출하지 않습니다.

6.11.3.1 DataTransferItemList 인터페이스

DataTransferItemList

모든 최신 엔진에서 지원됩니다.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

DataTransfer 객체는 DataTransferItemList 객체와 연결됩니다.

[Exposed=Window]
interface DataTransferItemList {
  readonly attribute unsigned long length;
  getter DataTransferItem (unsigned long index);
  DataTransferItem? add(DOMString data, DOMString type);
  DataTransferItem? add(File data);
  undefined remove(unsigned long index);
  undefined clear();
};
items.length

DataTransferItemList/length

모든 현재 엔진에서 지원됩니다.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

드래그 데이터 저장소의 아이템 수를 반환합니다.

items[index]

드래그 데이터 저장소index번째 항목을 나타내는 DataTransferItem 객체를 반환합니다.

items.remove(index)

DataTransferItemList/remove

모든 현재 엔진에서 지원됩니다.

Firefox50+Safari6+Chrome31+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

드래그 데이터 저장소index번째 항목을 제거합니다.

items.clear()

DataTransferItemList/clear

모든 현재 엔진에서 지원됩니다.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+

드래그 데이터 저장소의 모든 항목을 제거합니다.

items.add(data)

DataTransferItemList/add

모든 현재 엔진에서 지원됩니다.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer지원 안됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android14+
items.add(data, type)

주어진 데이터를 위한 새 항목을 드래그 데이터 저장소에 추가합니다. 데이터가 일반 텍스트인 경우 type 문자열도 제공되어야 합니다.

DataTransferItemList 객체의 DataTransfer 객체가 드래그 데이터 저장소와 연결된 동안 DataTransferItemList 객체의 모드드래그 데이터 저장소 모드와 동일합니다. DataTransferItemList 객체의 DataTransfer 객체가 드래그 데이터 저장소와 연결되지 않은 경우, DataTransferItemList 객체의 모드비활성 모드입니다. 이 섹션에서 참조된 드래그 데이터 저장소DataTransferItemList 객체의 DataTransfer 객체와 연결된 드래그 데이터 저장소입니다.

length 속성은 객체가 비활성 모드에 있을 때 0을 반환해야 하며, 그렇지 않은 경우 드래그 데이터 저장소 항목 목록에 있는 항목의 수를 반환해야 합니다.

DataTransferItemList 객체가 비활성 모드에 있지 않을 때, 지원되는 속성 인덱스인덱스입니다. 이는 드래그 데이터 저장소 항목 목록의 인덱스입니다.

인덱싱된 속성의 값을 결정하기 위해 DataTransferItemList 객체의 i 값을 드래그 데이터 저장소i번째 항목을 나타내는 DataTransferItem 객체로 반환해야 합니다. 동일한 항목이 이 DataTransferItemList 객체에서 여러 번 얻어질 때마다 동일한 객체가 반환되어야 합니다. DataTransferItem 객체는 처음 생성될 때 DataTransfer 객체와 연결되어야 합니다.

add() 메서드는 다음 단계를 수행해야 합니다:

  1. DataTransferItemList 객체가 읽기/쓰기 모드에 있지 않다면 null을 반환합니다.

  2. 다음 목록에서 적절한 단계 집합으로 이동합니다:

    메서드의 첫 번째 인수가 문자열일 경우

    이미 드래그 데이터 저장소 항목 목록종류텍스트이고 유형 문자열이 메서드의 두 번째 인수의 값과 동일한 항목이 있는 경우, "NotSupportedError" DOMException을 throw 합니다.

    그렇지 않은 경우, 드래그 데이터 저장소 항목 목록종류텍스트이고, 유형 문자열이 메서드의 두 번째 인수의 값과 동일하며, 메서드의 첫 번째 인수로 제공된 문자열 데이터를 가지는 항목을 추가합니다.

    메서드의 첫 번째 인수가 File인 경우

    드래그 데이터 저장소 항목 목록종류File이고, 유형 문자열type으로 변환된 File의 데이터와 동일한 항목을 추가합니다.

  3. 새로 추가된 항목에 해당하는 인덱싱된 속성의 값을 결정하고, 그 값을 반환합니다(새로 생성된 DataTransferItem 객체).

remove(index) 메서드는 다음 단계를 수행해야 합니다:

  1. DataTransferItemList 객체가 읽기/쓰기 모드에 있지 않다면 "InvalidStateError" DOMException을 throw 합니다.

  2. 드래그 데이터 저장소index번째 항목이 포함되어 있지 않다면, 아무런 작업도 하지 않습니다.

  3. 드래그 데이터 저장소에서 index번째 항목을 제거합니다.

clear() 메서드는 DataTransferItemList 객체가 읽기/쓰기 모드에 있을 경우, 드래그 데이터 저장소의 모든 항목을 제거해야 합니다. 그렇지 않다면, 아무런 작업도 하지 않습니다.

6.11.3.2 DataTransferItem 인터페이스

DataTransferItem

모든 최신 엔진에서 지원됨.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

DataTransferItem 객체는 DataTransfer 객체와 연결됩니다.

[Exposed=Window]
interface DataTransferItem {
  readonly attribute DOMString kind;
  readonly attribute DOMString type;
  undefined getAsString(FunctionStringCallback? _callback);
  File? getAsFile();
};

callback FunctionStringCallback = undefined (DOMString data);
item.kind

DataTransferItem/kind

모든 최신 엔진에서 지원됨.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

드래그 데이터 항목 종류, 하나: "string", "file"을 반환합니다.

item.type

DataTransferItem/type

모든 최신 엔진에서 지원됨.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

드래그 데이터 항목 유형 문자열을 반환합니다.

item.getAsString(callback)

DataTransferItem/getAsString

모든 최신 엔진에서 지원됨.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

드래그 데이터 항목 종류텍스트인 경우, 콜백을 인수로 전달된 문자열 데이터로 호출합니다.

file = item.getAsFile()

DataTransferItem/getAsFile

모든 최신 엔진에서 지원됨.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS?Chrome Android?WebView Android4+Samsung Internet?Opera Android14+

드래그 데이터 항목 종류파일인 경우, 파일 객체를 반환합니다.

DataTransferItem 객체의 DataTransfer 객체가 드래그 데이터 저장소와 연결되어 있으며 해당 드래그 데이터 저장소드래그 데이터 저장소 항목 목록에 해당 DataTransferItem 객체가 나타내는 항목이 여전히 포함되어 있는 동안, DataTransferItem 객체의 모드드래그 데이터 저장소 모드와 동일합니다. DataTransferItem 객체의 DataTransfer 객체가 드래그 데이터 저장소와 연결되어 있지 않거나, DataTransferItem 객체가 나타내는 항목이 관련 드래그 데이터 저장소 항목 목록에서 제거된 경우, DataTransferItem 객체의 모드비활성 모드가 됩니다. 이 섹션에서 참조된 드래그 데이터 저장소DataTransferItem 객체의 DataTransfer 객체와 연결된 드래그 데이터 저장소입니다.

kind 속성은 DataTransferItem 객체가 비활성 모드에 있는 경우 빈 문자열을 반환해야 합니다. 그렇지 않으면, 첫 번째 열에 항목이 나타내는 드래그 데이터 항목 종류가 포함된 행의 두 번째 열에 있는 문자열을 반환해야 합니다:

종류 문자열
텍스트 "string"
파일 "file"

type 속성은 객체가 비활성 모드에 있을 경우 빈 문자열을 반환해야 하며, 그렇지 않은 경우 DataTransferItem 객체가 나타내는 항목의 드래그 데이터 항목 유형 문자열을 반환해야 합니다.

getAsString(callback) 메서드는 다음 단계를 실행해야 합니다:

  1. callback이 null인 경우, 반환합니다.

  2. DataTransferItem 객체가 읽기/쓰기 모드 또는 읽기 전용 모드에 있지 않으면 반환합니다. 콜백은 절대 호출되지 않습니다.

  3. 드래그 데이터 항목 종류텍스트가 아닌 경우 반환합니다. 콜백은 절대 호출되지 않습니다.

  4. 그렇지 않은 경우, 항목의 실제 데이터를 전달 인수로 콜백을 호출하도록 작업을 큐에 추가합니다. 이 데이터는 DataTransferItem 객체가 나타내는 항목의 실제 데이터입니다.

getAsFile() 메서드는 다음 단계를 실행해야 합니다:

  1. DataTransferItem 객체가 읽기/쓰기 모드 또는 읽기 전용 모드에 있지 않으면 null을 반환합니다.

  2. 드래그 데이터 항목 종류파일이 아닌 경우 null을 반환합니다.

  3. 새로운 파일 객체를 반환합니다. 이 객체는 DataTransferItem 객체가 나타내는 항목의 실제 데이터를 나타냅니다.

6.11.4 DragEvent 인터페이스

DragEvent/DragEvent

모든 최신 엔진에서 지원됨.

Firefox3.5+Safari14+Chrome46+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer아니요
Firefox Android?Safari iOS아니요Chrome Android아니요WebView Android?Samsung Internet?Opera Android?

DragEvent

모든 최신 엔진에서 지원됨.

Firefox3.5+Safari14+Chrome46+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS아니요Chrome Android아니요WebView Android?Samsung Internet?Opera Android?

드래그 앤 드롭 처리 모델에는 여러 이벤트가 포함됩니다. 이들 모두는 DragEvent 인터페이스를 사용합니다.

[Exposed=Window]
interface DragEvent : MouseEvent {
  constructor(DOMString type, optional DragEventInit eventInitDict = {});

  readonly attribute DataTransfer? dataTransfer;
};

dictionary DragEventInit : MouseEventInit {
  DataTransfer? dataTransfer = null;
};
event.dataTransfer

DragEvent/dataTransfer

모든 최신 엔진에서 지원됨.

Firefox3.5+Safari14+Chrome46+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer🔰 10+
Firefox Android?Safari iOS아니요Chrome Android아니요WebView Android?Samsung Internet?Opera Android?

이벤트의 DataTransfer 객체를 반환합니다.

다른 이벤트 인터페이스와의 일관성을 위해 DragEvent 인터페이스에는 생성자가 있지만, 그다지 유용하지 않습니다. 특히, 스크립트에서 유용한 DataTransfer 객체를 생성할 방법이 없습니다. DataTransfer 객체는 드래그 앤 드롭 중 브라우저에서 조정하는 처리 및 보안 모델을 갖고 있기 때문입니다.

dataTransfer 속성은 초기화된 값을 반환해야 하며, 이벤트에 대한 컨텍스트 정보를 나타냅니다.

사용자가 특정 관련 대상과 함께, 선택적으로 특정 드래그 데이터 저장소를 사용하여 e라는 이름의 드래그 앤 드롭 이벤트를 요소에서 발생시켜야 할 때, 사용자 에이전트는 다음 단계를 수행해야 합니다:

  1. dataDragStoreWasChanged를 false로 설정합니다.
  2. 특정 관련 대상이 제공되지 않은 경우, 관련 대상을 null로 설정합니다.

  3. windowDocument 객체의 관련 글로벌 객체로 설정합니다.

  4. edragstart인 경우, 드래그 데이터 저장소 모드읽기/쓰기 모드로 설정하고, dataDragStoreWasChanged를 true로 설정합니다.

    edrop인 경우, 드래그 데이터 저장소 모드읽기 전용 모드로 설정합니다.

  5. 지정된 드래그 데이터 저장소와 연결된 새 DataTransfer 객체를 생성합니다.

  6. effectAllowed 속성을 드래그 데이터 저장소허용된 드래그 데이터 저장소 효과 상태로 설정합니다.

  7. edragstart, drag, 또는 dragleave인 경우, dropEffect 속성을 "none"로 설정합니다. edrop 또는 dragend인 경우, 현재의 드래그 작업에 해당하는 값으로 설정합니다. edragenter 또는 dragover인 경우, effectAllowed 속성의 값과 드래그 앤 드롭 소스에 기반한 값을 사용하여 설정합니다.

    effectAllowed dropEffect
    "none" "none"
    "copy" "copy"
    "copyLink" "copy", 또는, 적절한 경우, "link"
    "copyMove" "copy", 또는, 적절한 경우, "move"
    "all" "copy", 또는, 적절한 경우, "link" 또는 "move"
    "link" "link"
    "linkMove" "link", 또는, 적절한 경우, "move"
    "move" "move"
    "uninitialized" 텍스트 컨트롤에서 선택한 항목을 드래그하는 경우 "move", 또는, 적절한 경우, "copy" 또는 "link"
    "uninitialized" 선택한 항목을 드래그하는 경우 "copy", 또는, 적절한 경우, "link" 또는 "move"
    "uninitialized" a 요소와 href 속성을 포함하여 드래그하는 경우 "link", 또는, 적절한 경우, "copy" 또는 "move"
    기타 모든 경우 "copy", 또는, 적절한 경우, "link" 또는 "move"

    위 표에서 적절한 경우로 제공된 경우, 사용자 에이전트는 플랫폼 관행이 사용자가 이러한 대체 효과를 요청한 경우 대체 값을 사용할 수 있습니다.

    예를 들어, Windows 플랫폼 관행에서는 "alt" 키를 누른 상태에서 드래그하면 데이터를 이동하거나 복사하는 대신 연결하려는 의도를 나타냅니다. 따라서 Windows 시스템에서 위의 표에 따라 "link"가 옵션인 경우 "alt" 키가 눌린 상태에서 사용자 에이전트는 "copy" 또는 "move" 대신 "link"를 선택할 수 있습니다.

  8. event이벤트 생성의 결과로 설정합니다.

  9. eventtype 속성을 e로 초기화하고, bubbles 속성을 true로, view 속성을 window로, relatedTarget 속성을 관련 대상으로, dataTransfer 속성을 dataTransfer로 초기화합니다.

  10. edragleave 또는 dragend가 아닌 경우, eventcancelable 속성을 true로 초기화합니다.

  11. event의 마우스 및 키 속성을 초기화하여 사용자가 상호작용할 때의 입력 장치 상태에 맞게 초기화합니다.

    관련 포인팅 장치가 없는 경우, eventscreenX, screenY, clientX, clientY, 및 button 속성을 0으로 초기화합니다.

  12. event를 지정된 대상 요소에서 디스패치합니다.

  13. 드래그 데이터 저장소 허용된 효과 상태를 현재 dataTransfereffectAllowed 속성의 값으로 설정합니다. (이 값은 edragstart인 경우에만 변경될 수 있습니다.)

  14. dataDragStoreWasChanged가 true인 경우, 드래그 데이터 저장소 모드보호 모드로 되돌립니다.

  15. dataTransfer드래그 데이터 저장소 간의 연관성을 끊습니다.

6.11.5 처리 모델

사용자가 드래그 작업을 시작하려고 할 때, 사용자 에이전트는 다음 단계를 실행해야 합니다. 드래그가 다른 문서나 애플리케이션에서 시작되었고 사용자 에이전트가 드래그가 사용자 에이전트의 관리 범위 내의 문서와 교차할 때까지 드래그가 발생하고 있다는 사실을 인식하지 못한 경우에도 사용자 에이전트는 이러한 단계를 실행해야 합니다.

  1. 드래그 중인 항목을 다음과 같이 결정합니다:

    드래그 작업이 선택 영역에서 호출된 경우, 드래그 중인 항목은 선택 영역입니다.

    그렇지 않으면, 드래그 작업이 Document에서 호출된 경우, 드래그 중인 항목은 사용자가 드래그하려고 했던 노드에서 시작하여 상위로 올라가는 조상 체인에서 draggable IDL 속성이 true로 설정된 첫 번째 요소입니다. 그러한 요소가 없으면, 아무것도 드래그되지 않습니다. 드래그 앤 드롭 작업은 시작되지 않습니다.

    그렇지 않으면, 드래그 작업이 사용자 에이전트의 관리 범위 밖에서 호출되었습니다. 드래그 중인 항목은 드래그가 시작된 문서나 애플리케이션에서 정의됩니다.

    img 요소와 a 요소는 href 속성이 있을 때 draggable 속성이 기본적으로 true로 설정됩니다.

  2. 드래그 데이터 저장소를 생성합니다. 이 섹션의 단계에서 이후에 발생하는 모든 DND 이벤트는 이 드래그 데이터 저장소를 사용해야 합니다.

  3. 어떤 DOM 노드가 소스 노드인지 설정합니다:

    드래그 중인 항목이 선택 영역인 경우, 소스 노드는 사용자가 드래그를 시작한 Text 노드입니다 (일반적으로 사용자가 처음 클릭한 Text 노드). 사용자가 특정 노드를 지정하지 않은 경우, 예를 들어 사용자가 "선택 영역"의 드래그를 시작하라고 사용자 에이전트에게 지시한 경우, 소스 노드는 선택 영역의 일부를 포함하는 첫 번째 Text 노드입니다.

    그렇지 않으면, 드래그 중인 항목이 요소인 경우, 소스 노드는 드래그 중인 요소입니다.

    그렇지 않으면, 소스 노드는 다른 문서나 애플리케이션의 일부입니다. 이 경우 사양에서 소스 노드에서 이벤트를 디스패치하도록 요구하는 경우, 사용자 에이전트는 대신 해당 상황과 관련된 플랫폼별 규칙을 따라야 합니다.

    드래그 앤 드롭 작업 중에 소스 노드에서 여러 이벤트가 발생합니다.

  4. 드래그된 노드 목록을 다음과 같이 결정합니다:

    드래그 중인 항목이 선택 영역인 경우, 드래그된 노드 목록에는 트리 순서에 따라 선택 영역에 부분적으로 또는 완전히 포함된 모든 노드(및 그 모든 조상)가 포함됩니다.

    그렇지 않으면, 드래그된 노드 목록에는 소스 노드만 포함됩니다.

  5. 드래그 중인 항목이 선택 영역인 경우, 드래그 데이터 저장소 항목 목록에 다음 속성으로 항목을 추가합니다:

    드래그 데이터 항목 유형 문자열
    "text/plain"
    드래그 데이터 항목 종류
    텍스트
    실제 데이터
    선택한 텍스트

    그렇지 않으면, 파일이 드래그 중인 경우, 드래그 데이터 저장소 항목 목록에 파일당 하나씩 항목을 추가하고, 다음 속성으로 설정합니다:

    드래그 데이터 항목 유형 문자열
    파일의 MIME 유형이 알려진 경우 해당 유형, 그렇지 않으면 "application/octet-stream"
    드래그 데이터 항목 종류
    파일
    실제 데이터
    파일의 내용과 이름

    현재 파일 드래그는 파일 시스템 관리자 애플리케이션과 같이 외부에서만 발생할 수 있습니다.

    드래그가 애플리케이션 외부에서 시작된 경우, 사용자 에이전트는 플랫폼 규칙을 준수하여 적절하게 드래그 데이터 저장소 항목 목록에 항목을 추가해야 합니다. 그러나 플랫폼 규칙이 드래그된 데이터를 레이블링하는 데 MIME 유형을 사용하지 않는 경우, 사용자 에이전트는 해당 유형을 MIME 유형으로 매핑하기 위해 최선을 다해야 하며, 어떤 경우에도 드래그 데이터 항목 유형 문자열은 모두 ASCII 소문자로 변환되어야 합니다.

    사용자 에이전트는 선택 영역 또는 드래그된 요소를 HTML 등의 다른 형식으로 나타내는 하나 이상의 항목을 추가할 수도 있습니다.

  6. 드래그된 노드 목록이 비어 있지 않다면, 해당 노드에서 마이크로데이터를 추출하여 JSON 형식으로 변환하고, 드래그 데이터 저장소 항목 목록에 다음 속성으로 항목을 추가합니다:

    드래그 데이터 항목 유형 문자열
    application/microdata+json
    드래그 데이터 항목 종류
    텍스트
    실제 데이터
    생성된 JSON 문자열
  7. 다음 하위 단계를 실행합니다:

    1. urls을 « »로 설정합니다.

    2. 드래그된 노드 목록의 각 node에 대해 다음을 실행합니다:

      노드가 a 요소이며 href 속성이 있는 경우
      해당 요소의 href 속성 값을 주어진 URL 인코딩, 파싱 및 직렬화의 결과를 urls에 추가합니다. 요소의 노드 문서를 기준으로 합니다.
      노드가 img 요소이며 src 속성이 있는 경우
      해당 요소의 src 속성 값을 주어진 URL 인코딩, 파싱 및 직렬화의 결과를 urls에 추가합니다. 요소의 노드 문서를 기준으로 합니다.
    3. urls이 여전히 비어 있으면 반환합니다.

    4. url stringurls에 있는 문자열을 추가한 결과로 설정하고, 추가된 순서대로 U+000D 캐리지 리턴 U+000A 줄 바꿈 문자 쌍 (CRLF)로 구분합니다.

    5. 드래그 데이터 저장소 항목 목록에 다음 속성으로 항목을 추가합니다:

      드래그 데이터 항목 유형 문자열
      text/uri-list
      드래그 데이터 항목 종류
      텍스트
      실제 데이터
      url string
  8. 사용자 에이전트에 적절한 드래그 데이터 저장소 기본 피드백을 업데이트합니다 (사용자가 선택 영역을 드래그하는 경우, 이 선택 영역이 피드백의 기준이 될 가능성이 높습니다. 사용자가 요소를 드래그하는 경우, 해당 요소의 렌더링이 사용됩니다. 드래그가 사용자 에이전트 외부에서 시작된 경우, 드래그 피드백을 결정하는 플랫폼 규칙을 사용해야 합니다).

  9. DND 이벤트를 발생시킵니다 명명된 dragstart소스 노드에서 발생시킵니다.

    이벤트가 취소된 경우, 드래그 앤 드롭 작업이 발생하지 않습니다; 반환합니다.

    이벤트 리스너가 등록되지 않은 이벤트는 거의 정의상 취소되지 않기 때문에, 작성자가 이를 명시적으로 방지하지 않는 한 사용자는 항상 드래그 앤 드롭을 사용할 수 있습니다.

  10. 포인터 이벤트를 발생시킵니다 소스 노드에서 명명된 pointercancel를 발생시키고, 필요한 경우 Pointer Events에서 요구하는 후속 이벤트를 발생시킵니다. [POINTEREVENTS]

  11. 드래그 앤 드롭 작업을 시작합니다 플랫폼 규칙에 따라 일관된 방식으로 시작하고, 아래에 설명된 대로 수행합니다.

    드래그 앤 드롭 피드백은 다음과 같은 소스 중 사용할 수 있는 첫 번째 소스에서 생성해야 합니다:

    1. 있다면, 드래그 데이터 저장소 비트맵에서 가져옵니다. 이 경우, 드래그 데이터 저장소 핫 스팟 좌표를 사용하여 결과 이미지에 상대적으로 커서를 어디에 배치할지에 대한 힌트로 사용해야 합니다. 값은 각각 이미지의 왼쪽 측면과 위쪽 측면에서의 거리(단위: CSS 픽셀)로 표현됩니다. [CSS]
    2. 드래그 데이터 저장소 기본 피드백.

사용자 에이전트가 드래그 앤 드롭 작업을 시작해야 하는 순간부터 드래그 앤 드롭 작업이 끝날 때까지 장치 입력 이벤트(예: 마우스 및 키보드 이벤트)는 억제되어야 합니다.

드래그 작업 중에 사용자가 드롭 대상으로 직접 선택한 요소를 즉시 사용자 선택이라고 합니다. (요소만 사용자가 선택할 수 있으며, 다른 노드는 드롭 대상이 될 수 없습니다.) 그러나 즉시 사용자 선택이 반드시 현재 대상 요소인 것은 아닙니다. 현재 대상 요소는 드래그 앤 드롭 작업의 드롭 부분에 현재 선택된 요소입니다.

즉시 사용자 선택은 사용자가 다른 요소를 선택할 때마다(포인팅 장치로 가리키거나 다른 방법으로 선택함) 변경됩니다. 현재 대상 요소즉시 사용자 선택이 변경될 때, 아래 설명된 대로 문서 내 이벤트 리스너의 결과에 따라 변경됩니다.

현재 대상 요소즉시 사용자 선택은 모두 null일 수 있으며, 이는 선택된 대상 요소가 없음을 의미합니다. 이들은 또한 다른 (DOM 기반) 문서 또는 전혀 다른 (웹이 아닌) 프로그램의 요소일 수 있습니다. (예를 들어, 사용자가 텍스트를 워드 프로세서로 드래그할 수 있습니다.) 현재 대상 요소는 처음에 null입니다.

또한 현재 드래그 작업이라는 것도 있으며, 이는 "none", "copy", "link", "move"의 값을 가질 수 있습니다. 처음에는 "none" 값을 가지며, 아래 단계에서 설명된 대로 사용자 에이전트에 의해 업데이트됩니다.

사용자 에이전트는 드래그 작업이 시작된 즉시 및 이후로 드래그 작업이 진행되는 동안 매 350ms(±200ms)마다 작업을 큐에 추가하여 다음 단계를 순서대로 수행해야 합니다.

  1. 사용자 에이전트가 이전 반복의 단계를 여전히 수행 중인 상태에서 다음 반복이 예정된 경우, 이 반복은 건너뜁니다(즉, 드래그 앤 드롭 작업의 "누락된 프레임"을 건너뜁니다).

  2. DND 이벤트를 발생시킵니다 명명된 drag소스 노드에서 발생시킵니다. 이 이벤트가 취소된 경우, 사용자 에이전트는 현재 드래그 작업을 "none"(드래그 작업 없음)으로 설정해야 합니다.

  3. drag 이벤트가 취소되지 않았고 사용자가 드래그 앤 드롭 작업을 종료하지 않은 경우, 드래그 앤 드롭 작업의 상태를 다음과 같이 확인합니다.

    1. 사용자가 마지막 반복(또는 첫 번째 반복) 동안과 다른 즉시 사용자 선택을 가리키고 있으며, 이 즉시 사용자 선택현재 대상 요소와 같지 않은 경우, 현재 대상 요소를 다음과 같이 업데이트합니다.

      새로운 즉시 사용자 선택이 null인 경우

      현재 대상 요소도 null로 설정합니다.

      새로운 즉시 사용자 선택이 비DOM 문서 또는 애플리케이션에 있는 경우

      현재 대상 요소즉시 사용자 선택으로 설정합니다.

      그 외의 경우

      DND 이벤트를 발생시킵니다 명명된 dragenter즉시 사용자 선택에서 발생시킵니다.

      이벤트가 취소된 경우, 현재 대상 요소즉시 사용자 선택으로 설정합니다.

      그렇지 않은 경우, 다음 목록에서 적절한 단계를 실행합니다.

      즉시 사용자 선택이 텍스트 컨트롤(예: textarea 또는 input 요소의 type 속성이 Text 상태에 있는 경우) 또는 편집 호스트 또는 편집 가능한 요소이며, 드래그 데이터 저장소 항목 목록에 "text/plain"의 드래그 데이터 항목 종류를 가진 항목이 있는 경우

      현재 대상 요소즉시 사용자 선택으로 설정합니다.

      즉시 사용자 선택본문 요소인 경우

      현재 대상 요소를 변경하지 않습니다.

      그 외의 경우

      DND 이벤트를 발생시킵니다 명명된 dragenter본문 요소에서 발생시킵니다. 본문 요소가 없는 경우, document 객체에서 발생시킵니다. 그런 다음, 현재 대상 요소본문 요소로 설정합니다.

    2. 이전 단계에서 현재 대상 요소가 변경된 경우, 그리고 이전 대상 요소가 null이 아니거나 비DOM 문서의 일부가 아닌 경우, DND 이벤트를 발생시킵니다 명명된 dragleave를 이전 대상 요소에서 발생시킵니다. 이때 새로운 현재 대상 요소를 특정 관련 대상으로 설정합니다.

    3. 현재 대상 요소가 DOM 요소인 경우, DND 이벤트를 발생시킵니다 명명된 dragover를 이 현재 대상 요소에서 발생시킵니다.

      이벤트 dragover가 취소되지 않은 경우, 다음 목록에서 적절한 단계를 실행합니다.

      현재 대상 요소가 텍스트 컨트롤(예: textarea 또는 input 요소의 type 속성이 Text 상태에 있는 경우) 또는 편집 호스트 또는 편집 가능한 요소이며, 드래그 데이터 저장소 항목 목록에 "text/plain"의 드래그 데이터 항목 종류를 가진 항목이 있는 경우

      현재 드래그 작업을 "copy" 또는 "move" 중 적절한 것으로 설정합니다. 이는 플랫폼 관행에 따라 달라질 수 있습니다.

      그 외의 경우

      현재 드래그 작업을 "none"으로 재설정합니다.

      그렇지 않은 경우(즉, dragover 이벤트가 취소된 경우), 현재 드래그 작업을 이벤트 디스패치가 완료된 후의 effectAlloweddropEffect 속성의 값을 기반으로 설정합니다.

      effectAllowed dropEffect 드래그 작업
      "uninitialized", "copy", "copyLink", "copyMove", 또는 "all" "copy" "copy"
      "uninitialized", "link", "copyLink", "linkMove", 또는 "all" "link" "link"
      "uninitialized", "move", "copyMove", "linkMove", 또는 "all" "move" "move"
      다른 모든 경우 "none"
    4. 현재 대상 요소가 DOM 요소가 아닌 경우, 플랫폼별 메커니즘을 사용하여 수행 중인 드래그 작업이 무엇인지(없음, 복사, 링크 또는 이동)를 결정하고, 현재 드래그 작업을 적절히 설정합니다.

    5. 현재 드래그 작업에 맞게 드래그 피드백(예: 마우스 커서)을 업데이트합니다.

      드래그 작업 피드백
      "copy" 여기에 드롭하면 데이터가 복사됩니다.
      "link" 여기에 드롭하면 데이터가 링크됩니다.
      "move" 여기에 드롭하면 데이터가 이동됩니다.
      "none" 허용되지 않은 작업입니다. 여기에 드롭하면 드래그 앤 드롭 작업이 취소됩니다.
    6. 그렇지 않은 경우, 사용자가 드래그 앤 드롭 작업을 종료한 경우(예: 마우스 기반 드래그 앤 드롭 인터페이스에서 마우스 버튼을 놓는 경우) 또는 drag 이벤트가 취소된 경우, 이는 마지막 반복이 됩니다. 다음 단계를 실행한 후 드래그 앤 드롭 작업을 중지합니다.

      1. 현재 드래그 작업이 "none"인 경우(드래그 작업 없음), 또는 사용자가 드래그 앤 드롭 작업을 취소하여 종료한 경우(예: Escape 키를 눌러서), 또는 현재 대상 요소가 null인 경우, 드래그 작업이 실패한 것입니다. 다음 하위 단계를 실행합니다.

        1. dropped를 false로 설정합니다.

        2. 현재 대상 요소가 DOM 요소인 경우, DND 이벤트를 발생시킵니다 명명된 dragleave를 발생시킵니다. 그렇지 않은 경우, null이 아닌 경우, 플랫폼별 관행에 따라 드래그 취소를 수행합니다.

        3. 현재 드래그 작업을 "none"으로 설정합니다.

        그렇지 않은 경우, 드래그 작업이 성공할 수 있습니다. 다음 하위 단계를 실행합니다.

        1. dropped를 true로 설정합니다.

        2. 현재 대상 요소가 DOM 요소인 경우, DND 이벤트를 발생시킵니다 명명된 drop를 발생시킵니다. 그렇지 않은 경우, 드롭을 나타내는 플랫폼별 관행을 따릅니다.

        3. 이벤트가 취소된 경우, 현재 드래그 작업dropEffect 속성의 값으로 설정합니다. 이 값은 이벤트 디스패치가 완료된 후의 DragEvent 객체의 dataTransfer 객체의 속성입니다.

        4. 그렇지 않은 경우, 이벤트가 취소되지 않은 경우, 이벤트의 기본 작업을 수행합니다. 이는 정확한 대상에 따라 달라집니다.

          현재 대상 요소가 텍스트 컨트롤(예: textarea, 또는 input 요소의 type 속성이 Text 상태에 있는 경우) 또는 편집 호스트 또는 편집 가능한 요소이며, 드래그 데이터 저장소 항목 목록에 "text/plain"의 드래그 데이터 항목 종류를 가진 항목이 있는 경우

          해당 텍스트 컨트롤 또는 편집 호스트 또는 편집 가능한 요소에 "드래그 데이터 저장소 항목 목록"에 포함된 첫 번째 항목의 실제 데이터를 삽입합니다.

          그 외의 경우

          현재 드래그 작업을 "none"으로 재설정합니다.

      2. DND 이벤트를 발생시킵니다 명명된 dragend소스 노드에서 발생시킵니다.

      3. 다음 목록에서 적절한 단계를 실행하여 dragend 이벤트의 기본 작업을 수행합니다.

        dropped가 true이고, 현재 대상 요소텍스트 컨트롤 (아래 참조)이며, 현재 드래그 작업이 "move"이고, 드래그 앤 드롭 작업의 소스가 편집 호스트 내에 완전히 포함된 DOM의 선택 영역인 경우

        선택 영역 삭제를 수행합니다.

        dropped가 true이고, 현재 대상 요소텍스트 컨트롤 (아래 참조)이며, 현재 드래그 작업이 "move"이고, 드래그 앤 드롭 작업의 소스가 텍스트 컨트롤 내의 선택 영역인 경우

        사용자 에이전트는 해당 텍스트 컨트롤에서 드래그된 선택 영역을 삭제해야 합니다.

        dropped가 false이거나, 현재 드래그 작업이 "none"인 경우

        드래그가 취소되었습니다. 플랫폼 관행에 따라 이것이 사용자에게 나타내어져야 하는 경우(예: 드래그된 선택 영역이 드래그 앤 드롭 작업의 소스로 돌아가는 애니메이션), 그렇게 수행합니다.

        그 외의 경우

        이벤트에는 기본 작업이 없습니다.

        이 단계의 목적을 위해, 텍스트 컨트롤textarea 요소 또는 input 요소로서, type 속성이 다음 상태 중 하나에 있는 요소를 의미합니다: Text, Search, Tel, URL, Email, Password, 또는 Number 상태입니다.

사용자 에이전트는 스크롤 가능한 영역의 가장자리에 가까운 드래그에 대해 어떻게 반응할지 고려하는 것이 좋습니다. 예를 들어, 사용자가 긴 페이지의 뷰포트 하단으로 링크를 드래그하는 경우, 사용자가 페이지 하단에 링크를 드롭할 수 있도록 페이지를 스크롤하는 것이 적절할 수 있습니다.

이 모델은 관련된 노드가 어느 document 객체에서 왔는지와 무관하게 작동합니다. 이벤트는 위에서 설명한 대로 발생하며, 처리 모델의 나머지 부분은 드래그 앤 드롭 작업에 몇 개의 문서가 관련되어 있는지와 무관하게 위에서 설명한 대로 실행됩니다.

6.11.6 이벤트 요약

이 섹션은 규범적이지 않습니다.

다음 이벤트들은 드래그 앤 드롭 모델에 관련됩니다.

이벤트 이름 타겟 취소 가능? 드래그 데이터 저장소 모드 dropEffect 기본 동작
dragstart

HTMLElement/dragstart_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
소스 노드 ✓ 취소 가능 읽기/쓰기 모드 "없음" 드래그 앤 드롭 작업 시작
drag

HTMLElement/drag_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
소스 노드 ✓ 취소 가능 보호 모드 "없음" 드래그 앤 드롭 작업 계속
dragenter

HTMLElement/dragenter_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
즉각적인 사용자 선택 또는 바디 요소 ✓ 취소 가능 보호 모드 effectAllowed 값에 따라 즉각적인 사용자 선택을 잠재적인 타겟 요소로 거부
dragleave

HTMLElement/dragleave_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
이전 타겟 요소 보호 모드 "없음" 없음
dragover

HTMLElement/dragover_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
현재 타겟 요소 ✓ 취소 가능 보호 모드 effectAllowed 값에 따라 현재 드래그 작업을 "없음"으로 재설정
drop

HTMLElement/drop_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
현재 타겟 요소 ✓ 취소 가능 읽기 전용 모드 현재 드래그 작업 다양함
dragend

HTMLElement/dragend_event

모든 현재 엔진에서 지원됩니다.

Firefox9+ Safari3.1+ Chrome1+
Opera12+ Edge79+
Edge (Legacy)12+ Internet Explorer9+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12+
소스 노드 보호 모드 현재 드래그 작업 다양함

이 모든 이벤트는 버블링되고, 구성되며, effectAllowed 속성은 항상 dragstart 이벤트 후에 가졌던 값을 유지하며, uninitialized 기본값을 dragstart 이벤트에서 사용합니다.

6.11.7 draggable 속성

Global_attributes/draggable

모든 현재 엔진에서 지원됩니다.

Firefox2+Safari5+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

모든 HTML 요소에는 draggable 콘텐츠 속성을 설정할 수 있습니다. draggable 속성은 다음 키워드와 상태를 가진 열거형 속성입니다:

키워드 상태 간략한 설명
true true 요소는 드래그할 수 있습니다.
false false 요소는 드래그할 수 없습니다.

속성의 값이 없는 경우 기본값잘못된 값 기본값은 모두 auto 상태입니다. auto 상태는 사용자 에이전트의 기본 동작을 사용합니다.

draggable 속성이 있는 요소는 비시각적 상호작용을 위한 이름을 지정하는 title 속성도 있어야 합니다.

element.draggable [ = value ]

요소가 드래그 가능하면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

기본값을 재정의하고 draggable 콘텐츠 속성을 설정하도록 설정할 수 있습니다.

draggable IDL 속성은 콘텐츠 속성의 값에 따라 달라지며, 요소가 드래그 가능 여부를 제어합니다. 일반적으로 텍스트 선택만 드래그할 수 있지만, draggable IDL 속성이 true로 설정된 요소도 드래그할 수 있습니다.

요소의 draggable 콘텐츠 속성이 true 상태인 경우, draggable IDL 속성은 true를 반환해야 합니다.

그렇지 않은 경우, 요소의 draggable 콘텐츠 속성이 false 상태인 경우, draggable IDL 속성은 false를 반환해야 합니다.

그 외의 경우, 요소의 draggable 콘텐츠 속성은 auto 상태를 가집니다. 요소가 img 요소이거나, 이미지를 대표하는 object 요소 또는 a 요소로서 href 콘텐츠 속성을 가진 경우, draggable IDL 속성은 true를 반환해야 하며, 그렇지 않은 경우 draggable IDL 속성은 false를 반환해야 합니다.

draggable IDL 속성이 false 값으로 설정된 경우, draggable 콘텐츠 속성은 문자 그대로 "false" 값으로 설정되어야 합니다. draggable IDL 속성이 true 값으로 설정된 경우, draggable 콘텐츠 속성은 문자 그대로 "true" 값으로 설정되어야 합니다.

6.11.8 드래그 앤 드롭 모델의 보안 위험

사용자 에이전트는 DataTransfer 객체에 추가된 데이터를 dragstart 이벤트 동안 스크립트에 제공해서는 안 됩니다. 그렇지 않으면 사용자가 한 문서에서 두 번째 문서로 민감한 정보를 드래그하는 동안, 적대적인 세 번째 문서를 지나가는 경우, 적대적인 문서가 데이터를 가로챌 수 있기 때문입니다.

같은 이유로, 사용자 에이전트는 사용자가 드래그 작업을 명시적으로 종료한 경우에만 드롭을 성공한 것으로 간주해야 합니다. 스크립트가 드래그 작업을 종료하면 실패한 것으로 간주되어야 하며, drop 이벤트가 발생해서는 안 됩니다.

사용자 에이전트는 스크립트 작업에 대한 응답으로 드래그 앤 드롭 작업을 시작하지 않도록 주의해야 합니다. 예를 들어, 마우스와 윈도우 환경에서 스크립트가 사용자가 마우스 버튼을 누르고 있는 동안 윈도우를 이동시키면, UA는 이를 드래그 시작으로 간주하지 않습니다. 이는 그렇지 않을 경우 UA가 사용자의 동의 없이 민감한 소스에서 데이터를 드래그하여 적대적인 문서로 드롭할 수 있기 때문에 중요합니다.

사용자 에이전트는 드래그와 드롭 시 잠재적으로 활성화될 수 있는(스크립트가 포함된) 콘텐츠(예: HTML)를 알려진 안전한 기능의 허용 목록을 사용하여 필터링해야 합니다. 마찬가지로, 상대적 URL은 예상치 못한 방식으로 참조가 변경되지 않도록 절대적 URL로 변환해야 합니다. 이 명세는 이 작업이 수행되는 방식을 명시하지 않습니다.

적대적인 페이지가 일부 콘텐츠를 제공하고 사용자가 그 콘텐츠를 선택하여 드래그 앤 드롭(또는 복사 및 붙여넣기)하도록 유도하는 경우를 고려해 보십시오. 브라우저가 안전한 콘텐츠만 드래그되도록 보장하지 않으면, 선택된 항목에 포함된 스크립트와 이벤트 핸들러와 같은 잠재적으로 안전하지 않은 콘텐츠가 피해자 사이트에 드롭(또는 붙여넣기)된 후 피해자 사이트의 권한을 얻게 됩니다. 이는 크로스 사이트 스크립팅 공격을 가능하게 합니다.

6.12 popover 속성

Global_attributes/popover

모든 최신 엔진에서 지원됩니다.

Firefox🔰 114+Safaripreview+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet Explorer없음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

모든 HTML 요소popover 콘텐츠 속성을 설정할 수 있습니다. 지정되면 요소는 표시될 때까지 렌더링되지 않으며, 표시되는 순간 다른 페이지 콘텐츠 위에 렌더링됩니다.

popover 속성은 글로벌 속성이며, 작가들이 팝오버 기능을 가장 적합한 의미론적 요소에 적용할 수 있도록 유연성을 제공합니다.

다음은 웹사이트의 글로벌 내비게이션 내에 팝오버 하위 내비게이션 링크 목록을 만드는 방법을 보여줍니다.

<ul>
  <li>
    <a href=...>All Products</a>
    <button popovertarget=sub-nav>
     <img src=down-arrow.png alt="Product pages">
    </button>
    <ul popover id=sub-nav>
     <li><a href=...>Shirts</a>
     <li><a href=...>Shoes</a>
     <li><a href=...>Hats etc.</a>
    </ul>
  </li>
  <!-- 여기에 다른 목록 항목과 링크 추가 -->
</ul>

popover 속성을 접근성 의미론이 없는 요소에 사용할 때, 예를 들어 div 요소에서는 적절한 ARIA 속성을 사용하여 팝오버가 접근 가능하도록 해야 합니다.

다음은 사용자 정의 메뉴 팝오버를 생성하기 위한 기본 마크업을 보여줍니다. 이 경우, autofocus 속성 덕분에 팝오버가 호출될 때 첫 번째 메뉴 항목이 키보드 포커스를 받습니다. 화살표 키와 활성화 동작을 사용하여 메뉴 항목을 탐색하는 것은 여전히 작성자의 스크립팅이 필요합니다. 사용자 정의 메뉴 위젯을 빌드하기 위한 추가 요구 사항은 WAI-ARIA 사양에 정의되어 있습니다.

<button popovertarget=m>Actions</button>
<div role=menu id=m popover>
  <button role=menuitem tabindex=-1 autofocus>Edit</button>
  <button role=menuitem tabindex=-1>Hide</button>
  <button role=menuitem tabindex=-1>Delete</button>
</div>

팝오버는 사용자가 수행한 작업을 확인하는 상태 메시지를 렌더링하는 데 유용할 수 있습니다. 다음은 output 요소에서 팝오버를 표시하는 방법을 보여줍니다.

<button id=submit>Submit</button>
<p><output><span popover=manual></span></output></p>

<script>
 const sBtn = document.getElementById("submit");
 const outSpan = document.querySelector("output [popover=manual]");
 let successMessage;
 let errorMessage;

 /* 작업 성공 여부를 판단하고 적절한 성공 또는 오류 메시지를 결정하는 로직 정의 */

 sBtn.addEventListener("click", ()=> {
  if ( success ) {
   outSpan.textContent = successMessage;
  }
  else {
   outSpan.textContent = errorMessage;
  }
  outSpan.showPopover();

  setTimeout(function () { 
   outSpan.hidePopover(); 
  }, 10000); 
 }); 
</script>

팝오버 요소를 output 요소에 삽입하면 일반적으로 화면 읽기 프로그램이 콘텐츠가 표시될 때 이를 알리게 됩니다. 콘텐츠의 복잡성이나 빈도에 따라 이러한 알림이 이러한 보조 기술 사용자에게 유용하거나 귀찮을 수 있습니다. output 요소 또는 다른 ARIA 라이브 영역을 사용할 때 최상의 사용자 경험을 보장하기 위해 이를 염두에 두세요.

popover 속성은 다음 키워드와 상태를 가진 열거형 속성입니다:

키워드 상태 간단한 설명
auto auto 열릴 때 다른 팝오버를 닫습니다. 간단히 닫기 기능이 있으며 닫기 요청에 응답합니다.
(빈 문자열)
manual manual 다른 팝오버를 닫지 않으며, 간단히 닫기 또는 닫기 요청에 응답하지 않습니다.

이 속성의 누락된 값 기본값팝오버 없음 상태이며, 잘못된 값 기본값manual 상태입니다.

HTMLElement/popover

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (구버전)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

popover IDL 속성은 popover 속성을 반영해야 하며, 알려진 값들로만 제한됩니다.

모든 HTML 요소팝오버 가시성 상태를 가지며, 초기 상태는 숨김으로 설정되고, 다음 가능한 값들을 가질 수 있습니다:

Document팝오버 포인터다운 대상을 가지며, 이는 HTML 요소 또는 null로 설정되며, 초기 상태는 null입니다.

모든 HTML 요소팝오버 호출자를 가지며, 이는 HTML 요소 또는 null로 설정되며, 초기 상태는 null입니다.

모든 HTML 요소팝오버 표시 또는 숨김을 가지며, 이는 부울 값으로, 초기 상태는 false로 설정됩니다.

모든 HTML 요소팝오버 토글 작업 추적기를 가지며, 이는 토글 작업 추적기 또는 null로 설정되며, 초기 상태는 null입니다.

모든 HTML 요소팝오버 닫기 감시자를 가지며, 이는 닫기 감시자 또는 null로 설정되며, 초기 상태는 null입니다.

다음 속성 변경 단계는, element, localName, oldValue, value, 및 namespace를 주어 모든 HTML 요소에 대해 사용됩니다:

  1. namespace가 null이 아니면 반환합니다.

  2. localNamepopover가 아니면 반환합니다.

  3. element팝오버 가시성 상태표시 상태에 있으며, oldValuevalue가 다른 상태에 있으면, element, true, true, 및 false를 주어 팝오버 숨기기 알고리즘을 실행합니다.

element.showPopover()
팝오버 element를 최상위 레이어에 추가하여 표시합니다. elementpopover 속성이 auto 상태에 있으면, element의 조상에 해당하지 않는 한, 이 상태에서 다른 모든 auto 팝오버를 닫습니다.
element.hidePopover()
팝오버 element를 최상위 레이어에서 제거하고 display: none을 적용하여 숨깁니다.
element.togglePopover()
팝오버 element가 표시되지 않은 경우 이 메서드는 팝오버를 표시합니다. 그렇지 않으면 이 메서드는 팝오버를 숨깁니다. 이 메서드는 호출 후 팝오버가 열려 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

HTMLElement/showPopover

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (구버전)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

showPopover() 메서드 단계는 popover 표시 알고리즘을 this, true, 및 null을 인자로 실행하는 것입니다.

popover 표시를 위해, HTML 요소 element, 부울 throwExceptions, 및 HTML 요소 또는 null invoker를 주어진 상황에서 실행하십시오:

  1. popover 유효성 검사의 결과가 false라면, element, false, throwExceptions, 및 null을 주어 반환합니다.

  2. documentelement노드 문서로 설정하십시오.

  3. 확인: elementpopover 호출자가 null인지 확인합니다.

  4. 확인: elementdocument최상위 레이어에 없는지 확인합니다.

  5. nestedShowelementpopover 표시 또는 숨김으로 설정하십시오.

  6. elementpopover 표시 또는 숨김을 true로 설정하십시오.

  7. cleanupShowingFlag를 다음 단계로 설정하십시오:

    1. nestedShow가 false인 경우, elementpopover 표시 또는 숨김을 false로 설정하십시오.

  8. 이벤트를 발생시키고, 이벤트의 beforetoggle 이름을 지정하며, ToggleEvent를 사용하고, cancelable 속성을 true로 초기화하고, oldState 속성을 "closed"로, newState 속성을 "open"으로 초기화한 결과가 false인 경우, cleanupShowingFlag을 실행하고 반환하십시오.

  9. popover 유효성 검사의 결과가 false인 경우, element, false, throwExceptions, 및 document를 주어 cleanupShowingFlag을 실행하고 반환하십시오.

    popover 유효성 검사가 다시 호출된 이유는, beforetoggle 이벤트를 발생시키면 이 요소가 분리되거나 popover 속성이 변경될 수 있기 때문입니다.

  10. shouldRestoreFocus를 false로 설정하십시오.

  11. elementpopover 속성이 auto 상태에 있는 경우:

    1. originalTypeelementpopover 속성 값으로 설정하십시오.

    2. ancestor최상위 popover 조상 알고리즘을 실행하여 얻은 element, invoker, 및 true의 결과로 설정하십시오.

    3. ancestor가 null인 경우, ancestordocument로 설정하십시오.

    4. 모든 popover를 숨김을 실행하여 ancestor, false, 및 nestedShow가 아닌 값을 주십시오.

    5. originalTypeelementpopover 속성 값과 같지 않은 경우:

      1. throwExceptions가 true인 경우, "InvalidStateError" DOMException을 던지십시오.

      2. 반환하십시오.

    6. popover 유효성 검사의 결과가 false인 경우, element, false, throwExceptions, 및 document를 주어 cleanupShowingFlag을 실행하고 반환하십시오.

      popover 유효성 검사가 다시 호출된 이유는, 위에서 모든 popover를 숨김을 실행한 결과로 beforetoggle 이벤트가 발생했을 수 있기 때문이며, 이벤트 핸들러가 이 요소를 분리했거나 popover 속성을 변경했을 수 있기 때문입니다.

    7. 최상위 자동 popoverdocument에 대해 실행한 결과가 null인 경우, shouldRestoreFocus를 true로 설정하십시오.

      이것은 스택 내에서 첫 번째 popover에 대해서만 초점이 이전에 초점이 맞춰진 요소로 돌아가도록 보장합니다.

    8. elementpopover 종료 감시자element관련 글로벌 객체를 주어 종료 감시자 설정 결과로 설정하십시오.

  12. element이전 초점 요소를 null로 설정하십시오.

  13. originallyFocusedElementdocument문서의 초점 영역DOM 앵커로 설정하십시오.

  14. 요소를 최상위 레이어에 추가하십시오.

  15. elementpopover 표시 상태표시 중으로 설정하십시오.

  16. elementpopover 호출자invoker로 설정하십시오.

  17. popover 초점 맞춤 단계element로 실행하십시오.

  18. shouldRestoreFocus가 true이고 elementpopover 속성이 no popover 상태가 아닌 경우, element이전 초점 요소originallyFocusedElement로 설정하십시오.

  19. popover 토글 이벤트 작업 큐에 추가element, "closed", 및 "open"을 주어 실행하십시오.

  20. cleanupShowingFlag을 실행하십시오.

주어진 요소 element, 문자열 oldState 및 문자열 newState에 대해 popover 토글 이벤트 작업을 큐에 추가하려면 다음과 같이 합니다:

  1. 만약 elementpopover 토글 작업 추적기가 null이 아니면:

    1. oldStateelementpopover 토글 작업 추적기이전 상태로 설정합니다.

    2. elementpopover 토글 작업 추적기작업작업 큐에서 제거합니다.

    3. elementpopover 토글 작업 추적기를 null로 설정합니다.

  2. 요소 작업을 큐에 추가하고, DOM 조작 작업 소스element를 주어 다음 단계를 실행합니다:

    1. 이벤트를 발생시키고, 이름을 toggle로 지정하며, element에서 ToggleEvent를 사용하고, oldState 속성을 oldState로 초기화하고, newState 속성을 newState로 초기화합니다.

    2. elementpopover 토글 작업 추적기를 null로 설정합니다.

  3. elementpopover 토글 작업 추적기를 구조체로 설정하고, 작업을 방금 큐에 추가한 작업으로 설정하며, 이전 상태oldState로 설정합니다.

HTMLElement/hidePopover

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (구버전)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

hidePopover() 메서드의 단계는 다음과 같습니다:

  1. popover 숨김 알고리즘this, true, true, 및 true를 주어 실행하십시오.

HTML 요소 element, 불리언 focusPreviousElement, 불리언 fireEvents, 불리언 throwExceptions을 주어 popover 숨기기를 수행하려면 다음과 같이 합니다:

  1. element에 대해 throwExceptions 및 null을 주어 popover 유효성 검사를 실행한 결과가 false인 경우, 반환합니다.

  2. documentelement노드 문서로 설정합니다.

  3. nestedHideelementpopover 표시 또는 숨김으로 설정합니다.

  4. elementpopover 표시 또는 숨김을 true로 설정합니다.

  5. nestedHide가 true인 경우, fireEvents를 false로 설정합니다.

  6. cleanupSteps를 다음 단계로 설정합니다:

    1. nestedHide가 false인 경우, elementpopover 표시 또는 숨김을 false로 설정합니다.

    2. elementpopover 닫기 감시자가 null이 아닌 경우:

      1. elementpopover 닫기 감시자파괴합니다.

      2. elementpopover 닫기 감시자를 null로 설정합니다.

  7. elementpopover 속성이 auto 상태에 있는 경우:

    1. element, focusPreviousElementfireEvents을 주어 모든 popover 숨기기를 실행합니다.

    2. element, true 및 throwExceptions을 주어 popover 유효성 검사를 실행한 결과가 false인 경우, cleanupSteps를 실행하고 반환합니다.

      popover 유효성 검사모든 popover 숨기기 실행이 element를 연결 해제하거나 그 속성을 변경할 수 있기 때문에 다시 호출됩니다.

  8. autoPopoverListContainsElementdocument자동 popover 목록의 마지막 항목이 element인 경우 true로, 그렇지 않은 경우 false로 설정합니다.

  9. elementpopover 호출자를 null로 설정합니다.

  10. fireEvents가 true인 경우:

    1. element에서 beforetoggle라는 이름의 이벤트를 ToggleEvent을 사용하여 발생시키며, oldState 속성을 "open"으로 초기화하고 newState 속성을 "closed"로 초기화합니다.

    2. autoPopoverListContainsElement가 true이고 document자동 popover 목록의 마지막 항목이 element가 아닌 경우, element, focusPreviousElement 및 false를 주어 모든 popover 숨기기를 실행합니다.

    3. element, true, throwExceptions 및 null을 주어 popover 유효성 검사를 실행한 결과가 false인 경우, cleanupSteps를 실행하고 반환합니다.

      popover 유효성 검사beforetoggle 이벤트 발생이 element를 연결 해제하거나 그 속성을 변경할 수 있기 때문에 다시 호출됩니다.

    4. element를 주어 최상위 레이어에서 요소 제거를 요청합니다.

  11. 그렇지 않으면, element를 주어 즉시 최상위 레이어에서 요소를 제거합니다.

  12. elementpopover 표시 상태숨김으로 설정합니다.

  13. fireEvents가 true인 경우, element, "open", "closed"를 주어 popover 토글 이벤트 작업을 큐에 추가합니다.

  14. previouslyFocusedElementelement이전에 포커스된 요소로 설정합니다.

  15. previouslyFocusedElement가 null이 아닌 경우:

    1. element이전에 포커스된 요소를 null로 설정합니다.

    2. focusPreviousElement가 true이고 document문서의 포커스된 영역DOM 앵커element그림자 포함 포함 자손인 경우, previouslyFocusedElement에 대한 포커스 단계를 실행합니다. 이 단계를 수행할 때 뷰포트가 스크롤되지 않아야 합니다.

  16. cleanupSteps를 실행합니다.

HTMLElement/togglePopover

모든 현재 엔진에서 지원.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

togglePopover(force) 메서드 단계는 다음과 같습니다:

  1. 만약 this팝오버 가시성 상태표시 중이며, force가 존재하지 않거나 false인 경우, 팝오버 숨기기 알고리즘을 실행하고 this, true, true, 및 true를 전달합니다.

  2. 그렇지 않으면, force가 존재하지 않거나 true인 경우, 팝오버 표시를 실행하고 this, true 및 null을 전달합니다.

  3. 그 외의 경우:

    1. 만약 this팝오버 가시성 상태표시 중이라면 expectedToBeShowing을 true로 설정합니다; 그렇지 않으면 false로 설정합니다.

    2. 팝오버 유효성 검사를 실행하고 expectedToBeShowing, true 및 null을 전달합니다.

  4. this팝오버 가시성 상태표시 중이라면 true를 반환합니다; 그렇지 않으면 false를 반환합니다.

hide all popovers until, 다음 조건이 주어진 경우: HTML 요소 또는 document endpoint, a boolean focusPreviousElement, 및 boolean fireEvents:

  1. 만약 endpointHTML 요소이고 endpoint표시 중 상태가 아니라면 return.

  2. documentendpoint노드 문서로 설정합니다.

  3. closeAllOpenPopovers 알고리즘은 다음 단계를 수행합니다:

    1. popoverdocument최상위 자동 팝오버로 설정합니다.

    2. popover가 null이 아닐 때까지:

      1. 팝오버 숨기기 알고리즘을 실행하고 popover, focusPreviousElement, fireEvents, 및 false를 전달합니다.

      2. popoverdocument최상위 자동 팝오버로 설정합니다.

  4. 만약 endpointdocument라면, closeAllOpenPopovers을 실행하고 return.

  5. Assert: endpointpopover 속성이 자동 상태에 있습니다.

  6. repeatingHide를 false로 설정합니다.

  7. 다음 단계를 최소한 한 번 수행합니다:

    1. lastToHide를 null로 설정합니다.

    2. foundEndpoint를 false로 설정합니다.

    3. document표시 중인 자동 팝오버 목록의 각 popover에 대해 다음을 수행합니다:

      1. 만약 popoverendpoint라면, foundEndpoint를 true로 설정합니다.

      2. 그렇지 않으면, 만약 foundEndpoint가 true라면, lastToHidepopover로 설정하고 break합니다.

    4. 만약 foundEndpoint가 false라면, closeAllOpenPopovers을 실행하고 return.

    5. lastToHide가 null이 아니며, lastToHide팝오버 가시성 상태표시 중이고 document표시 중인 자동 팝오버 목록이 비어 있지 않은 동안:

      1. 팝오버 숨기기 알고리즘을 실행하고 document표시 중인 자동 팝오버 목록의 마지막 요소, focusPreviousElement, fireEvents, 및 false를 전달합니다.

    6. 만약 document표시 중인 자동 팝오버 목록endpoint가 포함되어 있고 document표시 중인 자동 팝오버 목록의 마지막 요소가 endpoint가 아닌 경우, repeatingHide를 true로 설정합니다; 그렇지 않으면 false로 설정합니다.

    7. 만약 repeatingHide가 true라면, fireEvents를 false로 설정합니다.

    그리고 repeatingHide가 true인 동안 계속 수행합니다.

모든 팝오버를 숨기기 알고리즘은 특정 이벤트가 발생할 때 모든 팝오버를 숨기기 위해 여러 상황에서 사용됩니다. 예를 들어, 팝오버의 가벼운 해제(light-dismiss) 중에, 이 알고리즘은 사용자가 클릭한 노드와 관련이 없는 팝오버만 닫도록 보장합니다.

다음을 찾기 위해 최상위 팝오버 조상, 다음 조건이 주어진 경우: 노드 newPopoverOrTopLayerElement, HTML 요소 또는 null invoker, 그리고 boolean isPopover, 다음 단계를 수행합니다. 반환 값은 HTML 요소 또는 null입니다.

최상위 팝오버 조상 알고리즘은 제공된 팝오버 또는 최상위 레이어 요소에 대해 최상위(최신) 조상 팝오버를 반환합니다. 팝오버는 여러 가지 방식으로 서로 관련될 수 있으며, 팝오버 트리를 형성할 수 있습니다. 한 팝오버(이를 "자식" 팝오버라고 합니다)가 최상위 조상 팝오버(이를 "부모" 팝오버라고 합니다)를 가질 수 있는 두 가지 경로가 있습니다:

  1. 팝오버가 노드 트리 내에서 서로 중첩되어 있습니다. 이 경우, 하위 팝오버는 "자식"이고 최상위 조상 팝오버는 "부모"입니다.

  2. 호출 요소(예: 버튼)가 popovertarget 속성을 가지고 있으며, 팝오버를 가리키고 있습니다. 이 경우, 팝오버는 "자식"이며, 호출 요소가 있는 팝오버 서브트리는 "부모"입니다. 호출자는 팝오버 안에 있어야 하며, 열린 팝오버를 참조해야 합니다.

위에서 형성된 각 관계에서 부모 팝오버는 자식 팝오버보다 표시 중인 자동 팝오버 목록에서 엄격히 이전에 있어야 하며, 그렇지 않으면 유효한 조상 관계를 형성하지 않습니다. 이로 인해 표시되지 않는 팝오버와 자기참조(예: 팝오버가 호출 요소를 포함하고, 해당 요소가 다시 포함된 팝오버를 가리키는 경우)가 제거되며, (순환 가능성 있는) 연결 그래프에서 잘 형성된 트리를 구성할 수 있게 됩니다. 자동 팝오버만 고려됩니다.

제공된 요소가 대화상자(dialog)와 같은 최상위 레이어 요소이며, 팝오버로 표시되지 않는 경우, 최상위 팝오버 조상은 노드 트리 내에서 첫 번째 팝오버만 찾습니다.

  1. 만약 isPopover가 true라면:

    1. 단언: newPopoverOrTopLayerElementHTML 요소입니다.

    2. 단언: newPopoverOrTopLayerElementpopover 속성이 팝오버 없음 상태 또는 수동 상태에 있지 않습니다.

    3. 단언: newPopoverOrTopLayerElement팝오버 가시성 상태팝오버 표시 상태에 있지 않습니다.

  2. 그 외의 경우:

    1. 단언: invoker가 null입니다.

  3. popoverPositions을 빈 순서 있는 맵으로 설정합니다.

  4. index를 0으로 설정합니다.

  5. documentnewPopoverOrTopLayerElement노드 문서로 설정합니다.

  6. document표시 중인 자동 팝오버 목록의 각 popover에 대해 다음을 수행합니다:

    1. 설정 popoverPositions[popover]을 index로 설정합니다.

    2. index를 1씩 증가시킵니다.

  7. 만약 isPopover가 true라면, 설정 popoverPositions[newPopoverOrTopLayerElement]을 index로 설정합니다.

  8. index를 1씩 증가시킵니다.

  9. topmostPopoverAncestor를 null로 설정합니다.

  10. checkAncestor를 다음 단계를 수행하는 알고리즘으로 설정합니다 candidate가 주어졌을 때:

    1. candidate가 null인 경우, return.

    2. candidateAncestorcandidate에 대해 가장 가까운 포괄적인 열린 팝오버 실행 결과로 설정합니다.

    3. candidateAncestor가 null인 경우, return.

    4. candidatePositionpopoverPositions[candidateAncestor]로 설정합니다.

    5. 만약 topmostPopoverAncestor가 null이거나 popoverPositions[topmostPopoverAncestor]이 candidatePosition보다 작은 경우, topmostPopoverAncestorcandidateAncestor로 설정합니다.

  11. checkAncestornewPopoverOrTopLayerElement의 부모 노드에 대해 실행합니다, 평면 트리 내에서.

  12. checkAncestorinvoker에 대해 실행합니다.

  13. topmostPopoverAncestor를 반환합니다.

node에 대해 가장 가까운 포괄적인 열린 팝오버를 찾기 위해, 다음 단계를 수행합니다. 이 단계는 HTML 요소 또는 null을 반환합니다.

  1. currentNodenode로 설정합니다.

  2. currentNode가 null이 아닐 때까지:

    1. 만약 currentNodepopover 속성이 자동 상태에 있고 currentNode팝오버 가시성 상태표시 중이라면, currentNode를 반환합니다.

    2. currentNodecurrentNode의 부모로 설정합니다, 평면 트리 내에서.

  3. null을 반환합니다.

document에 대해 최상위 자동 팝오버를 찾기 위해, 다음 단계를 수행합니다. 이 단계는 HTML 요소 또는 null을 반환합니다.

  1. 만약 document표시 중인 자동 팝오버 목록이 비어 있지 않다면, document표시 중인 자동 팝오버 목록의 마지막 요소를 반환합니다.

  2. null을 반환합니다.

subject에 대해 팝오버 포커싱 단계를 수행하기 위해:

  1. subject대화상자(dialog) 요소인 경우, subject에 대해 대화상자 포커싱 단계를 실행하고 반환합니다.

  2. subjectautofocus 속성이 있는 경우, controlsubject로 설정합니다.

  3. 그 외의 경우, control을 "기타"에 대해 subject자동 포커스 대리자로 설정합니다.

  4. control이 null인 경우, 반환합니다.

  5. control에 대해 포커싱 단계를 실행합니다.

  6. topDocument활성 문서로 설정합니다, control노드 문서탐색 문맥최상위 탐색 문맥의.

  7. control노드 문서원점topDocument원점과 동일하지 않은 경우, 반환합니다.

  8. topDocument자동 포커스 후보비웁니다.

  9. topDocument자동 포커스 처리됨 플래그를 true로 설정합니다.

element에 대해 팝오버 유효성 검사를 수행하기 위해, 다음이 주어진 경우: HTML 요소 element, boolean expectedToBeShowing, boolean throwExceptions, 그리고 document 또는 null expectedDocument, 다음 단계를 수행합니다. 이들은 예외를 발생시키거나 boolean을 반환합니다.

  1. 만약 element팝오버 속성이 팝오버 없음 상태에 있는 경우:

    1. 만약 throwExceptions이 true라면, "NotSupportedError" DOMException을 발생시킵니다.

    2. false를 반환합니다.

  2. 만약 다음 중 어느 하나라도 true라면:

    그렇다면 false를 반환합니다.

  3. 만약 다음 중 어느 하나라도 true라면:

    그렇다면:

    1. 만약 throwExceptions이 true라면, "InvalidStateError" DOMException을 발생시킵니다.

    2. false를 반환합니다.

  4. true를 반환합니다.

document에 대해 표시 중인 자동 팝오버 목록을 가져오기 위해, document document:

  1. popovers를 « »로 설정합니다.

  2. 각각에 대해 요소 elementdocument최상위 레이어에 있습니다: 만약 element팝오버 속성이 자동 상태에 있고, element팝오버 가시성 상태표시 중이라면, 추가합니다 elementpopovers에.

  3. popovers를 반환합니다.

6.12.1 팝오버 타겟 속성

버튼은 다음과 같은 콘텐츠 속성을 가질 수 있습니다:

지정된 경우, popovertarget 속성 값은 같은 ID를 가져야 합니다. popover 속성이 있는 요소와 동일한 트리 내에서, 버튼과 함께 popovertarget 속성을 가진 요소와 동일해야 합니다.

popovertargetaction 속성은 다음 키워드와 상태를 가지는 열거형 속성입니다:

키워드 상태 간략 설명
toggle toggle 대상 팝오버 요소를 표시하거나 숨깁니다.
show show 대상 팝오버 요소를 표시합니다.
hide hide 대상 팝오버 요소를 숨깁니다.

이 속성의 누락된 값 기본값잘못된 값 기본값은 모두 toggle 상태입니다.

가능한 경우 팝오버 요소가 DOM 내에서 트리거 요소 바로 뒤에 배치되도록 합니다. 이렇게 하면 화면 읽기 프로그램과 같은 보조 기술을 사용하는 사용자를 위해 팝오버가 논리적인 프로그래밍 읽기 순서로 노출되도록 할 수 있습니다.

다음은 popovertarget 속성과 popovertargetaction 속성을 조합하여 팝오버를 표시하고 닫을 수 있는 방법을 보여줍니다:

<button popovertarget="foo" popovertargetaction="show">
  Show a popover
</button>

<article popover="auto" id="foo">
  This is a popover article!
  <button popovertarget="foo" popovertargetaction="hide">Close</button>
</article>

만약 popovertargetaction 속성이 지정되지 않은 경우, 기본 동작은 연결된 팝오버를 토글하는 것입니다. 다음은 트리거 버튼에 popovertarget 속성만 지정하여 수동 팝오버를 열림 및 닫힘 상태 사이에서 토글할 수 있는 방법을 보여줍니다. 수동 팝오버는 가벼운 닫기닫기 요청에 응답하지 않습니다:

<input type="button" popovertarget="foo" value="Toggle the popover">

<div popover=manual id="foo">
  This is a popover!
</div>
DOM 인터페이스:
interface mixin PopoverInvokerElement {
  [CEReactions] attribute Element? popoverTargetElement;
  [CEReactions] attribute DOMString popoverTargetAction;
};

HTMLButtonElement/popoverTargetElement

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLInputElement/popoverTargetElement

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

popoverTargetElement IDL 속성은 popovertarget 속성을 반영해야 합니다.

HTMLButtonElement/popoverTargetAction

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLInputElement/popoverTargetAction

모든 현재 엔진에서 지원됩니다.

Firefox🔰 114+Safari17+Chrome114+
Opera?Edge114+
Edge (Legacy)?지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

popoverTargetAction IDL 속성은 popovertargetaction 속성을 반영해야 하며, 알려진 값으로만 제한됩니다.

팝오버 타겟 속성 활성화 동작을 실행하려면 Node node를 지정하세요:

  1. popovernode팝오버 타겟 요소로 설정합니다.

  2. popover가 null이면, 반환합니다.

  3. nodepopovertargetaction 속성이 show 상태에 있고 popover팝오버 가시성 상태표시 상태라면, 반환합니다.

  4. nodepopovertargetaction 속성이 hide 상태에 있고 popover팝오버 가시성 상태숨김 상태라면, 반환합니다.

  5. popover팝오버 가시성 상태표시 상태라면, 팝오버 숨기기 알고리즘popover, true, true, false를 인자로 하여 실행합니다.

  6. 그렇지 않으면, popover팝오버 가시성 상태숨김 상태이고, 팝오버 유효성 검사popover, false, false, null을 인자로 하여 실행한 결과가 true라면, 팝오버 표시popover, false, node를 인자로 하여 실행합니다.

팝오버 타겟 요소를 가져오려면 Node node를 지정하고, 다음 단계를 수행합니다. 이들은 HTML 요소 또는 null을 반환합니다.

  1. node버튼이 아니면, null을 반환합니다.

  2. node비활성화됨 상태이면, null을 반환합니다.

  3. node폼 소유자가 있고, node제출 버튼이면, null을 반환합니다.

  4. popoverElementnode연관된 요소 popovertarget 가져오기 작업의 결과로 설정합니다.

  5. popoverElement가 null이면, null을 반환합니다.

  6. popoverElementpopover 속성이 팝오버 없음 상태에 있으면, null을 반환합니다.

  7. popoverElement를 반환합니다.

6.12.2 팝오버 라이트 해제

"라이트 해제"는 popover 속성이 auto 상태에 있는 팝오버 바깥을 클릭하면 팝오버가 닫히는 것을 의미합니다. 이는 해당 팝오버가 닫기 요청에 반응하는 방식에 추가됩니다.

열린 팝오버 라이트 해제를 실행하려면, 이벤트 event를 지정하세요:

  1. 확인: eventisTrusted 속성이 true인지 확인합니다.

  2. targetevent타겟으로 설정합니다.

  3. documenttarget노드 문서로 설정합니다.

  4. topmostPopoverdocument에 대해 가장 상위의 자동 팝오버 실행 결과로 설정합니다.

  5. topmostPopover가 null이면 반환합니다.

  6. eventPointerEvent이고, event타입이 "pointerdown"인 경우: document팝오버 포인터다운 타겟target에 대해 가장 상위에서 클릭된 팝오버 실행 결과로 설정합니다.

  7. eventPointerEvent이고, event타입이 "pointerup"인 경우:

    1. ancestortarget에 대해 가장 상위에서 클릭된 팝오버 실행 결과로 설정합니다.

    2. sameTargetancestordocument팝오버 포인터다운 타겟과 동일한 경우 true로 설정합니다.

    3. document팝오버 포인터다운 타겟을 null로 설정합니다.

    4. ancestor가 null인 경우 ancestordocument로 설정합니다.

    5. sameTarget이 true인 경우 ancestor, false, true를 인자로 하여 모든 팝오버 숨기기를 실행합니다.

열린 팝오버 라이트 해제는 사용자가 페이지의 아무 곳이나 클릭하거나 터치할 때 Pointer Events 스펙에 의해 호출됩니다.

가장 상위에서 클릭된 팝오버를 찾으려면, 노드 node를 지정하세요:

  1. clickedPopovernode에 대해 가장 가까운 포함된 열린 팝오버 실행 결과로 설정합니다.

  2. invokerPopovernode에 대해 호출자를 위한 가장 가까운 포함된 타겟 팝오버 실행 결과로 설정합니다.

  3. getStackPositionHTML 요소 popover를 인자로 받아 다음 단계를 수행하는 알고리즘으로 설정하세요:

    1. popoverListpopover노드 문서보이는 자동 팝오버 목록으로 설정합니다.

    2. popoverpopoverList에 있으면, popoverpopoverList 내 인덱스 + 1을 반환합니다.

    3. 0을 반환합니다.

  4. clickedPopover를 인자로 하여 실행한 getStackPosition 결과가 invokerPopover를 인자로 하여 실행한 getStackPosition 결과보다 크면, clickedPopover를 반환합니다.

  5. invokerPopover를 반환합니다.

호출자를 위한 가장 가까운 포함된 타겟 팝오버를 찾으려면, 노드 node를 지정하세요:

  1. currentNodenode로 설정합니다.

  2. currentNode가 null이 아닐 때까지 반복합니다:

    1. targetPopovercurrentNode팝오버 타겟 요소로 설정합니다.

    2. targetPopover가 null이 아니고, targetPopoverpopover 속성이 auto 상태이며, targetPopover팝오버 가시성 상태표시 상태라면, targetPopover를 반환합니다.

    3. currentNode플랫 트리currentNode의 조상으로 설정합니다.

7 웹 페이지 로드

이 섹션에서는 웹 브라우저에 가장 직접적으로 적용되는 기능을 설명합니다. 그러나 달리 명시된 경우를 제외하고, 이 섹션에서 정의된 요구 사항은 웹 브라우저가 아닌 모든 사용자 에이전트에도 적용됩니다.

7.1 지원 개념

7.1.1 출처

출처는 웹 보안 모델의 기본 통화입니다. 동일한 출처를 공유하는 웹 플랫폼의 두 액터는 서로를 신뢰하고 동일한 권한을 가진 것으로 간주됩니다. 다른 출처를 가진 액터들은 잠재적으로 서로 적대적일 수 있으며, 서로 다른 정도로 격리됩니다.

예를 들어, bank.example.com에 호스팅된 Example Bank의 웹 사이트가 charity.example.org에 호스팅된 Example Charity의 웹 사이트의 DOM을 검사하려고 하면, "SecurityError" DOMException이 발생합니다.


출처는 다음 중 하나입니다:

불투명 출처

내부 값으로, 이를 다시 생성할 수 있는 직렬화가 없으며(이는 출처의 직렬화에 따라 "null"로 직렬화됨), 의미 있는 유일한 작업은 동일성 테스트입니다.

튜플 출처

튜플은 다음을 포함합니다:

출처는 여러 Document 객체 간에 공유될 수 있습니다. 또한 출처는 일반적으로 불변입니다. 오직 도메인튜플 출처에서 변경할 수 있으며, 이는 document.domain API를 통해서만 가능합니다.

유효 도메인출처 origin에 대해 다음과 같이 계산됩니다:

  1. origin불투명 출처인 경우, null을 반환합니다.

  2. origin도메인이 null이 아닌 경우, origin도메인을 반환합니다.

  3. origin호스트를 반환합니다.

출처의 직렬화는 주어진 출처 origin에 다음 알고리즘을 적용하여 얻은 문자열입니다:

  1. origin불투명 출처인 경우, "null"을 반환합니다.

  2. 그렇지 않으면, resultorigin스킴으로 설정합니다.

  3. result에 "://"을 추가합니다.

  4. origin호스트, 직렬화된 값을 result에 추가합니다.

  5. origin포트가 null이 아닌 경우, U+003A COLON 문자 (:)와 origin포트직렬화된 값을 result에 추가합니다.

  6. result를 반환합니다.

("https", "xn--maraa-rta.example", null, null)의 직렬화는 "https://xn--maraa-rta.example"입니다.

이전에 출처의 유니코드 직렬화도 있었습니다. 그러나 이는 널리 채택되지 않았습니다.


출처, AB동일 출처라고 하는 경우, 다음 알고리즘이 true를 반환합니다:

  1. AB가 동일한 불투명 출처인 경우, true를 반환합니다.

  2. AB가 모두 튜플 출처이며, 그들의 스킴, 호스트포트가 동일한 경우, true를 반환합니다.

  3. false를 반환합니다.

출처, AB동일 출처-도메인이라고 하는 경우, 다음 알고리즘이 true를 반환합니다:

  1. AB가 동일한 불투명 출처인 경우, true를 반환합니다.

  2. AB가 모두 튜플 출처인 경우:

    1. AB스킴이 동일하고, 그들의 도메인이 동일하며 null이 아닌 경우, true를 반환합니다.

    2. 그렇지 않으면, AB동일 출처이며 그들의 도메인이 둘 다 null인 경우, true를 반환합니다.

  3. false를 반환합니다.

A B 동일 출처 동일 출처-도메인
("https", "example.org", null, null) ("https", "example.org", null, null)
("https", "example.org", 314, null) ("https", "example.org", 420, null)
("https", "example.org", 314, "example.org") ("https", "example.org", 420, "example.org")
("https", "example.org", null, null) ("https", "example.org", null, "example.org")
("https", "example.org", null, "example.org") ("http", "example.org", null, "example.org")
7.1.1.1 사이트

스킴과 호스트튜플로서, 스킴(ASCII 문자열)과 호스트(호스트)로 구성됩니다.

사이트불투명 출처 또는 스킴과 호스트입니다.

출처 origin을 주어진 경우, 사이트를 획득하려면 다음 단계를 수행합니다:

  1. origin불투명 출처인 경우, origin을 반환합니다.

  2. origin호스트등록 가능 도메인이 null인 경우, (origin스킴, origin호스트)를 반환합니다.

  3. (origin스킴, origin호스트등록 가능 도메인)를 반환합니다.

사이트, AB동일 사이트라고 하는 경우, 다음 알고리즘이 true를 반환합니다:

  1. AB가 동일한 불투명 출처인 경우, true를 반환합니다.

  2. A 또는 B불투명 출처인 경우, false를 반환합니다.

  3. AB스킴 값이 다르면, false를 반환합니다.

  4. AB호스트 값이 동일하지 않으면, false를 반환합니다.

  5. true를 반환합니다.

사이트의 직렬화는 주어진 사이트 site에 대해 다음 알고리즘을 적용하여 얻은 문자열입니다:

  1. site불투명 출처인 경우, "null"을 반환합니다.

  2. resultsite[0]으로 설정합니다.

  3. result에 "://"을 추가합니다.

  4. site[1], 직렬화된 값을 result에 추가합니다.

  5. result를 반환합니다.

직렬화된 값이 사이트인지 출처인지 문맥상 명확해야 합니다. 두 사이에 문법적 차이가 없을 수도 있기 때문입니다. 예를 들어, 출처 ("https", "shop.example", null, null)와 사이트 ("https", "shop.example")는 동일한 직렬화: "https://shop.example"를 가집니다.

출처, AB스킴이 없는 동일 사이트라고 하는 경우, 다음 알고리즘이 true를 반환합니다:

  1. AB가 동일한 불투명 출처인 경우, true를 반환합니다.

  2. AB가 모두 튜플 출처인 경우:

    1. hostAA호스트로, hostBB호스트로 설정합니다.

    2. hostA동일한 hostB이며, hostA등록 가능 도메인이 null인 경우, true를 반환합니다.

    3. hostA등록 가능 도메인동일한 hostB등록 가능 도메인이고, null이 아닌 경우, true를 반환합니다.

  3. false를 반환합니다.

출처, AB동일 사이트라고 하는 경우, 다음 알고리즘이 true를 반환합니다:

  1. siteA사이트를 획득하여 얻은 값으로 설정합니다.

  2. siteB사이트를 획득하여 얻은 값으로 설정합니다.

  3. siteA동일 사이트siteB인 경우, true를 반환합니다.

  4. false를 반환합니다.

동일 출처동일 출처-도메인 개념과 달리, 스킴이 없는 동일 사이트동일 사이트의 경우, 포트도메인 구성 요소는 무시됩니다.

URL에서 설명된 이유로 인해, 동일 사이트스킴이 없는 동일 사이트 개념은 가능한 한 피하고, 대신 동일 출처 검사를 사용하는 것이 좋습니다.

wildlife.museum, museumcom공용 접미사이고 example.com이 그렇지 않다고 가정합니다:

A B 스킴이 없는 동일 사이트 동일 사이트
("https", "example.com") ("https", "sub.example.com")
("https", "example.com") ("https", "sub.other.example.com")
("https", "example.com") ("http", "non-secure.example.com")
("https", "r.wildlife.museum") ("https", "sub.r.wildlife.museum")
("https", "r.wildlife.museum") ("https", "sub.other.r.wildlife.museum")
("https", "r.wildlife.museum") ("https", "other.wildlife.museum")
("https", "r.wildlife.museum") ("https", "wildlife.museum")
("https", "wildlife.museum") ("https", "wildlife.museum")
("https", "example.com") ("https", "example.com.")

(여기에서는 포트도메인 구성 요소를 생략했습니다. 이는 고려되지 않기 때문입니다.)

7.1.1.2 동일 출처 제한 완화
document.domain [ = domain ]

보안 검사에 사용되는 현재 도메인을 반환합니다.

하위 도메인을 제거하는 값으로 설정할 수 있어, 출처도메인을 변경하여 동일 도메인의 다른 하위 도메인에 있는 페이지들이 서로 접근할 수 있게 합니다. 이는 동일 도메인의 다른 호스트에서 동작하는 페이지들이 서로의 DOM에 동기적으로 접근할 수 있도록 합니다.

샌드박스된 iframe 안에서, 불투명 출처를 가진 Document들, 그리고 탐색 문맥이 없는 Document들에서는 설정자가 "SecurityError" 예외를 발생시킵니다. crossOriginIsolated 또는 originAgentCluster가 true를 반환하는 경우, 설정자는 아무 작업도 하지 않습니다.

document.domain 설정자의 사용을 피하십시오. 이는 동일 출처 정책이 제공하는 보안 보호를 약화시킵니다. 특히 공유 호스팅을 사용하는 경우, 예를 들어 신뢰할 수 없는 제3자가 동일 IP 주소에서 다른 포트를 통해 HTTP 서버를 호스팅할 수 있다면, 동일 출처 보호가 실패할 수 있습니다. 이는 document.domain 설정자가 사용된 후에는 출처를 비교할 때 포트가 무시되기 때문입니다.

이러한 보안 위험으로 인해 이 기능은 웹 플랫폼에서 제거되는 중입니다. (이 과정은 수년이 걸릴 수 있습니다.)

대신, 출처 간 안전한 통신을 위해 postMessage() 또는 MessageChannel 객체를 사용하십시오.

domain getter 단계는 다음과 같습니다:

  1. effectiveDomainthis출처유효 도메인으로 설정합니다.

  2. effectiveDomain이 null이면, 빈 문자열을 반환합니다.

  3. effectiveDomain직렬화된 값으로 반환합니다.

domain setter 단계는 다음과 같습니다:

  1. this탐색 문맥이 null인 경우, "SecurityError" DOMException을 발생시킵니다.

  2. this활성 샌드박싱 플래그 집합샌드박스된 document.domain 탐색 문맥 플래그가 설정되어 있는 경우, "SecurityError" DOMException을 발생시킵니다.

  3. effectiveDomainthis출처유효 도메인으로 설정합니다.

  4. effectiveDomain이 null인 경우, "SecurityError" DOMException을 발생시킵니다.

  5. 주어진 값이 유효 도메인의 등록 가능 도메인 접미사이거나 동일하지 않은 경우, "SecurityError" DOMException을 발생시킵니다.

  6. 주변 에이전트에이전트 클러스터is origin-keyed가 true이면, 반환합니다.

  7. this출처도메인을 주어진 값을 파싱한 결과로 설정합니다.

스칼라 값 문자열 hostSuffixString호스트 originalHost등록 가능 도메인 접미사이거나 동일한지를 결정하기 위해 다음 단계를 따릅니다:

  1. hostSuffixString이 빈 문자열이면, false를 반환합니다.

  2. hostSuffixhostSuffixString파싱한 결과로 설정합니다.

  3. hostSuffix가 실패하면, false를 반환합니다.

  4. hostSuffix동일하지 않으면 originalHost와:

    1. hostSuffix 또는 originalHost도메인이 아니면, false를 반환합니다.

      이것은 호스트IP 주소인 경우를 제외합니다.

    2. hostSuffix가 U+002E (.)으로 접두사로 붙어 originalHost의 끝과 일치하지 않으면, false를 반환합니다.

    3. 다음 중 하나가 true이면:

      그러면 false를 반환합니다. [URL]

    4. 단언합니다: originalHost공용 접미사가 U+002E (.)으로 접두사로 붙어 hostSuffix의 끝과 일치합니다.

  5. true를 반환합니다.

hostSuffixString originalHost 등록 가능 도메인 접미사이거나 동일한지 참고
"0.0.0.0" 0.0.0.0
"0x10203" 0.1.2.3
"[0::1]" ::1
"example.com" example.com
"example.com" example.com. 끝에 붙는 점은 중요합니다.
"example.com." example.com
"example.com" www.example.com
"com" example.com 작성 당시, com은 공용 접미사입니다.
"example" example
"compute.amazonaws.com" example.compute.amazonaws.com 작성 당시, *.compute.amazonaws.com은 공용 접미사입니다.
"example.compute.amazonaws.com" www.example.compute.amazonaws.com
"amazonaws.com" www.example.compute.amazonaws.com
"amazonaws.com" test.amazonaws.com 작성 당시, amazonaws.com은 등록 가능한 도메인입니다.

7.1.2 출처 기반 에이전트 클러스터

window.originAgentCluster

Window에이전트 클러스터에 속해 있으며, 그 클러스터가 출처-기반으로 키됨인 경우 true를 반환합니다. 자세한 내용은 이 섹션에서 설명합니다.

Document보안 컨텍스트를 통해 제공될 때, 이를 출처-기반 에이전트 클러스터에 배치하도록 요청할 수 있습니다. 이 작업은 `Origin-Agent-Cluster` HTTP 응답 헤더를 사용하여 수행됩니다. 이 헤더는 구조화된 헤더로, 값은 불리언이어야 합니다. [STRUCTURED-FIELDS]

새로운 문서 객체 생성 및 초기화의 처리 모델에 따라, 이 헤더를 사용함으로써, Document에이전트 클러스터 키출처가 되며, 해당 사이트 대신 사용됩니다.

Document 객체가 같은 브라우징 컨텍스트 그룹 내에서 로드된 이전 페이지에서 이 헤더를 생략한 경우에도 originAgentCluster가 false를 반환할 수 있습니다. 반대로, 이 헤더가 설정되지 않은 경우에도 true를 반환할 수 있습니다.

같은 브라우징 컨텍스트 그룹 내의 동일 출처 Document 객체가 다른 에이전트 클러스터에 배치되지 않도록 기록된 에이전트 클러스터 키 맵을 통해 방지됩니다.

Document 객체가 불투명 출처를 가진 경우, originAgentCluster getter는 항상 true를 반환합니다.

7.1.3 교차 출처 오프너 정책

교차 출처 오프너 정책 값최상위 브라우징 컨텍스트에서 탐색되는 문서가 새로운 최상위 브라우징 컨텍스트와 해당 그룹을 강제로 생성할 수 있도록 합니다. 가능한 값은 다음과 같습니다:

"unsafe-none"

이는 현재 기본값으로, 문서는 전임자와 동일한 최상위 브라우징 컨텍스트에 위치하게 되며, 전임자가 다른 교차 출처 오프너 정책을 지정하지 않는 한 동일한 컨텍스트를 사용합니다.

"same-origin-allow-popups"

이는 문서에 대해 새로운 최상위 브라우징 컨텍스트를 강제로 생성하며, 전임자가 동일한 교차 출처 오프너 정책을 지정하지 않거나 그들이 동일 출처가 아닐 경우 이를 적용합니다.

"same-origin"

이는 "same-origin-allow-popups"와 동일하게 동작하지만, 생성된 보조 브라우징 컨텍스트는 동일한 동일 출처의 문서를 포함해야 하며, 동일한 교차 출처 오프너 정책을 가지고 있어야 합니다. 그렇지 않으면 오프너에게 닫힌 상태로 나타납니다.

"same-origin-plus-COEP"

이는 "same-origin"과 동일하게 동작하지만, 추가로 새로운 최상위 브라우징 컨텍스트그룹교차 출처 격리 모드를 "논리적" 또는 "구체적"으로 설정합니다.

"same-origin-plus-COEP"는 `Cross-Origin-Opener-Policy` 헤더를 통해 직접 설정할 수 없으며, `Cross-Origin-Opener-Policy: same-origin`과 `Cross-Origin-Embedder-Policy` 헤더를 함께 설정함으로써 생성됩니다.

교차 출처 오프너 정책은 다음으로 구성됩니다:

교차 출처 오프너 정책 값을 일치시키기 위해, 주어진 교차 출처 오프너 정책 값 A, 출처 originA, 교차 출처 오프너 정책 값 B, 그리고 출처 originB에 대해 다음을 수행합니다:

  1. 만약 A가 "unsafe-none"이고 B도 "unsafe-none"라면, true를 반환합니다.

  2. 만약 A가 "unsafe-none"이거나 B가 "unsafe-none"라면, false를 반환합니다.

  3. 만약 AB와 동일하고 originAoriginB동일 출처라면, true를 반환합니다.

  4. false를 반환합니다.

7.1.3.1 헤더

Headers/Cross-Origin-Opener-Policy

모든 현재 엔진에서 지원됨.

Firefox79+Safari15.2+Chrome83+
Opera아니오Edge83+
Edge (Legacy)?Internet Explorer아니오
Firefox Android?Safari iOS?Chrome Android?WebView Android아니오Samsung Internet?Opera Android아니오

Document교차 출처 오프너 정책은 `Cross-Origin-Opener-Policy` 및 `Cross-Origin-Opener-Policy-Report-Only` HTTP 응답 헤더에서 파생됩니다. 이 헤더들은 구조화된 헤더로, 그 값은 토큰이어야 합니다. [STRUCTURED-FIELDS]

유효한 토큰 값은 오프너 정책 값들입니다. 토큰에는 "report-to" 매개변수와 같은 매개변수가 첨부될 수 있습니다. 이 매개변수는 적절한 보고 엔드포인트를 식별하는 유효한 URL 문자열을 가질 수 있습니다. [REPORTING]

아래에 설명된 처리 모델에 따라, 사용자 에이전트는 이 헤더에 유효하지 않은 값이 포함된 경우 이를 무시합니다. 마찬가지로, 값이 토큰으로 파싱될 수 없는 경우에도 사용자 에이전트는 이 헤더를 무시합니다.


응답 response환경 reservedEnvironment가 주어졌을 때 교차 출처 오프너 정책을 획득하는 절차는 다음과 같습니다:

  1. policy를 새로운 교차 출처 오프너 정책으로 설정합니다.

  2. 만약 reservedEnvironment비보안 컨텍스트라면, policy를 반환합니다.

  3. parsedItem을 `Cross-Origin-Opener-Policy`와 "item"를 사용하여 구조화된 필드 값을 얻는 결과로 설정합니다.

  4. 만약 parsedItem이 null이 아니라면:

    1. 만약 parsedItem[0]이 "same-origin"이라면:

      1. coepresponsereservedEnvironment에서 교차 출처 임베더 정책을 획득한 결과로 설정합니다.

      2. 만약 coep교차 출처 격리와 호환되면, policy을 "same-origin-plus-COEP"으로 설정합니다.

      3. 그렇지 않으면, policy을 "same-origin"으로 설정합니다.

    2. 만약 parsedItem[0]이 "same-origin-allow-popups"이라면, policy을 "same-origin-allow-popups"으로 설정합니다.

    3. 만약 parsedItem[1]["report-to"]가 존재하고 그것이 문자열이라면, policy보고 엔드포인트parsedItem[1]["report-to"]로 설정합니다.

  5. parsedItem을 `Cross-Origin-Opener-Policy-Report-Only`와 "item"을 사용하여 구조화된 필드 값을 얻는 결과로 설정합니다.

  6. 만약 parsedItem이 null이 아니라면:

    1. 만약 parsedItem[0]이 "same-origin"이라면:

      1. coepresponsereservedEnvironment에서 교차 출처 임베더 정책을 획득한 결과로 설정합니다.

      2. 만약 coep교차 출처 격리와 호환되거나 coep보고 전용 값교차 출처 격리와 호환되면, policy보고 전용 값을 "same-origin-plus-COEP"으로 설정합니다.

        보고 전용 COOP은 COEP의 보고 전용을 고려하여 특별한 "same-origin-plus-COEP" 값을 할당합니다. 이를 통해 개발자는 COOP과 COEP의 배포 순서에 더 큰 자유를 가질 수 있습니다.

      3. 그렇지 않으면, policy보고 전용 값을 "same-origin"으로 설정합니다.

    2. 만약 parsedItem[0]이 "same-origin-allow-popups"이라면, policy보고 전용 값을 "same-origin-allow-popups"으로 설정합니다.

    3. 만약 parsedItem[1]["report-to"]가 존재하고 그것이 문자열이라면, policy보고 전용 엔드포인트parsedItem[1]["report-to"]로 설정합니다.

  7. policy를 반환합니다.

7.1.3.2 교차 출처 오프너 정책으로 인한 브라우징 컨텍스트 그룹 전환

다음과 같은 경우를 가정하고, COOP 값이 브라우징 컨텍스트 그룹 전환을 요구하는지 확인하려면, 부울 isInitialAboutBlank, 두 개의 기원(origin) responseOriginactiveDocumentNavigationOrigin, 그리고 두 개의 교차 출처 오프너 정책 값 responseCOOPValueactiveDocumentCOOPValue을 사용하십시오:

  1. 만약 일치하는 activeDocumentCOOPValue, activeDocumentNavigationOrigin, responseCOOPValue, responseOrigin의 결과가 true라면, false를 반환하십시오.

  2. 다음이 모두 true인 경우:

    그런 경우 false를 반환하십시오.

  3. true를 반환하십시오.

다음과 같은 경우를 가정하고, 보고 전용 COOP 강제 적용이 브라우징 컨텍스트 그룹 전환을 요구하는지 확인하려면, 부울 isInitialAboutBlank, 두 개의 기원(origin) responseOrigin, activeDocumentNavigationOrigin, 그리고 두 개의 교차 출처 오프너 정책 responseCOOPactiveDocumentCOOP을 사용하십시오:

  1. 만약 COOP 값이 브라우징 컨텍스트 그룹 전환을 요구하는지 확인한 결과가 false라면, false를 반환하십시오.

    보고 전용 정책을 일치시키는 것은 웹사이트가 모든 페이지에서 동일한 보고 전용 교차 출처 오프너 정책을 지정하고 이들 페이지 간의 탐색에 대해 위반 보고서를 받지 않도록 허용합니다.

  2. 만약 COOP 값이 브라우징 컨텍스트 그룹 전환을 요구하는지 확인한 결과가 true라면, true를 반환하십시오.

  3. 그렇지 않으면 false를 반환하십시오.

교차 출처 오프너 정책 강제 적용 결과는 다음과 같은 구조체를 포함하는 항목으로 구성됩니다:

다음과 같은 경우를 가정하고, 응답의 교차 출처 오프너 정책을 강제 적용하려면, 브라우징 컨텍스트 browsingContext, URL responseURL, 기원(origin) responseOrigin, 교차 출처 오프너 정책 responseCOOP, 교차 출처 오프너 정책 강제 적용 결과 currentCOOPEnforcementResult, 그리고 참조자 referrer를 사용하십시오:

  1. newCOOPEnforcementResult를 새로운 교차 출처 오프너 정책 강제 적용 결과로 설정하십시오.

    브라우징 컨텍스트 그룹 전환이 필요한지 여부
    currentCOOPEnforcementResult브라우징 컨텍스트 그룹 전환이 필요한지 여부
    보고 전용으로 인해 브라우징 컨텍스트 그룹 전환이 필요할지 여부
    currentCOOPEnforcementResult보고 전용으로 인해 브라우징 컨텍스트 그룹 전환이 필요할지 여부
    url
    responseURL
    origin
    responseOrigin
    교차 출처 오프너 정책
    responseCOOP
    현재 컨텍스트가 탐색 소스인지 여부
    true
  2. isInitialAboutBlankbrowsingContext활성 문서초기 about:blank 상태로 설정하십시오.

  3. 만약 isInitialAboutBlank이 true이고 browsingContext초기 URL이 null이라면, browsingContext초기 URLresponseURL로 설정하십시오.

  4. 만약 COOP 값이 브라우징 컨텍스트 그룹 전환을 요구하는지 확인한 결과가 true라면:

    1. newCOOPEnforcementResult브라우징 컨텍스트 그룹 전환이 필요한지 여부를 true로 설정하십시오.

    2. 만약 browsingContext그룹브라우징 컨텍스트 집합크기가 1보다 크다면:

      1. COOP 응답으로 탐색할 때 브라우징 컨텍스트 그룹 전환에 대한 위반 보고서를 대기열에 추가하십시오. 이때 responseCOOP, "enforce", responseURL, currentCOOPEnforcementResulturl, currentCOOPEnforcementResultorigin, responseOrigin, 그리고 referrer를 사용하십시오.

      2. COOP 응답으로부터 탐색할 때 브라우징 컨텍스트 그룹 전환에 대한 위반 보고서를 대기열에 추가하십시오. 이때 currentCOOPEnforcementResult교차 출처 오프너 정책, "enforce", currentCOOPEnforcementResulturl, responseURL, currentCOOPEnforcementResultorigin, responseOrigin, 그리고 currentCOOPEnforcementResult현재 컨텍스트가 탐색 소스인지 여부를 사용하십시오.

  5. 만약 보고 전용 COOP을 강제 적용할 때 브라우징 컨텍스트 그룹 전환이 필요한지 확인한 결과가 true라면:

    1. result보고 전용으로 인해 브라우징 컨텍스트 그룹 전환이 필요할지 여부를 true로 설정하십시오.

    2. 만약 browsingContext그룹브라우징 컨텍스트 집합크기가 1보다 크다면:

      1. COOP 응답으로 탐색할 때 브라우징 컨텍스트 그룹 전환에 대한 보고 전용 위반 보고서를 대기열에 추가하십시오. 이때 responseCOOP, "reporting", responseURL, currentCOOPEnforcementResulturl, currentCOOPEnforcementResultorigin, responseOrigin, 그리고 referrer를 사용하십시오.

      2. COOP 응답으로부터 탐색할 때 브라우징 컨텍스트 그룹 전환에 대한 보고 전용 위반 보고서를 대기열에 추가하십시오. 이때 currentCOOPEnforcementResult교차 출처 오프너 정책, "reporting", currentCOOPEnforcementResulturl, responseURL, currentCOOPEnforcementResultorigin, 그리고 currentCOOPEnforcementResult현재 컨텍스트가 탐색 소스인지 여부를 사용하십시오.

  6. newCOOPEnforcementResult를 반환하십시오.

탐색 응답에 사용할 브라우징 컨텍스트를 얻으려면, 다음과 같은 경우를 가정하십시오. 브라우징 컨텍스트 browsingContext, 샌드박싱 플래그 세트 sandboxFlags, 교차 출처 오프너 정책 navigationCOOP, 그리고 교차 출처 오프너 정책 강제 적용 결과 coopEnforcementResult를 사용하십시오:

  1. 만약 browsingContext최상위 브라우징 컨텍스트가 아니라면, browsingContext를 반환하십시오.

  2. 만약 coopEnforcementResult브라우징 컨텍스트 그룹 전환이 필요한지 여부가 false라면:

    1. 만약 coopEnforcementResult보고 전용으로 인해 브라우징 컨텍스트 그룹 전환이 필요할지 여부가 true라면, browsingContext가상 브라우징 컨텍스트 그룹 ID를 새로 고유하게 설정하십시오.

    2. browsingContext를 반환하십시오.

  3. newBrowsingContext새로운 최상위 브라우징 컨텍스트 및 문서 생성의 첫 번째 반환 값으로 설정하십시오.

    이 경우 브라우징 컨텍스트 그룹 교환이 수행됩니다. browsingContext는 새 문서 객체를 초기화하는 데 사용되지 않습니다. 다른 문서에도 사용되지 않는다면(예: 백/포워드 캐시의 경우), 사용자 에이전트는 이 시점에서 그것을 삭제할 수 있습니다.

  4. 만약 navigationCOOP이 "same-origin-plus-COEP"라면, newBrowsingContext그룹교차 출처 격리 모드를 "논리적" 또는 "구체적"으로 설정하십시오. 이 선택은 구현 정의입니다.

    일부 플랫폼에서는 교차 출처 격리 기능이 요구하는 보안 속성을 제공하는 것이 어렵습니다. "구체적"은 이에 접근할 수 있게 하고, "논리적"은 그렇지 않습니다.

  5. 만약 sandboxFlags가 비어 있지 않다면:

    1. 확인: navigationCOOP이 "unsafe-none"입니다.

    2. 확인: newBrowsingContext팝업 샌드박싱 플래그 세트비어 있습니다.

    3. newBrowsingContext팝업 샌드박싱 플래그 세트복제sandboxFlags로 설정하십시오.

  6. newBrowsingContext를 반환하십시오.

7.1.3.3 보고

액세서-액세스된 관계는 두 브라우징 컨텍스트 간의 액세스가 발생한 관계를 설명하는 열거형입니다. 다음 값들을 가질 수 있습니다:

액세서가 오프너임

액세서 브라우징 컨텍스트 또는 그 조상 중 하나가 액세스된 브라우징 컨텍스트최상위 브라우징 컨텍스트오프너 브라우징 컨텍스트인 경우.

액세서가 오프니임

액세스된 브라우징 컨텍스트 또는 그 조상 중 하나가 액세서 브라우징 컨텍스트최상위 브라우징 컨텍스트오프너 브라우징 컨텍스트인 경우.

없음

액세서 브라우징 컨텍스트와 액세스된 브라우징 컨텍스트, 또는 그들의 조상 간에 오프너 관계가 없는 경우.

브라우징 컨텍스트 accessoraccessed, JavaScript 속성 이름 P, 그리고 환경 설정 객체 environment를 주어 두 브라우징 컨텍스트 간의 액세스가 보고되어야 하는지 확인하려면:

  1. P교차 출처 접근 가능한 창 속성 이름이 아닌 경우, 반환하십시오.

  2. 확인: accessor활성 문서accessed활성 문서가 모두 완전히 활성화됨.

  3. accessorTopDocumentaccessor최상위 브라우징 컨텍스트활성 문서로 설정하십시오.

  4. accessorInclusiveAncestorOriginsaccessor활성 문서포함된 조상 탐색 가능 각각의 출처를 가져와 얻은 목록으로 설정하십시오.

  5. accessedTopDocumentaccessed최상위 브라우징 컨텍스트활성 문서로 설정하십시오.

  6. accessedInclusiveAncestorOriginsaccessed활성 문서포함된 조상 탐색 가능 각각의 출처를 가져와 얻은 목록으로 설정하십시오.

  7. 만약 accessorInclusiveAncestorOrigins 중 하나라도 accessorTopDocument출처동일 출처가 아니거나, accessedInclusiveAncestorOrigins 중 하나라도 accessedTopDocument출처동일 출처가 아닌 경우, 반환하십시오.

    이 방법은 교차 출처의 iframe에 대한 정보를 교차 출처 오프너 정책 보고를 사용한 최상위 프레임에 노출하지 않도록 합니다.

  8. 만약 accessor최상위 브라우징 컨텍스트가상 브라우징 컨텍스트 그룹 IDaccessed최상위 브라우징 컨텍스트가상 브라우징 컨텍스트 그룹 ID와 같은 경우, 반환하십시오.

  9. accessorAccessedRelationship액세서-액세스된 관계의 값으로 없음으로 설정하십시오.

  10. 만약 accessed최상위 브라우징 컨텍스트오프너 브라우징 컨텍스트accessor이거나, accessor조상인 경우, accessorAccessedRelationship액세서가 오프너임으로 설정하십시오.

  11. 만약 accessor최상위 브라우징 컨텍스트오프너 브라우징 컨텍스트accessed이거나, accessed조상인 경우, accessorAccessedRelationship액세서가 오프니임으로 설정하십시오.

  12. 액세스에 대한 위반 보고 큐에 추가, accessorAccessedRelationship, accessorTopDocument크로스 오리진 오프너 정책, accessedTopDocument크로스 오리진 오프너 정책, accessor활성 문서URL, accessed활성 문서URL, accessor최상위 탐색 문맥초기 URL, accessed최상위 탐색 문맥초기 URL, accessor활성 문서기원, accessed활성 문서기원, accessor최상위 탐색 문맥생성 시 오프너 기원, accessed최상위 탐색 문맥생성 시 오프너 기원, accessorTopDocument리퍼러, accessedTopDocument리퍼러, Penvironment을 가지고.

보고서에 보낼 URL을 정화하려면 URL url이 주어졌을 때:

  1. sanitizedURLurl의 복사본으로 설정하십시오.

  2. 사용자 이름을 설정하여 sanitizedURL과 빈 문자열을 전달하십시오.

  3. 비밀번호를 설정하여 sanitizedURL과 빈 문자열을 전달하십시오.

  4. 정화된 URL의 직렬화sanitizedURL조각 제외 설정이 true로 설정된 상태에서 반환하십시오.

COOP 응답으로 이동할 때 브라우징 컨텍스트 그룹 전환에 대한 위반 보고를 대기열에 추가하려면 교차 출처 오프너 정책 coop, 문자열 disposition, URL coopURL, URL previousResponseURL, 두 개의 출처 coopOriginpreviousResponseOrigin, 그리고 참조자 referrer가 주어졌을 때:

  1. 만약 coop보고서 엔드포인트가 null이면 반환하십시오.

  2. coopValuecoop으로 설정하십시오.

  3. 만약 disposition이 "reporting"이면, coopValuecoop보고 전용 값으로 설정하십시오.

  4. serializedReferrer를 빈 문자열로 설정하십시오.

  5. 만약 referrerURL이면, serializedReferrerreferrer직렬화로 설정하십시오.

  6. body를 다음 속성을 포함하는 새 객체로 설정하십시오:

    disposition disposition
    effectivePolicy coopValue
    previousResponseURL 만약 coopOriginpreviousResponseOrigin동일 출처이면, previousResponseURL정화된 URL로 설정하십시오. 그렇지 않으면 null로 설정하십시오.
    referrer serializedReferrer
    type "navigation-to-response"
  7. 대기열 body를 "coop"로 설정하고, coop보고서 엔드포인트coopURL을 사용하십시오.

COOP 응답에서 벗어날 때 브라우징 컨텍스트 그룹 전환에 대한 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 문자열 disposition, URL coopURL, URL nextResponseURL, 두 개의 출처 coopOriginnextResponseOrigin, 그리고 boolean isCOOPResponseNavigationSource가 주어졌을 때:

  1. 만약 coop보고 엔드포인트가 null이면 반환.

  2. coopValuecoop으로 설정.

  3. 만약 disposition이 "reporting"이면, coopValuecoop보고 전용 값으로 설정.

  4. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition disposition
    effectivePolicy coopValue
    nextResponseURL 만약 coopOriginnextResponseOrigin동일 출처이거나 isCOOPResponseNavigationSource가 true이면, URL을 정화하여 nextResponseURL을 사용. 그렇지 않으면 null.
    type "navigation-from-response"
  5. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURL을 사용.

액세스에 대한 위반 보고를 대기열에 추가하기 위해, 주어진 액세서-액세스드 관계 accessorAccessedRelationship, 두 개의 교차 출처 오프너 정책 accessorCOOPaccessedCOOP, 네 개의 URL accessorURL, accessedURL, accessorInitialURL, accessedInitialURL, 네 개의 출처 accessorOrigin, accessedOrigin, accessorCreatorOriginaccessedCreatorOrigin, 두 개의 리퍼러 accessorReferreraccessedReferrer, 문자열 propertyName, 그리고 환경 설정 객체 environment가 주어졌을 때:

  1. 만약 coop보고 엔드포인트가 null이면 반환.

  2. coopValuecoop으로 설정.

  3. 만약 disposition이 "reporting"이면, coopValuecoop보고 전용 값으로 설정.

  4. 만약 accessorAccessedRelationship액세서가 오프너라면:

    1. 열린 창에 대한 액세스 위반 보고를 대기열에 추가를 실행, 주어진 accessorCOOP, accessorURL, accessedURL, accessedInitialURL, accessorOrigin, accessedOrigin, accessedCreatorOrigin, propertyName, 그리고 environment.

    2. 오프너에서의 액세스 위반 보고를 대기열에 추가를 실행, 주어진 accessedCOOP, accessedURL, accessorURL, accessedOrigin, accessorOrigin, propertyName, 그리고 accessedReferrer.

  5. 그렇지 않고, 만약 accessorAccessedRelationship액세서가 오프니라면:

    1. 오프너에 대한 액세스 위반 보고를 대기열에 추가를 실행, 주어진 accessorCOOP, accessorURL, accessedURL, accessorOrigin, accessedOrigin, propertyName, accessorReferrer, 그리고 environment.

    2. 열린 창에서의 액세스 위반 보고를 대기열에 추가를 실행, 주어진 accessedCOOP, accessedURL, accessorURL, accessorInitialURL, accessedOrigin, accessorOrigin, accessorCreatorOrigin, 그리고 propertyName.

  6. 그렇지 않다면:

    1. 다른 창에 대한 액세스 위반 보고를 대기열에 추가를 실행, 주어진 accessorCOOP, accessorURL, accessedURL, accessorOrigin, accessedOrigin, propertyName, 그리고 environment.

    2. 다른 창에서의 액세스 위반 보고를 대기열에 추가를 실행, 주어진 accessedCOOP, accessedURL, accessorURL, accessedOrigin, accessorOrigin, 그리고 propertyName.

오프너에 대한 액세스 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 두 개의 URL coopURLopenerURL, 두 개의 출처 coopOriginopenerOrigin, 문자열 propertyName, 리퍼러 referrer, 그리고 환경 설정 객체 environment가 주어졌을 때:

  1. sourceFile, lineNumber, 그리고 columnNumber를 이 보고를 트리거한 관련 스크립트 URL 및 문제 발생 위치로 설정.

  2. serializedReferrer를 빈 문자열로 설정.

  3. 만약 referrerURL인 경우, serializedReferrerreferrer직렬화로 설정.

  4. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition "reporting"
    effectivePolicy coop보고 전용 값
    property propertyName
    openerURL 만약 coopOriginopenerOrigin동일 출처이면, openerURL정화된 URL을 사용하고, 그렇지 않으면 null.
    referrer serializedReferrer
    sourceFile sourceFile
    lineNumber lineNumber
    columnNumber columnNumber
    type "access-to-opener"
  5. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURLenvironment를 사용.

열린 창에 대한 액세스 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 세 개의 URL coopURL, openedWindowURLinitialWindowURL, 세 개의 출처 coopOrigin, openedWindowOrigin, 그리고 openerInitialOrigin, 문자열 propertyName, 그리고 환경 설정 객체 environment가 주어졌을 때:

  1. sourceFile, lineNumber, 그리고 columnNumber를 이 보고를 트리거한 관련 스크립트 URL 및 문제 발생 위치로 설정.

  2. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition "reporting"
    effectivePolicy coop보고 전용 값
    property propertyName
    openedWindowURL 만약 coopOriginopenedWindowOrigin동일 출처이면, openedWindowURL정화된 URL을 사용하고, 그렇지 않으면 null.
    openedWindowInitialURL 만약 coopOriginopenerInitialOrigin동일 출처이면, initialWindowURL정화된 URL을 사용하고, 그렇지 않으면 null.
    sourceFile sourceFile
    lineNumber lineNumber
    columnNumber columnNumber
    type "access-to-opener"
  3. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURLenvironment를 사용.

다른 창에 대한 액세스 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 두 개의 URL coopURLotherURL, 두 개의 출처 coopOriginotherOrigin, 문자열 propertyName, 그리고 환경 설정 객체 environment가 주어졌을 때:

  1. sourceFile, lineNumber, 그리고 columnNumber를 이 보고를 트리거한 관련 스크립트 URL 및 문제 발생 위치로 설정.

  2. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition "reporting"
    effectivePolicy coop보고 전용 값
    property propertyName
    otherURL 만약 coopOriginotherOrigin동일 출처이면, otherURL정화된 URL을 사용하고, 그렇지 않으면 null.
    sourceFile sourceFile
    lineNumber lineNumber
    columnNumber columnNumber
    type "access-to-opener"
  3. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURLenvironment를 사용.

오프너에서의 액세스에 대한 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 두 개의 URL coopURLopenerURL, 두 개의 출처 coopOriginopenerOrigin, 문자열 propertyName, 그리고 리퍼러 referrer가 주어졌을 때:

  1. 만약 coop보고 엔드포인트가 null이면, 반환.

  2. serializedReferrer를 빈 문자열로 설정.

  3. 만약 referrerURL인 경우, serializedReferrerreferrer직렬화로 설정.

  4. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition "reporting"
    effectivePolicy coop보고 전용 값
    property propertyName
    openerURL 만약 coopOriginopenerOrigin동일 출처이면, openerURL정화된 URL을 사용하고, 그렇지 않으면 null.
    referrer serializedReferrer
    type "access-to-opener"
  5. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURL을 사용.

열린 창에서의 액세스에 대한 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 세 개의 URL coopURL, openedWindowURLinitialWindowURL, 세 개의 출처 coopOrigin, openedWindowOrigin, 그리고 openerInitialOrigin, 그리고 문자열 propertyName이 주어졌을 때:

  1. 만약 coop보고 엔드포인트가 null이면, 반환.

  2. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition "reporting"
    effectivePolicy coopValue
    property coop보고 전용 값
    openedWindowURL 만약 coopOriginopenedWindowOrigin동일 출처이면, openedWindowURL정화된 URL을 사용하고, 그렇지 않으면 null.
    openedWindowInitialURL 만약 coopOriginopenerInitialOrigin동일 출처이면, initialWindowURL정화된 URL을 사용하고, 그렇지 않으면 null.
    type "access-to-opener"
  3. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURL을 사용.

다른 창에서의 액세스에 대한 위반 보고를 대기열에 추가하기 위해, 주어진 교차 출처 오프너 정책 coop, 두 개의 URL coopURLotherURL, 두 개의 출처 coopOriginotherOrigin, 그리고 문자열 propertyName이 주어졌을 때:

  1. 만약 coop보고 엔드포인트가 null이면, 반환.

  2. body를 다음 속성을 포함하는 새 객체로 설정:

    disposition "reporting"
    effectivePolicy coop보고 전용 값
    property propertyName
    otherURL 만약 coopOriginotherOrigin동일 출처이면, otherURL정화된 URL을 사용하고, 그렇지 않으면 null.
    type "access-to-opener"
  3. 대기열 body를 "coop"로 설정하고, coop보고 엔드포인트coopURL을 사용.

7.1.4 교차 출처 임베더 정책

Headers/Cross-Origin-Embedder-Policy

모든 현재 엔진에서 지원됩니다.

Firefox79+Safari15.2+Chrome83+
Opera?Edge83+
Edge (Legacy)?Internet Explorer지원 안 함
Firefox Android?Safari iOS?Chrome Android?WebView Android86+Samsung Internet?Opera Android?

임베더 정책 값은 리소스 소유자의 명시적 허가 없이 크로스 오리진 리소스를 가져오는 것을 제어하는 세 가지 문자열 중 하나입니다.

"unsafe-none"

이 값은 기본값입니다. 이 값을 사용할 때, 크로스 오리진 리소스는 CORS 프로토콜이나 `Cross-Origin-Resource-Policy` 헤더를 통해 명시적인 허가 없이도 가져올 수 있습니다.

"require-corp"

이 값을 사용할 때, 크로스 오리진 리소스를 가져오려면 서버의 명시적인 허가가 CORS 프로토콜이나 `Cross-Origin-Resource-Policy` 헤더를 통해 필요합니다.

"credentialless"

이 값을 사용할 때, 크로스 오리진 no-CORS 리소스를 가져오는 경우 자격 증명이 생략됩니다. 그 대가로 명시적인 `Cross-Origin-Resource-Policy` 헤더는 필요하지 않습니다. 자격 증명이 포함된 다른 요청은 CORS 프로토콜이나 `Cross-Origin-Resource-Policy` 헤더를 통해 서버의 명시적인 허가가 필요합니다.

"credentialless"를 지원하기 전에, 구현자들은 다음 두 가지를 지원하는 것이 강력히 권장됩니다:

그렇지 않으면 공격자들이 클라이언트의 네트워크 위치를 이용해 비공개 리소스를 읽을 수 있게 되어, 교차 출처 격리 기능을 악용할 수 있습니다.

임베더 정책 값이 "credentialless" 또는 "require-corp"일 때, 교차 출처 격리와 호환됩니다.

임베더 정책은 다음으로 구성됩니다:

"coep" 보고 유형은 값이 "coep"인 보고 유형입니다. 이 보고 유형은 ReportingObserver에게 표시됩니다.

7.1.4.1 헤더

`Cross-Origin-Embedder-Policy`와 `Cross-Origin-Embedder-Policy-Report-Only` HTTP 응답 헤더는 서버가 임베더 정책환경 설정 객체에 대해 선언할 수 있도록 합니다. 이 헤더들은 구조화된 헤더로, 그 값은 토큰이어야 합니다. [STRUCTURED-FIELDS]

유효한 토큰 값은 임베더 정책 값입니다. 토큰에는 부가적으로 파라미터가 포함될 수 있습니다; 이 중 "report-to" 파라미터는 적절한 보고 엔드포인트를 식별하는 유효한 URL 문자열을 가질 수 있습니다. [REPORTING]

처리 모델은 (기본적으로 "unsafe-none") 헤더가 토큰으로 구문 분석될 수 없는 경우 열림 상태로 실패합니다. 여기에는 응답 내에 있는 여러 인스턴스의 `Cross-Origin-Embedder-Policy` 헤더를 결합하여 우발적으로 생성된 리스트도 포함됩니다:

`Cross-Origin-Embedder-Policy` 최종 임베더 정책 값
헤더가 전달되지 않음 "unsafe-none"
`require-corp` "require-corp"
`unknown-value` "unsafe-none"
`require-corp, unknown-value` "unsafe-none"
`unknown-value, unknown-value` "unsafe-none"
`unknown-value, require-corp` "unsafe-none"
`require-corp, require-corp` "unsafe-none"

(이는 `Cross-Origin-Embedder-Policy-Report-Only`에도 동일하게 적용됩니다.)


응답 response환경 environment에서 임베더 정책을 획득하기 위해:

  1. policy를 새로운 임베더 정책으로 설정합니다.

  2. environment비보안 컨텍스트인 경우, policy를 반환합니다.

  3. parsedItem구조화된 필드 값을 얻는 것의 결과로 설정합니다. `Cross-Origin-Embedder-Policy`와 "item"을 response헤더 목록에서 가져옵니다.

  4. parsedItem이 null이 아니고 parsedItem[0]이 교차 출처 격리와 호환되는 경우:

    1. policyparsedItem[0]으로 설정합니다.

    2. parsedItem[1]["report-to"] 존재하는 경우, policy엔드포인트parsedItem[1]["report-to"]로 설정합니다.

  5. parsedItem구조화된 필드 값을 얻는 것의 결과로 설정합니다. `Cross-Origin-Embedder-Policy-Report-Only`와 "item"을 response헤더 목록에서 가져옵니다.

  6. parsedItem이 null이 아니고 parsedItem[0]이 교차 출처 격리와 호환되는 경우:

    1. policy보고 전용 값parsedItem[0]으로 설정합니다.

    2. parsedItem[1]["report-to"] 존재하는 경우, policy엔드포인트parsedItem[1]["report-to"]로 설정합니다.

  7. policy를 반환합니다.

7.1.4.2 임베더 정책 확인

응답 response, 탐색 가능 객체 navigable임베더 정책 responsePolicy을 가지고 내비게이션 응답이 자신의 임베더 정책을 준수하는지 확인하기 위해:

  1. navigable자식 탐색 가능 객체이 아니면, true를 반환합니다.

  2. parentPolicynavigable컨테이너 문서정책 컨테이너임베더 정책으로 설정합니다.

  3. 만약 parentPolicy보고 전용 값교차 출처 격리와 호환되고 responsePolicy이 그렇지 않다면, response, "navigation", parentPolicy보고 전용 보고 엔드포인트, "reporting", 및 navigable컨테이너 문서관련 설정 객체를 사용하여 교차 출처 임베더 정책 상속 위반을 큐에 추가합니다.

  4. 만약 parentPolicy교차 출처 격리와 호환되지 않거나, responsePolicy교차 출처 격리와 호환된다면 true를 반환합니다.

  5. response, "navigation", parentPolicy보고 엔드포인트, "enforce", 및 navigable컨테이너 문서관련 설정 객체를 사용하여 교차 출처 임베더 정책 상속 위반을 큐에 추가합니다.

  6. false를 반환합니다.

WorkerGlobalScope workerGlobalScope, 환경 설정 객체 owner응답 response를 가지고 글로벌 객체의 임베더 정책을 확인하기 위해:

  1. workerGlobalScopeDedicatedWorkerGlobalScope 객체가 아니면, true를 반환합니다.

  2. policyworkerGlobalScope임베더 정책으로 설정합니다.

  3. ownerPolicyowner정책 컨테이너임베더 정책으로 설정합니다.

  4. 만약 ownerPolicy보고 전용 값교차 출처 격리와 호환되고, policy이 그렇지 않다면, response, "worker initialization", ownerPolicy보고 전용 보고 엔드포인트, "reporting", 및 owner를 사용하여 교차 출처 임베더 정책 상속 위반을 큐에 추가합니다.

  5. 만약 ownerPolicy교차 출처 격리와 호환되지 않거나, policy교차 출처 격리와 호환된다면 true를 반환합니다.

  6. response, "worker initialization", ownerPolicy보고 엔드포인트, "enforce", 및 owner를 사용하여 교차 출처 임베더 정책 상속 위반을 큐에 추가합니다.

  7. false를 반환합니다.

응답 response, 문자열 type, 문자열 endpoint, 문자열 disposition환경 설정 객체 settings를 가지고 교차 출처 임베더 정책 상속 위반을 큐에 추가하기 위해:

  1. serialized보고를 위한 응답 URL 직렬화의 결과로 설정합니다.

  2. body를 다음 속성을 포함하는 새로운 객체로 설정합니다:

    type type
    blockedURL serialized
    disposition disposition
  3. 큐에 추가합니다 bodyendpoint에서 settings에 대한 "coep" 보고 유형으로.

7.1.5 샌드박싱

샌드박싱 플래그 세트는 잠재적으로 신뢰할 수 없는 리소스의 기능을 제한하기 위해 사용되는 다음 플래그 중 하나 이상의 집합입니다:

샌드박스 내비게이션 브라우징 컨텍스트 플래그

이 플래그는 샌드박스된 브라우징 컨텍스트 자체 외의 브라우징 컨텍스트(또는 그 안에 더 중첩된 브라우징 컨텍스트), 보조 브라우징 컨텍스트 (이는 다음에 정의된 샌드박스된 보조 내비게이션 브라우징 컨텍스트 플래그에 의해 보호됨), 및 최상위 브라우징 컨텍스트 (이는 아래에 정의된 사용자 활성화 없는 최상위 내비게이션 샌드박스 브라우징 컨텍스트 플래그사용자 활성화 있는 최상위 내비게이션 샌드박스 브라우징 컨텍스트 플래그에 의해 보호됨)로의 이동을 방지합니다.

만약 샌드박스된 보조 내비게이션 브라우징 컨텍스트 플래그가 설정되지 않은 경우, 특정 상황에서는 팝업(새로운 최상위 브라우징 컨텍스트)을 여는 것이 허용될 수 있습니다. 이 브라우징 컨텍스트는 항상 하나의 허용된 샌드박스 내비게이터를 가지고 있으며, 이는 브라우징 컨텍스트가 생성될 때 설정되어 그들을 생성한 브라우징 컨텍스트가 실제로 이를 탐색할 수 있도록 합니다. (그렇지 않으면, 샌드박스 내비게이션 브라우징 컨텍스트 플래그는 팝업이 열렸을 때조차 탐색을 방지할 것입니다.)

샌드박스된 보조 내비게이션 브라우징 컨텍스트 플래그

이 플래그는 새로운 보조 브라우징 컨텍스트를 생성하는 것을 방지합니다. 예를 들어, target 속성이나 window.open() 메서드를 사용하는 경우가 해당됩니다.

사용자 활성화 없는 최상위 내비게이션 샌드박스 브라우징 컨텍스트 플래그

이 플래그는 최상위 브라우징 컨텍스트를 탐색하지 못하게 하고, 최상위 브라우징 컨텍스트를 닫는 것을 방지합니다. 이는 샌드박스된 브라우징 컨텍스트의 활성 창일시적 활성화가 없을 때만 적용됩니다.

사용자 활성화 없는 최상위 내비게이션 샌드박스 브라우징 컨텍스트 플래그가 설정되지 않은 경우, 콘텐츠는 최상위 브라우징 컨텍스트를 탐색할 수 있지만, 다른 브라우징 컨텍스트는 여전히 샌드박스 내비게이션 브라우징 컨텍스트 플래그샌드박스된 보조 내비게이션 브라우징 컨텍스트 플래그에 의해 보호될 수 있습니다.

사용자 활성화 있는 최상위 내비게이션 샌드박스 브라우징 컨텍스트 플래그

이 플래그는 최상위 브라우징 컨텍스트를 탐색하지 못하게 하고, 최상위 브라우징 컨텍스트를 닫는 것을 방지합니다. 이는 샌드박스된 브라우징 컨텍스트의 활성 창일시적 활성화가 있을 때만 적용됩니다.

사용자 활성화 없는 최상위 내비게이션 샌드박스 브라우징 컨텍스트 플래그와 마찬가지로, 이 플래그는 최상위 브라우징 컨텍스트에만 영향을 미치며, 설정되지 않은 경우에도 다른 브라우징 컨텍스트는 여전히 다른 플래그에 의해 보호될 수 있습니다.

샌드박스된 원본 브라우징 컨텍스트 플래그

이 플래그는 콘텐츠를 불투명한 원본으로 강제하여 동일한 원본의 다른 콘텐츠에 접근하지 못하도록 방지합니다.

이 플래그는 또한 스크립트가 document.cookie IDL 속성에서 읽거나 쓰는 것을 방지하고, localStorage에 대한 접근을 차단합니다.

샌드박스된 폼 브라우징 컨텍스트 플래그

이 플래그는 폼 제출을 차단합니다.

샌드박스된 포인터 잠금 브라우징 컨텍스트 플래그

이 플래그는 포인터 잠금 API를 비활성화합니다. [POINTERLOCK]

샌드박스된 스크립트 브라우징 컨텍스트 플래그

이 플래그는 스크립트 실행을 차단합니다.

샌드박스된 자동 기능 브라우징 컨텍스트 플래그

이 플래그는 비디오 자동 재생 또는 폼 컨트롤 자동 초점과 같은 자동으로 트리거되는 기능을 차단합니다.

샌드박스된 document.domain 브라우징 컨텍스트 플래그

이 플래그는 콘텐츠가 document.domain 세터를 사용하는 것을 방지합니다.

샌드박스가 보조 브라우징 컨텍스트로 전파되는 플래그

이 플래그는 콘텐츠가 생성하는 보조 브라우징 컨텍스트가 콘텐츠의 활성 샌드박싱 플래그 세트를 상속받도록 하여 샌드박스를 벗어나지 못하게 합니다.

샌드박스된 모달 플래그

이 플래그는 콘텐츠가 모달 대화 상자를 생성하기 위해 다음 기능 중 어느 것도 사용할 수 없도록 방지합니다:

샌드박스된 화면 방향 잠금 브라우징 컨텍스트 플래그

이 플래그는 화면 방향을 잠그는 기능을 비활성화합니다. [SCREENORIENTATION]

샌드박스된 프레젠테이션 브라우징 컨텍스트 플래그

이 플래그는 프레젠테이션 API를 비활성화합니다. [PRESENTATION]

샌드박스된 다운로드 브라우징 컨텍스트 플래그

이 플래그는 다운로드 하이퍼링크를 통해 또는 다운로드로 처리되는 내비게이션을 통해 콘텐츠가 다운로드를 시작하거나 인스턴스화하지 못하도록 방지합니다. 다운로드로 처리됨.

샌드박스된 사용자 정의 프로토콜 내비게이션 브라우징 컨텍스트 플래그

이 플래그는 페치 스킴이 아닌 프로토콜로의 내비게이션이 외부 소프트웨어로의 전달되지 않도록 방지합니다.

사용자 에이전트가 문자열 input, 샌드박싱 플래그 세트 output을 가지고 샌드박싱 지시문을 파싱해야 할 때, 다음 단계를 실행해야 합니다:

  1. ASCII 공백으로 input을 분할하여 tokens를 얻습니다.

  2. output을 비워 둡니다.

  3. 다음 플래그를 output에 추가합니다:


모든 최상위 브라우징 컨텍스트팝업 샌드박싱 플래그 세트를 가지고 있으며, 이는 샌드박싱 플래그 세트입니다. 브라우징 컨텍스트가 생성될 때, 해당 팝업 샌드박싱 플래그 세트는 비워져 있어야 합니다. 이는 탐색 가능한 항목을 선택하는 규칙탐색 응답을 위한 브라우징 컨텍스트를 얻는 알고리즘에 의해 채워집니다.

모든 iframe 요소는 iframe 샌드박싱 플래그 세트를 가지고 있으며, 이는 샌드박싱 플래그 세트입니다. 특정 시간에 iframe 샌드박싱 플래그 세트에 설정된 플래그는 iframe 요소의 샌드박스 속성에 의해 결정됩니다.

모든 Document활성 샌드박싱 플래그 세트를 가지고 있으며, 이는 샌드박싱 플래그 세트입니다. Document가 생성될 때, 해당 활성 샌드박싱 플래그 세트는 비워져 있어야 합니다. 이는 탐색 알고리즘에 의해 채워집니다.

모든 CSP 목록 cspListCSP 파생 샌드박싱 플래그를 가지고 있으며, 이는 샌드박싱 플래그 세트입니다. 이는 다음 알고리즘의 반환 값입니다:

  1. directives를 빈 순서가 있는 집합으로 설정합니다.

  2. cspList의 정책에 대해:

    1. 만약 policy처분이 "enforce"가 아니라면, 계속합니다.

    2. 만약 policy지침 세트가 "샌드박스"라는 이름을 가진 지침포함한다면, 해당 지침을 directives추가합니다.

  3. directives가 비어 있다면, 빈 샌드박싱 플래그 세트를 반환합니다.

  4. directivedirectives[directives크기 − 1]로 설정합니다.

  5. 샌드박싱 지시문을 파싱한 결과를 directive로 반환합니다.


브라우징 컨텍스트 browsing context의 생성 샌드박싱 플래그를 결정하기 위해, null 또는 요소 embedder를 가지고, 다음 샌드박싱 플래그 세트에 존재하는 플래그들의 합집합을 반환합니다:

7.1.6 정책 컨테이너

정책 컨테이너구조체로, Document, WorkerGlobalScope, 또는 WorkletGlobalScope에 적용되는 정책을 포함합니다. 이는 다음과 같은 항목을 포함합니다:

다른 정책들을 정책 컨테이너로 이동하십시오.

정책 컨테이너를 복제하기 위해, 정책 컨테이너 policyContainer를 사용합니다:

  1. clone을 새로운 정책 컨테이너로 설정합니다.

  2. policypolicyContainerCSP 목록에서 cloneCSP 목록으로 복사하여 추가합니다.

  3. clone임베더 정책policyContainer임베더 정책의 복사본으로 설정합니다.

  4. clone리퍼러 정책policyContainer리퍼러 정책으로 설정합니다.

  5. clone을 반환합니다.

url 정책 컨테이너를 기록에 저장해야 하는지를 결정하려면:

  1. 만약 url스킴이 "blob"이라면, false를 반환합니다.

  2. 만약 url로컬이라면, true를 반환합니다.

  3. false를 반환합니다.

페치 응답에서 정책 컨테이너 생성을 수행하기 위해, 응답 response환경-또는-null environment가 주어졌을 때:

  1. 만약 responseURL스킴이 "blob"이라면, 정책 컨테이너를 복제한 결과를 responseURLblob URL 항목환경정책 컨테이너로 반환합니다.

  2. result를 새로운 정책 컨테이너로 설정합니다.

  3. resultCSP 목록response가 주어진 상태에서 응답의 콘텐츠 보안 정책을 파싱한 결과로 설정합니다.

  4. 만약 environment가 null이 아니면, result임베더 정책responseenvironment를 가지고 임베더 정책을 얻는 결과로 설정합니다. 그렇지 않으면 "unsafe-none"으로 설정합니다.

  5. result리퍼러 정책response를 가지고 리퍼러-정책 헤더를 파싱한 결과로 설정합니다. [REFERRERPOLICY]

  6. result을 반환합니다.

탐색 매개변수 정책 컨테이너 결정을 위해 URL responseURL과 네 개의 정책 컨테이너-또는-null historyPolicyContainer, initiatorPolicyContainer, parentPolicyContainer, 및 responsePolicyContainer가 주어졌을 때:

  1. 만약 historyPolicyContainer가 null이 아니라면:

    1. 단언: responseURL정책 컨테이너를 기록에 저장해야 하는지 요구합니다.

    2. historyPolicyContainer복제본을 반환합니다.

  2. 만약 responseURLabout:srcdoc라면:

    1. 단언: parentPolicyContainer가 null이 아닙니다.

    2. parentPolicyContainer복제본을 반환합니다.

  3. 만약 responseURL로컬이고 initiatorPolicyContainer가 null이 아니라면 initiatorPolicyContainer복제본을 반환합니다.

  4. 만약 responsePolicyContainer가 null이 아니라면 responsePolicyContainer을 반환합니다.

  5. 새로운 정책 컨테이너를 반환합니다.

작업자 글로벌 스코프의 정책 컨테이너를 초기화하기 위해, WorkerGlobalScope workerGlobalScope, 응답 response, 및 환경 environment가 주어졌을 때:

  1. 만약 workerGlobalScopeurl로컬이지만, 그 스킴이 "blob"이 아니라면:

    1. 단언: workerGlobalScope소유자 세트크기가 1임을 단언합니다.

    2. workerGlobalScope정책 컨테이너workerGlobalScope소유자 세트[0]의 관련 설정 객체정책 컨테이너복제본으로 설정합니다.

  2. 그 외의 경우, workerGlobalScope정책 컨테이너responseenvironment가 주어졌을 때 페치 응답에서 정책 컨테이너 생성의 결과로 설정합니다.

7.2.1 Window, WindowProxy, 및 Location 객체에 대한 보안 인프라

일반적으로 객체는 출처 간에 접근할 수 없지만, 웹 플랫폼은 웹이 의존하는 몇 가지 기존 예외가 없으면 웹 플랫폼 자체를 충실하게 유지할 수 없습니다.

이 섹션은 JavaScript 사양의 용어와 타이포그래피 규칙을 사용합니다. [JAVASCRIPT]

7.2.1.1 IDL과의 통합

보안 검사를 수행할 때, platformObject, identifier, 및 type이 주어지면, 다음 단계를 수행합니다:

  1. 만약 platformObjectWindow 또는 Location 객체가 아니라면, 반환합니다.

  2. e에 대해 CrossOriginProperties(platformObject):

    1. 만약 SameValue(e.[[Property]], identifier)가 true이면:

      1. 만약 type이 "method"이고 e에 [[NeedsGet]] 또는 [[NeedsSet]]이 없다면, 반환합니다.

      2. 그렇지 않고, 만약 type이 "getter"이고 e.[[NeedsGet]]이 true라면, 반환합니다.

      3. 그렇지 않고, 만약 type이 "setter"이고 e.[[NeedsSet]]이 true라면, 반환합니다.

  3. 만약 IsPlatformObjectSameOrigin(platformObject)이 false이면, "SecurityError" DOMException을 발생시킵니다.

7.2.1.2 공유된 내부 슬롯: [[CrossOriginPropertyDescriptorMap]]

WindowLocation 객체는 모두 [[CrossOriginPropertyDescriptorMap]] 내부 슬롯을 가지고 있으며, 그 값은 처음에 비어 있는 맵입니다.

[[CrossOriginPropertyDescriptorMap]] 내부 슬롯은 (currentGlobal, objectGlobal, propertyKey) 튜플을 키로 하고 속성 설명자를 값으로 가지는 맵을 포함하며, 이는 currentGlobalWindow 또는 Location 객체를 objectGlobal에서 검사할 때 스크립트에 보이는 내용을 메모이제이션한 것입니다. 이는 나중에 조회할 때 CrossOriginGetOwnPropertyHelper에 의해 게으르게 채워집니다.

사용자 에이전트는 값의 어떤 부분에 대한 참조도 없을 때, 맵에 보관된 값과 그에 상응하는 키를 가비지 수집할 수 있도록 허용해야 합니다. 즉, 가비지 수집이 관찰되지 않는 한 가능합니다.

예를 들어, const href = Object.getOwnPropertyDescriptor(crossOriginLocation, "href").set를 사용할 경우, 값과 그에 해당하는 키는 관찰될 수 있으므로 가비지 수집되지 않습니다.

사용자 에이전트는 document.domain이 설정되면 맵에서 키-값 쌍을 제거하는 최적화를 수행할 수 있습니다. 이는 document.domain이 이전 값을 다시 참조할 수 없으므로 관찰되지 않습니다.

예를 들어, www.example.com에서 document.domain을 "example.com"으로 설정하면, 사용자 에이전트는 키의 일부가 www.example.com인 모든 키-값 쌍을 맵에서 제거할 수 있습니다. 이는 www.example.com이 다시는 출처의 일부가 될 수 없으므로 해당 값을 맵에서 다시 조회할 수 없기 때문입니다.

7.2.1.3 공유된 추상 연산
7.2.1.3.1 CrossOriginProperties (O)
  1. 단언: OLocation 또는 Window 객체입니다.

  2. 만약 OLocation 객체라면, 다음을 반환합니다: « { [[Property]]: "href", [[NeedsGet]]: false, [[NeedsSet]]: true }, { [[Property]]: "replace" } ».

  3. 다음을 반환합니다: « { [[Property]]: "window", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "self", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "location", [[NeedsGet]]: true, [[NeedsSet]]: true }, { [[Property]]: "close" }, { [[Property]]: "closed", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "focus" }, { [[Property]]: "blur" }, { [[Property]]: "frames", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "length", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "top", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "opener", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "parent", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "postMessage" } ».

이 추상 연산은 Completion Record를 반환하지 않습니다.

인덱스된 속성들은 이 알고리즘에서 safelisting될 필요가 없습니다. 이는 WindowProxy 객체에 의해 직접 처리됩니다.

JavaScript 속성 이름 P는 "window", "self", "location", "close", "closed", "focus", "blur", "frames", "length", "top", "opener", "parent", "postMessage" 또는 배열 인덱스 속성 이름일 때 cross-origin 접근 가능한 window 속성 이름입니다.

7.2.1.3.2 CrossOriginPropertyFallback (P)
  1. 만약 P가 "then", %Symbol.toStringTag%, %Symbol.hasInstance%, 또는 %Symbol.isConcatSpreadable%라면, 다음을 반환합니다: PropertyDescriptor{ [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

  2. "SecurityError" DOMException을 발생시킵니다.

7.2.1.3.3 IsPlatformObjectSameOrigin (O)
  1. 만약 현재 설정 객체출처O관련 설정 객체출처동일 출처 도메인이면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

이 추상 연산은 Completion Record를 반환하지 않습니다.

여기서 현재 설정 객체는 대략적으로 "호출자"에 해당합니다. 왜냐하면 이 검사는 getter/setter/메서드와 관련된 실행 컨텍스트JavaScript 실행 컨텍스트 스택에 올라가기 전에 수행되기 때문입니다. 예를 들어, 코드 w.document에서 이 단계는 document getter에 도달하기 전에 [[Get]] 알고리즘의 일부로 호출됩니다.

7.2.1.3.4 CrossOriginGetOwnPropertyHelper (O, P)

이 추상 연산이 undefined를 반환하고 사용자 정의 동작이 없는 경우, 호출자는 "SecurityError" DOMException을 발생시켜야 합니다. 실제로는 호출자가 CrossOriginPropertyFallback을 호출하여 이를 처리합니다.

  1. crossOriginKey현재 설정 객체, O관련 설정 객체, 그리고 P로 구성된 튜플로 정의합니다.

  2. CrossOriginProperties(O)의 각 e에 대해:

    1. 만약 SameValue(e.[[Property]], P)가 true이면:

      1. 만약 O[[CrossOriginPropertyDescriptorMap]] 내부 슬롯의 값이 crossOriginKey를 키로 하는 엔트리를 포함하고 있다면, 해당 엔트리의 값을 반환합니다.

      2. originalDescOrdinaryGetOwnProperty(O, P)로 정의합니다.

      3. crossOriginDesc를 undefined로 정의합니다.

      4. 만약 e.[[NeedsGet]] 및 e.[[NeedsSet]]이 존재하지 않는다면:

        1. valueoriginalDesc.[[Value]]로 정의합니다.

        2. 만약 IsCallable(value)가 true라면, value현재 영역에서 생성된 익명 내장 함수로 설정하며, 이는 객체 O에서 IDL 연산 P와 동일한 단계를 수행합니다.

        3. crossOriginDescPropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }로 설정합니다.

      5. 그 외의 경우:

        1. crossOriginGet를 undefined로 정의합니다.

        2. 만약 e.[[NeedsGet]]이 true라면, crossOriginGet현재 영역에서 생성된 익명 내장 함수로 설정하며, 이는 객체 O에서 IDL 속성 P의 getter와 동일한 단계를 수행합니다.

        3. crossOriginSet를 undefined로 정의합니다.

        4. 만약 e.[[NeedsSet]]이 true라면, crossOriginSet현재 영역에서 생성된 익명 내장 함수로 설정하며, 이는 객체 O에서 IDL 속성 P의 setter와 동일한 단계를 수행합니다.

        5. crossOriginDescPropertyDescriptor{ [[Get]]: crossOriginGet, [[Set]]: crossOriginSet, [[Enumerable]]: false, [[Configurable]]: true }로 설정합니다.

      6. O[[CrossOriginPropertyDescriptorMap]] 내부 슬롯에 crossOriginKey를 키로 하고 crossOriginDesc를 값으로 가지는 엔트리를 생성합니다.

      7. crossOriginDesc를 반환합니다.

  3. undefined를 반환합니다.

이 추상 연산은 Completion Record를 반환하지 않습니다.

여기에서 생성된 속성 설명자가 설정 가능하도록 한 이유는 JavaScript 명세서에서 요구하는 내부 필수 메서드의 불변성을 보존하기 위함입니다. 특히, 속성의 값이 탐색의 결과로 변경될 수 있기 때문에, 속성이 설정 가능하도록 하는 것이 요구됩니다. (그러나 호환성 문제로 인해 이러한 불변성을 보존할 수 없는 경우가 있습니다. 이와 관련된 내용은 tc39/ecma262 이슈 #672 및 이 명세서의 다른 참조에서 확인할 수 있습니다.) [JAVASCRIPT]

이 속성 설명자가 동일 출처 동작과 일치하지 않음에도 불구하고 열거되지 않도록 설정한 이유는 기존 웹 콘텐츠와의 호환성을 위해서입니다. 자세한 내용은 이슈 #3183를 참조하십시오.

7.2.1.3.5 CrossOriginGet (O, P, Receiver)
  1. desc를 ? O.[[GetOwnProperty]](P)로 정의합니다.

  2. Assert: desc가 undefined가 아님을 확인합니다.

  3. 만약 IsDataDescriptor(desc)가 true이면, desc.[[Value]]를 반환합니다.

  4. Assert: IsAccessorDescriptor(desc)가 true임을 확인합니다.

  5. getterdesc.[[Get]]로 정의합니다.

  6. 만약 getter가 undefined이면, "SecurityError" DOMException을 발생시킵니다.

  7. ? Call(getter, Receiver)을 반환합니다.

7.2.1.3.6 CrossOriginSet (O, P, V, Receiver)
  1. desc를 ? O.[[GetOwnProperty]](P)로 정의합니다.

  2. Assert: desc가 undefined가 아님을 확인합니다.

  3. 만약 desc.[[Set]]이 존재하고 그 값이 undefined가 아니면:

    1. ? Call(setter, Receiver, « V »)을 수행합니다.

    2. true를 반환합니다.

  4. "SecurityError" DOMException을 발생시킵니다.

7.2.1.3.7 CrossOriginOwnPropertyKeys (O)
  1. keys를 새로 빈 목록으로 정의합니다.

  2. CrossOriginProperties(O)의 각 e에 대해, e.[[Property]]를 keys추가합니다.

  3. keys와 « "then", %Symbol.toStringTag%, %Symbol.hasInstance%, %Symbol.isConcatSpreadable% »의 연결을 반환합니다.

이 추상 연산은 Completion Record를 반환하지 않습니다.

7.2.2 Window 객체

Window

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
[Global=Window,
Exposed=Window,
LegacyUnenumerableNamedProperties]
interface Window : EventTarget {
  // 현재 브라우징 컨텍스트
  [LegacyUnforgeable] readonly attribute WindowProxy window;
  [Replaceable] readonly attribute WindowProxy self;
  [LegacyUnforgeable] readonly attribute Document document;
  attribute DOMString name; 
  [PutForwards=href, LegacyUnforgeable] readonly attribute Location location;
  readonly attribute History history;
  readonly attribute Navigation navigation;
  readonly attribute CustomElementRegistry customElements;
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  attribute DOMString status;
  undefined close();
  readonly attribute boolean closed;
  undefined stop();
  undefined focus();
  undefined blur();

  // 다른 브라우징 컨텍스트
  [Replaceable] readonly attribute WindowProxy frames;
  [Replaceable] readonly attribute unsigned long length;
  [LegacyUnforgeable] readonly attribute WindowProxy? top;
  attribute any opener;
  [Replaceable] readonly attribute WindowProxy? parent;
  readonly attribute Element? frameElement;
  WindowProxy? open(optional USVString url = "", optional DOMString target = "_blank", optional [LegacyNullToEmptyString] DOMString features = "");

  // 이 객체는 글로벌 객체이므로, IDL 명명된 getter는 NamedPropertiesObject 별난 객체를 프로토타입 체인에 추가합니다.
  // 사실, 이는 글로벌 객체를 별난 객체로 만들지 않습니다.
  // 인덱스 접근은 WindowProxy 별난 객체에 의해 처리됩니다.
  getter object (DOMString name);

  // 사용자 에이전트
  readonly attribute Navigator navigator;
  [Replaceable] readonly attribute Navigator clientInformation; // .navigator의 레거시 별명
  readonly attribute boolean originAgentCluster;

  // 사용자 프롬프트
  undefined alert();
  undefined alert(DOMString message);
  boolean confirm(optional DOMString message = "");
  DOMString? prompt(optional DOMString message = "", optional DOMString default = "");
  undefined print();

  undefined postMessage(any message, USVString targetOrigin, optional sequence<object> transfer = []);
  undefined postMessage(any message, optional WindowPostMessageOptions options = {});

  // 폐기된 멤버도 포함
};
Window includes GlobalEventHandlers;
Window includes WindowEventHandlers;

dictionary WindowPostMessageOptions : StructuredSerializeOptions {
  USVString targetOrigin = "/";
};
window.window

Window/window

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.frames

Window/frames

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.self

Window/self

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이 속성들은 모두 window를 반환합니다.

window.document

Window/document

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

window과 연결된 Document를 반환합니다.

document.defaultView

Document/defaultView

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

document과 연결된 Window를 반환하며, 없을 경우 null을 반환합니다.

Window 객체에는 Document 객체인 연관된 Document가 있습니다. 이는 Document 객체입니다. 이 객체는 Window 객체가 생성될 때 설정되며, 초기 about:blank Document에서 탐색이 이루어질 때만 변경됩니다.

Window탐색 컨텍스트는 해당 연관된 Document탐색 컨텍스트입니다. 이는 null이거나 탐색 컨텍스트입니다.

Window탐색 가능탐색 가능으로, 해당 Window연관된 Document활성 문서인 것이며, 그런 탐색 가능이 없다면 null입니다.

window, frames, 및 self 접근자 단계는 this관련 영역의 [[GlobalEnv]].[[GlobalThisValue]]를 반환하는 것입니다.

document 접근자 단계는 this연관된 Document를 반환하는 것입니다.

Document 객체는 Window 객체와 연관되어 있으며, 이 객체는 새로운 Document 객체를 생성하는 탐색 알고리즘이 탐색 컨텍스트에서 처음으로 페이지를 로드할 때 한 번 변경될 수 있습니다. 이 특정 경우에는 초기 about:blank 페이지의 Window 객체가 재사용되며 새로운 Document 객체를 얻게 됩니다.

defaultView 접근자 단계는 다음과 같습니다:

  1. this탐색 컨텍스트가 null이라면, null을 반환합니다.

  2. this탐색 컨텍스트WindowProxy 객체를 반환합니다.


HTMLDocument

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

역사적인 이유로 Window 객체는 HTMLDocument라는 이름의 쓰기 가능, 설정 가능, 열거 불가능한 속성을 가져야 하며, 그 값은 Document 인터페이스 객체여야 합니다.

7.2.2.1 윈도우 열기 및 닫기
window = window.open([ url [, target [, features ] ] ])

Window/open

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

새 창을 열어 url을 표시합니다 (기본값은 "about:blank") 및 이를 반환합니다. target (기본값은 "_blank")은 새 창의 이름을 제공합니다. 해당 이름을 가진 창이 이미 존재하면 해당 창이 재사용됩니다. features 인수는 쉼표로 구분된 토큰 집합을 포함할 수 있습니다:

"noopener"
"noreferrer"

이들은 하이퍼링크에서 noopenernoreferrer 링크 타입과 동일하게 동작합니다.

"popup"

새 창에 최소한의 웹 브라우저 사용자 인터페이스를 제공하도록 사용자 에이전트에 권장합니다. (모든 BarProp 객체에서 visible 접근자에도 영향을 미칩니다.)

globalThis.open("https://email.example/message/CAOOOkFcWW97r8yg=SsWg7GgCmp4suVX9o85y8BvNRqMjuc5PXg", undefined, "noopener,popup");
window.name [ = value ]

Window/name

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

창의 이름을 반환합니다.

이름을 변경할 수 있습니다.

window.close()

Window/close

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

창을 닫습니다.

window.closed

Window/closed

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

창이 닫힌 경우 true를 반환하고, 그렇지 않은 경우 false를 반환합니다.

window.stop()

Window/stop

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)14+Internet Explorer지원 안 됨
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

문서 로드를 취소합니다.

윈도우 열기 단계는 문자열 url, 문자열 target 및 문자열 features가 주어졌을 때 다음과 같이 수행됩니다:

  1. 만약 이벤트 루프종료 중첩 레벨이 0이 아니면, null을 반환합니다.

  2. sourceDocument엔트리 글로벌 객체연관된 Document로 설정합니다.

  3. 만약 target이 빈 문자열이면, target을 "_blank"로 설정합니다.

  4. tokenizedFeaturesfeatures를 토큰화한 결과로 설정합니다.

  5. noopenernoreferrer를 false로 설정합니다.

  6. 만약 tokenizedFeatures["noopener"]가 존재하면:

    1. noopenertokenizedFeatures["noopener"]를 불리언 특징으로 파싱한 결과로 설정합니다.

    2. tokenizedFeatures["noopener"]를 제거합니다.

  7. 만약 tokenizedFeatures["noreferrer"]가 존재하면:

    1. noreferrertokenizedFeatures["noreferrer"]를 불리언 특징으로 파싱한 결과로 설정합니다.

    2. tokenizedFeatures["noreferrer"]를 제거합니다.

  8. referrerPolicy를 빈 문자열로 설정합니다.

  9. 만약 noreferrer가 true이면, noopener를 true로 설정하고 referrerPolicy를 "no-referrer"로 설정합니다.

  10. targetNavigablewindowType탐색 가능한 객체를 선택하는 규칙target, sourceDocument노드 탐색 가능한 객체noopener를 사용하여 적용한 결과로 설정합니다.

    만약 링크를 클릭하여 새 탭에서 열 수 있는 사용자 에이전트가 있고, 사용자가 새 탭에서 열기 위해 Control-클릭을 수행하고, onclick 핸들러가 window.open() API를 사용하여 페이지를 iframe 요소에 열 경우, 사용자 에이전트는 선택된 타겟 브라우징 컨텍스트 대신 새 탭을 타겟으로 할 수 있습니다.

  11. 만약 targetNavigable이 null이면, null을 반환합니다.

  12. 만약 windowType이 "new and unrestricted" 또는 "new with no opener" 중 하나이면:

    1. targetNavigable활성 브라우징 컨텍스트팝업 여부팝업 창이 요청되었는지 확인한 결과로 설정합니다. tokenizedFeatures가 주어졌을 때.

    2. 브라우징 컨텍스트 기능 설정targetNavigable활성 브라우징 컨텍스트에 대해 수행합니다. [CSSOMVIEW]에 따라 tokenizedFeatures가 주어졌을 때.

    3. urlRecordURL 레코드로 설정합니다. about:blank.

    4. 만약 url이 빈 문자열이 아니면, urlRecordURL 인코딩-파싱 결과로 설정합니다. url엔트리 설정 객체를 기준으로.

    5. 만약 urlRecord가 실패하면, "SyntaxError" DOMException을 던집니다.

    6. 만약 urlRecordabout:blank와 일치하면, targetNavigable활성 문서urlRecord가 주어졌을 때 URL 및 기록 업데이트 단계를 수행합니다.

      이것은 urlabout:blank?foo와 같은 경우에 필요합니다. 만약 url이 단순히 about:blank라면, 이 단계는 아무 일도 하지 않습니다.

    7. 그렇지 않으면, 탐색targetNavigable에 대해 수행합니다. sourceDocument를 사용하여, referrerPolicyreferrerPolicy로 설정하고 예외 활성화를 true로 설정합니다.

  13. 그렇지 않으면:

    1. 만약 url이 빈 문자열이 아니면:

      1. urlRecordURL 인코딩-파싱 결과로 설정합니다. url엔트리 설정 객체를 기준으로.

      2. 만약 urlRecord가 실패하면, "SyntaxError" DOMException을 던집니다.

      3. 탐색targetNavigable에 대해 수행합니다. sourceDocument를 사용하여, referrerPolicyreferrerPolicy로 설정하고 예외 활성화를 true로 설정합니다.

    2. 만약 noopener가 false이면, targetNavigable활성 브라우징 컨텍스트오프너 브라우징 컨텍스트sourceDocument브라우징 컨텍스트로 설정합니다.

  14. 만약 noopener가 true이거나 windowType이 "new with no opener"이면, null을 반환합니다.

  15. targetNavigable활성 WindowProxy를 반환합니다.

open(url, target, features) 메서드 단계는 url, target, features가 주어졌을 때 윈도우 열기 단계를 수행하는 것입니다.

이 메서드는 기존 브라우징 컨텍스트탐색하거나, 보조 브라우징 컨텍스트를 열고 탐색하는 메커니즘을 제공합니다.


features 인수를 토큰화하려면:

  1. tokenizedFeatures를 새 순서가 있는 맵으로 설정합니다.

  2. positionfeatures의 첫 번째 코드 포인트로 설정합니다.

  3. 반복하며 positionfeatures의 끝을 지나지 않는 동안:

    1. name을 빈 문자열로 설정합니다.

    2. value를 빈 문자열로 설정합니다.

    3. 코드 포인트 시퀀스를 수집하여, features에서 position을 기준으로 피처 구분자를 만납니다. 이 과정은 이름 앞의 선행 구분자를 건너뜁니다.

    4. 코드 포인트 시퀀스를 수집하여, features에서 position을 기준으로 피처 구분자가 아닌 코드를 만납니다. 수집된 문자를 name으로 설정하고, ASCII 소문자로 변환합니다.

    5. name피처 이름을 정규화한 결과로 설정합니다.

    6. 반복하며 positionfeatures의 끝을 지나지 않고, featuresposition에 있는 코드 포인트가 U+003D (=)가 아닌 동안:

      1. 만약 featuresposition에 있는 코드 포인트가 U+002C (,)이거나, 피처 구분자가 아니면, 반복을 중단합니다.

      2. position을 1만큼 증가시킵니다.

      이는 첫 번째 U+003D (=)로 건너뛰지만, U+002C (,)나 비구분자를 지나지 않습니다.

    7. 만약 featuresposition에 있는 코드 포인트가 피처 구분자인 경우:

      1. positionfeatures의 끝을 지나지 않고, featuresposition에 있는 코드 포인트가 피처 구분자인 동안:

        1. 만약 featuresposition에 있는 코드 포인트가 U+002C (,)이면, 반복을 중단합니다.

        2. position을 1만큼 증가시킵니다.

        이는 첫 번째 비구분자로 건너뛰지만, U+002C (,)를 지나지 않습니다.

      2. 코드 포인트 시퀀스를 수집하여, features에서 position을 기준으로 피처 구분자가 아닌 코드 포인트를 만납니다. value를 수집된 코드 포인트로 설정하고, ASCII 소문자로 변환합니다.

    8. 만약 name이 빈 문자열이 아니면, tokenizedFeatures[name]을 value로 설정합니다.

  4. tokenizedFeatures를 반환합니다.

윈도우 피처가 설정되어 있는지 확인하려면, tokenizedFeatures, featureNamedefaultValue가 주어졌을 때:

  1. 만약 tokenizedFeatures[featureName]이 존재하면, tokenizedFeatures[featureName]을 불리언 피처로 파싱한 결과를 반환합니다.

  2. defaultValue를 반환합니다.

팝업 윈도우가 요청되었는지 확인하려면, tokenizedFeatures가 주어졌을 때:

  1. 만약 tokenizedFeatures비어 있으면, false를 반환합니다.

  2. 만약 tokenizedFeatures["popup"]이 존재하면, tokenizedFeatures["popup"]을 불리언 피처로 파싱한 결과를 반환합니다.

  3. location윈도우 피처가 설정되어 있는지 확인한 결과로 설정합니다. tokenizedFeatures, "location", 및 false를 기준으로.

  4. toolbar윈도우 피처가 설정되어 있는지 확인한 결과로 설정합니다. tokenizedFeatures, "toolbar", 및 false를 기준으로.

  5. 만약 locationtoolbar가 모두 false이면, true를 반환합니다.

  6. menubar윈도우 피처가 설정되어 있는지 확인한 결과로 설정합니다. tokenizedFeatures, "menubar", 및 false를 기준으로.

  7. 만약 menubar가 false이면, true를 반환합니다.

  8. resizable윈도우 피처가 설정되어 있는지 확인한 결과로 설정합니다. tokenizedFeatures, "resizable", 및 true를 기준으로.

  9. 만약 resizable가 false이면, true를 반환합니다.

  10. scrollbars윈도우 피처가 설정되어 있는지 확인한 결과로 설정합니다. tokenizedFeatures, "scrollbars", 및 false를 기준으로.

  11. 만약 scrollbars가 false이면, true를 반환합니다.

  12. status윈도우 피처가 설정되어 있는지 확인한 결과로 설정합니다. tokenizedFeatures, "status", 및 false를 기준으로.

  13. 만약 status가 false이면, true를 반환합니다.

  14. false를 반환합니다.

코드 포인트가 피처 구분자이려면, ASCII 공백 문자이거나, U+003D (=) 또는 U+002C (,)이어야 합니다.

레거시 이유로 인해 일부 피처 이름에는 몇 가지 별칭이 있습니다. 피처 이름을 정규화하려면 name을 기준으로 스위치를 전환하십시오:

"screenx"
"left"를 반환합니다.
"screeny"
"top"을 반환합니다.
"innerwidth"
"width"를 반환합니다.
"innerheight"
"height"을 반환합니다.
그 외의 경우
name을 반환합니다.

불리언 피처를 파싱하려면, 문자열 value가 주어졌을 때:

  1. 만약 value가 빈 문자열이면, true를 반환합니다.

  2. 만약 value가 "yes"라면, true를 반환합니다.

  3. 만약 value가 "true"라면, true를 반환합니다.

  4. parsed정수를 파싱하는 규칙에 따라 value를 파싱한 결과로 설정합니다.

  5. 만약 parsed가 오류라면, 0으로 설정합니다.

  6. 만약 parsed가 0이면 false를 반환하고, 그렇지 않으면 true를 반환합니다.


name getter 단계는:

  1. 만약 thisnavigable이 null이면, 빈 문자열을 반환합니다.

  2. thisnavigable대상 이름을 반환합니다.

name setter 단계는:

  1. 만약 thisnavigable이 null이면, 반환합니다.

  2. thisnavigable활성 세션 기록 항목문서 상태탐색 대상 이름을 주어진 값으로 설정합니다.

탐색 가능 항목이 다른 출처탐색될 때 이름이 재설정됩니다.


close() 메서드 단계는:

  1. thisTraversablethisnavigable로 설정합니다.

  2. 만약 thisTraversable최상위 탐색 가능 항목이 아니면, 반환합니다.

  3. 만약 thisTraversableis closing이 true이면, 반환합니다.

  4. browsingContextthisTraversable활성 브라우징 컨텍스트로 설정합니다.

  5. sourceSnapshotParamsthisTraversable활성 문서를 기준으로 스냅샷 소스 스냅샷 매개변수를 스냅샷하는 결과로 설정합니다.

  6. 다음 조건이 모두 true이면:

    다음과 같이 합니다:

    1. thisTraversableis closing을 true로 설정합니다.

    2. 작업을 큐에 추가하여 DOM 조작 작업 소스에서 thisTraversable닫습니다.

탐색 가능 항목스크립트로 닫을 수 있는 경우, 활성 브라우징 컨텍스트보조 브라우징 컨텍스트이고, 이 컨텍스트가 스크립트에 의해 생성된 경우(사용자의 동작에 의한 것이 아닌 경우), 또는 최상위 탐색 가능 항목세션 기록 항목크기가 1인 경우입니다.

closed getter 단계는 this브라우징 컨텍스트가 null이거나, is closing이 true이면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

stop() 메서드 단계는:

  1. 만약 thisnavigable이 null이면, 반환합니다.

  2. 로드 중지 thisnavigable.

7.2.2.2 Window 객체에 대한 인덱스 접근
window.length

Window/length

현재 모든 엔진에서 지원합니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

문서 트리 자식 탐색 가능 항목의 수를 반환합니다.

window[index]

지정된 문서 트리 자식 탐색 가능 항목에 해당하는 WindowProxy를 반환합니다.

length getter 단계는 this연결된 문서문서 트리 자식 탐색 가능 항목크기를 반환합니다.

문서 트리 자식 탐색 가능 항목에 대한 인덱스 접근은 WindowProxy 객체의 [[GetOwnProperty]] 내부 메서드를 통해 정의됩니다.

7.2.2.3 Window 객체에 대한 이름 접근
window[name]

지정된 요소 또는 요소 집합을 반환합니다.

일반적으로 이 API를 사용하는 것은 코드의 견고성을 떨어뜨릴 수 있습니다. 웹 플랫폼에 새로운 기능이 추가됨에 따라 이 API에 매핑되는 ID가 시간이 지남에 따라 변경될 수 있습니다. 대신 document.getElementById() 또는 document.querySelector()를 사용하세요.

Window 객체 window문서 트리 자식 탐색 가능 대상 이름 속성 집합은 다음 단계들을 실행하여 반환되는 값입니다:

  1. childrenwindow연결된 문서문서 트리 자식 탐색 가능 항목으로 설정합니다.

  2. firstNamedChildren을 빈 순서가 있는 집합으로 설정합니다.

  3. navigable에 대해 children을 반복합니다:

    1. namenavigable대상 이름으로 설정합니다.

    2. name이 빈 문자열이면 계속 진행합니다.

    3. firstNamedChildrenname이 같은 탐색 가능 항목포함하고 있으면, 계속 진행합니다.

    4. navigablefirstNamedChildren에 추가합니다.

  4. names를 빈 순서가 있는 집합으로 설정합니다.

  5. navigable에 대해 firstNamedChildren을 반복합니다:

    1. namenavigable대상 이름으로 설정합니다.

    2. navigable활성 문서출처window관련 설정 객체출처동일 출처라면, namenames에 추가합니다.

  6. names을 반환합니다.

아래 예제와 같이 https://example.org/에 호스팅된 페이지에서, https://elsewhere.example/window.name을 "spices"로 설정했다고 가정하면, 모든 것이 로드된 후 window.spices를 평가하면 undefined가 반환됩니다:

<iframe src=https://elsewhere.example.com/></iframe>
<iframe name=spices></iframe>

Window 객체는 이름 지정 속성을 지원합니다. window지원되는 속성 이름은 각 속성을 기여한 요소에 따라 트리 순서로 구성되며, 나중에 추가된 중복 항목은 무시됩니다:

이름이 지정된 속성의 값을 결정하기 위해 name을 사용하여 Window 객체 window에서 다음 단계를 사용하여 반환된 값을 반환합니다:

  1. objectswindow의 이름이 name이름이 지정된 객체의 목록으로 설정합니다.

    이 알고리즘이 실행되지 않았다면 해당 속성은 존재하지 않으므로 적어도 하나 이상의 객체가 있어야 합니다.

  2. objects탐색 가능 항목이 포함되어 있다면:

    1. containerwindow연결된 문서후손objects에 포함된 콘텐츠 탐색 가능 항목이 있는 첫 번째 탐색 가능 컨테이너로 설정합니다.

    2. container콘텐츠 탐색 가능 항목활성 WindowProxy를 반환합니다.

  3. 그렇지 않고 objects에 하나의 요소만 있는 경우 해당 요소를 반환합니다.

  4. 그렇지 않으면, window연관된 Document에 루트를 둔 HTMLCollection을 반환하며, 해당 컬렉션의 필터는 window의 이름 name과 일치하는 이름이 지정된 객체들만 매칭합니다. (정의에 따라, 이들은 모두 요소가 됩니다.)

이름이 지정된 객체들Window 객체 window에서 위 알고리즘의 목적을 위해 다음과 같이 구성됩니다:

Window 인터페이스는 [Global] 확장 속성을 가지고 있으므로, 그 이름 속성들은 이름 지정 속성 객체의 규칙을 따르며, 레거시 플랫폼 객체의 규칙은 따르지 않습니다.

window.top

Window/top

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

최상위 탐색 가능한 WindowProxy에 대한 참조를 반환합니다.

window.opener [ = value ]

Window/opener

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

열린 탐색 문맥에 대한 WindowProxy를 반환합니다.

해당 문맥이 없거나 null로 설정된 경우 null을 반환합니다.

null로 설정할 수 있습니다.

window.parent

Window/parent

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1.3+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

부모 탐색 가능한 WindowProxy를 반환합니다.

window.frameElement

Window/frameElement

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

탐색 가능한 컨테이너 요소를 반환합니다.

해당 요소가 없거나 교차 출처 상황에서 null을 반환합니다.

top 속성의 getter 단계는 다음과 같습니다:

  1. 현재 navigable가 null인 경우, null을 반환합니다.

  2. 현재 navigable의 최상위 탐색 가능한 WindowProxy를 반환합니다.

opener 속성의 getter 단계는 다음과 같습니다:

  1. 현재 browsing context가 null인 경우, null을 반환합니다.

  2. 현재 opener browsing context가 null인 경우, null을 반환합니다.

  3. 현재 opener browsing contextWindowProxy 객체를 반환합니다.

opener 속성의 setter 단계는 다음과 같습니다:

  1. 지정된 값이 null인 경우, 현재의 browsing contextopener browsing context를 null로 설정합니다.

  2. 지정된 값이 null이 아닌 경우, opener 속성 값을 설정합니다.

window.opener를 null로 설정하면 opener 브라우징 컨텍스트 참조가 삭제됩니다. 실제로 이는 이후 스크립트가 opener 브라우징 컨텍스트Window 객체에 접근하지 못하도록 방지합니다.

기본적으로 스크립트는 opener 브라우징 컨텍스트Window 객체에 window.opener getter를 통해 접근할 수 있습니다. 예를 들어, 스크립트는 window.opener.location을 설정하여 opener 브라우징 컨텍스트를 탐색할 수 있습니다.

parent 속성의 getter 단계는 다음과 같습니다:

  1. 현재 navigable가 null인 경우, null을 반환합니다.

  2. 현재 navigable의 부모가 존재하는 경우, 해당 부모의 WindowProxy를 반환합니다.

frameElement 속성의 getter 단계는 다음과 같습니다:

  1. 현재 node navigable가 null인 경우, null을 반환합니다.

  2. 현재의 컨테이너를 반환합니다. 해당 컨테이너가 없거나 교차 출처 상황인 경우 null을 반환합니다.

다음과 같은 경우 이 속성들이 null을 반환할 수 있습니다:

<!DOCTYPE html>
<iframe></iframe>

<script>
"use strict";
const element = document.querySelector("iframe");
const iframeWindow = element.contentWindow;
element.remove();

console.assert(iframeWindow.top === null);
console.assert(iframeWindow.parent === null);
console.assert(iframeWindow.frameElement === null);
</script>

여기서 iframeWindow에 해당하는 탐색 문맥은 element가 문서에서 제거될 때 무효화됩니다.

7.2.2.5 역사적인 브라우저 인터페이스 요소 API

역사적인 이유로 Window 인터페이스에는 특정 웹 브라우저 인터페이스 요소의 가시성을 나타내는 일부 속성이 있었습니다.

개인정보 보호 및 상호 운용성의 이유로, 이러한 속성들은 이제 Window탐색 컨텍스트팝업 여부 속성이 true인지 false인지를 나타내는 값을 반환합니다.

각 인터페이스 요소는 BarProp 객체로 표시됩니다:

BarProp

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
[Exposed=Window]
interface BarProp {
  readonly attribute boolean visible;
};
window.locationbar.visible

Window/locationbar

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
window.menubar.visible

Window/menubar

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
window.personalbar.visible

Window/personalbar

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.scrollbars.visible

Window/scrollbars

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.statusbar.visible

Window/statusbar

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
window.toolbar.visible

Window/toolbar

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?

Window가 팝업이 아니면 true를 반환합니다. 그렇지 않으면 false를 반환합니다.

BarProp/visible

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android?

visible의 getter 단계는 다음과 같습니다:

  1. browsingContextthis관련 전역 객체탐색 컨텍스트로 설정하십시오.

  2. browsingContext가 null이면 true를 반환하십시오.

  3. browsingContext최상위 탐색 컨텍스트팝업 여부의 부정을 반환하십시오.

다음 BarProp 객체는 각 Window 객체에 대해 존재해야 합니다:

주소 표시줄 BarProp 객체
역사적으로 브라우저의 주소 표시줄을 나타내는 제어를 포함하는 사용자 인터페이스 요소를 나타냈습니다.
메뉴 막대 BarProp 객체
역사적으로 메뉴 형식의 명령 목록이나 유사한 인터페이스 개념을 포함하는 사용자 인터페이스 요소를 나타냈습니다.
개인 도구 모음 BarProp 객체
역사적으로 사용자의 즐겨찾기 페이지 링크 또는 유사한 인터페이스 개념을 포함하는 사용자 인터페이스 요소를 나타냈습니다.
스크롤바 BarProp 객체
역사적으로 스크롤 메커니즘 또는 유사한 인터페이스 개념을 포함하는 사용자 인터페이스 요소를 나타냈습니다.
상태 표시줄 BarProp 객체
역사적으로 문서 바로 아래 또는 뒤에 위치하는 사용자 인터페이스 요소를 나타내며, 일반적으로 진행 중인 네트워크 활동이나 사용자의 포인팅 장치가 현재 가리키는 요소에 대한 정보를 제공합니다.
도구 모음 BarProp 객체
역사적으로 문서 바로 위 또는 앞에 위치하는 사용자 인터페이스 요소를 나타내며, 일반적으로 세션 기록 탐색 컨트롤(뒤로 및 앞으로 버튼, 새로 고침 버튼 등)을 제공합니다.

locationbar 속성은 주소 표시줄 BarProp 객체를 반환해야 합니다.

menubar 속성은 메뉴 막대 BarProp 객체를 반환해야 합니다.

personalbar 속성은 개인 도구 모음 BarProp 객체를 반환해야 합니다.

scrollbars 속성은 스크롤바 BarProp 객체를 반환해야 합니다.

statusbar 속성은 상태 표시줄 BarProp 객체를 반환해야 합니다.

toolbar 속성은 도구 모음 BarProp 객체를 반환해야 합니다.


역사적인 이유로, status 속성은 Window 객체에서 마지막으로 설정된 문자열을 반환해야 하며, 설정 시 새로운 값으로 설정되어야 합니다. Window 객체가 생성될 때 이 속성은 빈 문자열로 설정되어야 합니다. 이 외에는 다른 기능을 수행하지 않습니다.

7.2.2.6 Window 객체에 대한 스크립트 설정

창 환경 설정 객체를 설정하려면, 주어진 URL creationURL, 자바스크립트 실행 컨텍스트 execution context, null 또는 환경 reservedEnvironment, URL topLevelCreationURL, 그리고 기원 topLevelOrigin을 사용하여 다음 단계를 수행하십시오:

  1. realmexecution context의 Realm 구성 요소 값으로 설정하십시오.

  2. windowrealm전역 객체로 설정하십시오.

  3. settings object를 새 환경 설정 객체로 설정하십시오. 해당 객체의 알고리즘은 다음과 같이 정의됩니다:

    realm 실행 컨텍스트

    execution context를 반환하십시오.

    모듈 맵

    window연관된 Document모듈 맵을 반환하십시오.

    API 기본 URL

    window연관된 Document의 현재 기본 URL을 반환하십시오.

    기원

    window기원을 반환하십시오. window연관된 Document에서.

    정책 컨테이너

    window정책 컨테이너를 반환하십시오. window연관된 Document에서.

    교차 출처 격리 기능

    다음 두 가지가 모두 참인 경우 true를 반환하고, 그렇지 않으면 false를 반환하십시오:

    시간 기원

    window연관된 Document로드 타이밍 정보탐색 시작 시간을 반환하십시오.

  4. reservedEnvironment가 null이 아닌 경우 다음을 수행하십시오:

    1. settings objectidreservedEnvironmentid, 대상 탐색 컨텍스트reservedEnvironment대상 탐색 컨텍스트로, 그리고 settings object활성 서비스 워커reservedEnvironment활성 서비스 워커로 설정하십시오.

    2. reservedEnvironmentid를 빈 문자열로 설정하십시오.

      예약된 환경의 ID는 생성된 환경 설정 객체에 완전히 이전된 것으로 간주됩니다. 이 시점부터 예약된 환경은 환경id로 검색할 수 없습니다.

  5. 그렇지 않은 경우, settings objectid를 새로운 고유 불투명 문자열로 설정하고, settings object대상 탐색 컨텍스트를 null로 설정하며, settings object활성 서비스 워커를 null로 설정하십시오.

  6. settings object생성 URLcreationURL로, settings object최상위 생성 URLtopLevelCreationURL로, 그리고 settings object최상위 기원topLevelOrigin으로 설정하십시오.

  7. realm의 [[HostDefined]] 필드를 settings object로 설정하십시오.

7.2.3 WindowProxy 이국적 객체

WindowProxy는 이국적 객체로, Window 일반 객체를 감싸고, 대부분의 작업을 래핑된 객체를 통해 간접적으로 수행합니다. 각 탐색 컨텍스트에는 연관된 WindowProxy 객체가 있습니다. 탐색 컨텍스트이동될 때, 탐색 컨텍스트의 연관된 WindowProxy 객체에 의해 감싸진 Window 객체가 변경됩니다.

WindowProxy 이국적 객체는 명시적으로 아래에 달리 명시된 경우를 제외하고 일반적인 내부 메서드를 사용해야 합니다.

WindowProxy 인터페이스 객체는 존재하지 않습니다.

모든 WindowProxy 객체에는 래핑된 Window 객체를 나타내는 [[Window]] 내부 슬롯이 있습니다.

WindowProxy는 "프록시"라는 이름이 붙어 있지만, 실제 프록시처럼 대상의 내부 메서드에 대해 다형성 디스패치를 수행하지 않습니다. 이는 WindowProxyLocation 객체 간의 기계를 재사용하기 위한 것입니다. Window 객체가 일반 객체로 남아 있는 한, 이는 관찰할 수 없으며 양쪽으로 구현될 수 있습니다.

7.2.3.1 [[GetPrototypeOf]] ( )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. IsPlatformObjectSameOrigin(W)이 참이면, OrdinaryGetPrototypeOf(W)를 반환하십시오.

  3. null을 반환하십시오.

7.2.3.2 [[SetPrototypeOf]] ( V )
  1. ! SetImmutablePrototype(this, V)를 반환하십시오.

7.2.3.3 [[IsExtensible]] ( )
  1. true를 반환하십시오.

7.2.3.4 [[PreventExtensions]] ( )
  1. false를 반환하십시오.

7.2.3.5 [[GetOwnProperty]] ( P )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. P배열 인덱스 속성 이름인 경우:

    1. index를 ! ToUint32(P)로 설정하십시오.

    2. childrenW연관된 Document문서 트리 자식 내비게이블로 설정하십시오.

    3. value를 undefined로 설정하십시오.

    4. indexchildren크기보다 작으면 다음을 수행하십시오:

      1. 오름차순으로 정렬children에서 navigableAnavigableB보다 작으면 navigableA컨테이너navigableB컨테이너보다 W연관된 Document에 더 먼저 삽입된 경우입니다.

      2. valuechildren[index]의 활성 WindowProxy로 설정하십시오.

    5. value가 undefined인 경우 다음을 수행하십시오:

      1. IsPlatformObjectSameOrigin(W)이 참이면 undefined를 반환하십시오.

      2. "SecurityError" DOMException을 던지십시오.

    6. PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: true }를 반환하십시오.

  3. IsPlatformObjectSameOrigin(W)이 참이면 ! OrdinaryGetOwnProperty(W, P)를 반환하십시오.

    이는 기존 웹 콘텐츠와의 호환성을 유지하기 위해 자바스크립트 명세의 의도적인 위반입니다. 자세한 내용은 tc39/ecma262 issue #672를 참조하십시오. [JAVASCRIPT]

  4. propertyCrossOriginGetOwnPropertyHelper(W, P)로 설정하십시오.

  5. property가 undefined가 아니면 property를 반환하십시오.

  6. property가 undefined이고 PW문서 트리 자식 내비게이블 대상 이름 속성 세트에 포함된 경우 다음을 수행하십시오:

    1. value를 이름이 PW명명된 객체활성 WindowProxy로 설정하십시오.

    2. PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }를 반환하십시오.

      속성 설명자가 열거할 수 없는 이유는 동일 출처 동작과 일치하지 않음에도 불구하고 기존 웹 콘텐츠와의 호환성을 유지하기 위함입니다. 자세한 내용은 issue #3183를 참조하십시오.

  7. ? CrossOriginPropertyFallback(P)를 반환하십시오.

7.2.3.6 [[DefineOwnProperty]] ( P, Desc )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. IsPlatformObjectSameOrigin(W)이 참이면:

    1. P배열 인덱스 속성 이름인 경우, false를 반환하십시오.

    2. ? OrdinaryDefineOwnProperty(W, P, Desc)를 반환하십시오.

      이는 기존 웹 콘텐츠와의 호환성을 유지하기 위해 자바스크립트 명세의 의도적인 위반입니다. 자세한 내용은 tc39/ecma262 issue #672를 참조하십시오. [JAVASCRIPT]

  3. "SecurityError" DOMException을 던지십시오.

7.2.3.7 [[Get]] ( P, Receiver )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. 두 탐색 컨텍스트 간의 액세스가 보고되어야 하는지 확인하십시오, 현재 전역 객체browsing context, Wbrowsing context, P현재 설정 객체를 고려하십시오.

  3. IsPlatformObjectSameOrigin(W)이 참이면, ? OrdinaryGet(this, P, Receiver)를 반환하십시오.

  4. ? CrossOriginGet(this, P, Receiver)를 반환하십시오.

OrdinaryGetCrossOriginGet[[GetOwnProperty]] 내부 메서드를 호출하므로, W 대신 this가 전달됩니다.

7.2.3.8 [[Set]] ( P, V, Receiver )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. 두 탐색 컨텍스트 간의 액세스가 보고되어야 하는지 확인하십시오, 현재 전역 객체browsing context, Wbrowsing context, P, 및 현재 설정 객체를 고려하십시오.

  3. IsPlatformObjectSameOrigin(W)이 참이면:

    1. P배열 인덱스 속성 이름인 경우, false를 반환하십시오.

    2. ? OrdinarySet(W, P, V, Receiver)를 반환하십시오.

  4. ? CrossOriginSet(this, P, V, Receiver)를 반환하십시오.

    CrossOriginSet[[GetOwnProperty]] 내부 메서드를 호출하므로, W 대신 this가 전달됩니다.

7.2.3.9 [[Delete]] ( P )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. IsPlatformObjectSameOrigin(W)이 참이면:

    1. P배열 인덱스 속성 이름인 경우:

      1. desc를 ! this.[[GetOwnProperty]](P)로 설정하십시오.

      2. desc가 undefined이면 true를 반환하십시오.

      3. false를 반환하십시오.

    2. ? OrdinaryDelete(W, P)를 반환하십시오.

  3. "SecurityError" DOMException을 던지십시오.

7.2.3.10 [[OwnPropertyKeys]] ( )
  1. Wthis[[Window]] 내부 슬롯의 값으로 설정하십시오.

  2. maxPropertiesW연관된 Document문서 트리 자식 내비게이블크기로 설정하십시오.

  3. keys범위 0부터 maxProperties까지(단, maxProperties는 제외)를 설정하십시오.

  4. IsPlatformObjectSameOrigin(W)이 참이면, keysOrdinaryOwnPropertyKeys(W)의 연결을 반환하십시오.

  5. keys와 ! CrossOriginOwnPropertyKeys(W)의 연결을 반환하십시오.

7.2.4 Location 인터페이스

Document/location

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Location

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Window/location

모든 최신 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Window 객체는 Window 객체가 생성될 때 할당되는 고유한 Location 객체 인스턴스와 연관되어 있습니다.

Location 이국적 객체는 IDL, 생성 후 자바스크립트 내부 메서드의 호출, 및 자바스크립트 내부 메서드의 재정의를 혼합하여 정의됩니다. 무시무시한 보안 정책과 결합되어 있으므로 이를 구현할 때 특히 주의하십시오.

Location 객체를 생성하려면 다음 단계를 수행하십시오:

  1. location을 새 Location 플랫폼 객체로 설정하십시오.

  2. valueOflocation관련 영역.[[Intrinsics]].[[%Object.prototype.valueOf%]]로 설정하십시오.

  3. ! location.[[DefineOwnProperty]]("valueOf", { [[Value]]: valueOf, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })를 수행하십시오.

  4. ! location.[[DefineOwnProperty]](%Symbol.toPrimitive%, { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })를 수행하십시오.

  5. location[[DefaultProperties]] 내부 슬롯의 값을 location.[[OwnPropertyKeys]]()로 설정하십시오.

  6. location을 반환하십시오.

valueOf%Symbol.toPrimitive% 자체 데이터 속성의 추가와 Location의 모든 IDL 속성이 [LegacyUnforgeable]로 표시된다는 사실은 Location 인터페이스를 참조하거나 이를 문자열화하여 문서의 URL을 결정한 다음 이를 보안과 관련된 방식으로 사용하는 레거시 코드에 의해 필요합니다. 특히, valueOf, %Symbol.toPrimitive%, 및 [LegacyUnforgeable] 문자열화 완화는 foo[location] = bar 또는 location + ""과 같은 코드가 잘못 유도되지 않도록 보장합니다.

document.location [ = value ]
window.location [ = value ]

현재 페이지의 위치와 함께 Location 객체를 반환합니다.

다른 페이지로 이동하도록 설정할 수 있습니다.

Document 객체의 location getter 단계는 this완전히 활성화된 경우, 관련 글로벌 객체Location 객체를 반환하고, 그렇지 않으면 null을 반환합니다.

Window 객체의 location getter 단계는 thisLocation 객체를 반환합니다.

Location 객체는 연관된 DocumentURL의 표현을 제공하며, 연관된 내비게이블이동다시 로드하는 방법을 제공합니다.

[Exposed=Window]
interface Location { // 그러나 추가 생성 단계재정의된 내부 메서드도 참조하십시오.
  [LegacyUnforgeable] stringifier attribute USVString href;
  [LegacyUnforgeable] readonly attribute USVString origin;
  [LegacyUnforgeable] attribute USVString protocol;
  [LegacyUnforgeable] attribute USVString host;
  [LegacyUnforgeable] attribute USVString hostname;
  [LegacyUnforgeable] attribute USVString port;
  [LegacyUnforgeable] attribute USVString pathname;
  [LegacyUnforgeable] attribute USVString search;
  [LegacyUnforgeable] attribute USVString hash;

  [LegacyUnforgeable] undefined assign(USVString url);
  [LegacyUnforgeable] undefined replace(USVString url);
  [LegacyUnforgeable] undefined reload();

  [LegacyUnforgeable, SameObject] readonly attribute DOMStringList ancestorOrigins;
};
location.toString()
location.href

Location/href

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

Location/toString

모든 최신 엔진에서 지원됩니다.

Firefox22+ Safari1+ Chrome52+
Opera? Edge79+
Edge (Legacy)12+ Internet Explorer11
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

현재 페이지의 URL을 포함하는 Location 객체를 반환합니다.

지정된 URL로 이동할 수 있습니다.

location.origin

Location/origin

모든 최신 엔진에서 지원됩니다.

Firefox21+ Safari5.1+ Chrome8+
Opera? Edge79+
Edge (Legacy)12+ Internet Explorer11
Firefox Android? Safari iOS? Chrome Android? WebView Android3+ Samsung Internet? Opera Android?

해당 Location 객체의 URL 원본을 반환합니다.

location.protocol

Location/protocol

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 스킴을 반환합니다.

스킴이 변경된 동일한 URL로 이동할 수 있습니다.

location.host

Location/host

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 호스트와 포트를 반환합니다(스킴에 대해 기본 포트가 다를 경우).

호스트와 포트가 변경된 동일한 URL로 이동할 수 있습니다.

location.hostname

Location/hostname

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 호스트를 반환합니다.

호스트가 변경된 동일한 URL로 이동할 수 있습니다.

location.port

Location/port

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 포트를 반환합니다.

포트가 변경된 동일한 URL로 이동할 수 있습니다.

location.pathname

Location/pathname

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 경로를 반환합니다.

경로가 변경된 동일한 URL로 이동할 수 있습니다.

location.search

Location/search

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 쿼리를 반환합니다(비어 있지 않은 경우 선행 "?" 포함).

쿼리가 변경된 동일한 URL로 이동할 수 있습니다(선행 "?"는 무시됨).

location.hash

Location/hash

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera12.1+ Edge79+
Edge (Legacy)12+ Internet Explorer3+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android12.1+

해당 Location 객체의 URL 조각을 반환합니다(비어 있지 않은 경우 선행 "#" 포함).

조각이 변경된 동일한 URL로 이동할 수 있습니다(선행 "#"는 무시됨).

location.assign(url)

Location/assign

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari3+ Chrome1+
Opera3+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS1+ Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

지정된 URL로 이동합니다.

location.replace(url)

Location/replace

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera3+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

세션 기록에서 현재 페이지를 제거하고 지정된 URL로 이동합니다.

location.reload()

Location/reload

모든 최신 엔진에서 지원됩니다.

Firefox1+ Safari1+ Chrome1+
Opera3+ Edge79+
Edge (Legacy)12+ Internet Explorer5.5+
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android10.1+

현재 페이지를 다시 로드합니다.

location.ancestorOrigins

Location/ancestorOrigins

Firefox아니요 Safari6+ Chrome20+
Opera? Edge79+
Edge (Legacy)? Internet Explorer아니요
Firefox Android? Safari iOS? Chrome Android? WebView Android? Samsung Internet? Opera Android?

DOMStringList 객체는 조상 탐색 가능 항목활성 문서의 원본 목록을 반환합니다.

Location 객체는 관련 관련된 Document을 가지고 있으며, 이는 해당 관련 글로벌 객체브라우징 컨텍스트활성 문서이고, 이 Location 객체의 관련 글로벌 객체브라우징 컨텍스트가 null이 아닌 경우이며, 그렇지 않으면 null입니다.

Location 객체는 관련된 url을 가지고 있으며, 이는 해당 Location 객체의 관련된 DocumentURL이고, 이 Location 객체의 관련된 Document가 null이 아닌 경우이며, 그렇지 않으면 about:blank입니다.

Location 객체는 관련된 조상 출처 목록을 가지고 있습니다. Location 객체가 생성될 때, 그 조상 출처 목록은 다음 단계를 통해 생성된 문자열의 목록을 포함하는 DOMStringList 객체로 설정되어야 합니다:

  1. output을 새로운 목록으로 설정합니다.

  2. currentLocation 객체의 관련된 Document로 설정합니다.

  3. current컨테이너 문서가 null이 아닌 동안:

    1. currentcurrent컨테이너 문서로 설정합니다.

    2. 추가 current출처의 직렬화output에 추가합니다.

  4. output을 반환합니다.

Location 객체 탐색으로 Location 객체의 locationURL url로, 선택적으로 NavigationHistoryBehavior을 (기본값 "auto") 지정하여 탐색합니다:

  1. navigablelocation관련된 글로벌 객체탐색 가능 항목으로 설정합니다.

  2. sourceDocument현재 글로벌 객체연결된 Document로 설정합니다.

  3. location관련된 Document가 아직 완전히 로드되지 않았고, 현재 글로벌 객체일시적 활성화를 가지고 있지 않은 경우, historyHandling을 "replace"로 설정합니다.

  4. navigableurlsourceDocument을 사용하여 탐색합니다. 예외 활성화를 true로 설정하고, historyHandling으로 historyHandling을 설정합니다.

href 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. 주어진 값을 엔트리 설정 객체를 기준으로 URL 인코딩-파싱의 결과로 url을 설정합니다.

  3. url이 실패라면, "SyntaxError" DOMException을 throw합니다.

  4. Location-객체 탐색 thisurl로 설정합니다.

href 설정자는 고의적으로 보안 검사를 포함하지 않습니다.

origin getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. ASCII 직렬화를 반환합니다 thisurlorigin.

protocol getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. thisurlscheme을 반환하고, 그 뒤에 ":"을 추가합니다.

protocol 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. possibleFailure을 다음 값으로 기본 URL 파싱의 결과로 설정합니다. copyURLurl로 설정하고 scheme 시작 상태로 설정합니다 state override.

    URL 파서는 여러 개의 연속적인 콜론을 무시하기 때문에, "https:" (또는 "https::::") 값을 제공하는 것은 "https" 값을 제공하는 것과 동일합니다.

  5. possibleFailure이 실패라면, "SyntaxError" DOMException을 throw합니다.

  6. copyURLschemeHTTP(S) scheme이 아니라면, 이 단계를 종료합니다.

  7. Location-객체 탐색thiscopyURL로 설정합니다.

host getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. urlthisurl로 설정합니다.

  3. urlhost가 null이라면, 빈 문자열을 반환합니다.

  4. urlport가 null이라면, urlhost를 반환합니다, 직렬화된 상태로.

  5. urlhost를 반환합니다, 직렬화된 상태로, 그 뒤에 ":"와 urlport를 추가합니다, 직렬화된 상태로.

host 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. copyURLopaque path가 있다면, return합니다.

  5. 기본 URL 파싱을 수행하고, copyURLurl로 설정하며 host 상태state override로 설정합니다.

  6. Location-객체 탐색thiscopyURL로 설정합니다.

hostname getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. thisurlhost가 null이라면, 빈 문자열을 반환합니다.

  3. thisurlhost를 반환합니다, 직렬화된 상태로.

hostname 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. copyURLopaque path가 있다면, return합니다.

  5. 기본 URL 파싱을 수행하고, copyURLurl로 설정하며 hostname 상태state override로 설정합니다.

  6. Location-객체 탐색thiscopyURL로 설정합니다.

port getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. thisurlport가 null이라면, 빈 문자열을 반환합니다.

  3. thisurlport를 반환합니다, 직렬화된 상태로.

port 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. copyURLusername/password/port를 가질 수 없다면, return합니다.

  5. 주어진 값이 빈 문자열인 경우, copyURLport를 null로 설정합니다.

  6. 그렇지 않은 경우, 기본 URL 파싱을 수행하고, copyURLurl로 설정하며 port 상태state override로 설정합니다.

  7. Location-객체 탐색thiscopyURL로 설정합니다.

pathname getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. URL 경로 직렬화의 결과를 반환합니다. 이 Location 객체의 url을 사용합니다.

pathname 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. copyURLopaque path가 있다면, return합니다.

  5. copyURL경로를 빈 목록으로 설정합니다.

  6. 기본 URL 파싱을 수행하고, copyURLurl로 설정하며 경로 시작 상태state override로 설정합니다.

  7. Location-객체 탐색thiscopyURL로 설정합니다.

search getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. thisurlquery가 null이거나 빈 문자열인 경우, 빈 문자열을 반환합니다.

  3. "?"를 반환하고, 그 뒤에 thisurlquery를 반환합니다.

search 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. 주어진 값이 빈 문자열인 경우, copyURLquery를 null로 설정합니다.

  5. 그렇지 않은 경우, 다음 하위 단계를 수행합니다:

    1. 주어진 값에서 선행 "?"을 제거한 값을 input으로 설정합니다(있는 경우).

    2. copyURLquery를 빈 문자열로 설정합니다.

    3. 기본 URL 구문 분석 input, null, 해당 Document문서의 문자 인코딩, copyURLurl로 사용하고, 쿼리 상태상태 오버라이드로 사용하여 수행합니다.

  6. Location-객체 탐색thiscopyURL로 설정합니다.

hash getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null이 아니고, 해당 originsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  2. thisurlfragment가 null이거나 빈 문자열인 경우, 빈 문자열을 반환합니다.

  3. "#"를 반환하고, 그 뒤에 thisurlfragment를 반환합니다.

hash 설정자 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. copyURLthisurl의 복사본으로 설정합니다.

  4. 주어진 값에서 선행 "#"을 제거한 값을 input으로 설정합니다(있는 경우).

  5. copyURLfragment를 빈 문자열로 설정합니다.

  6. 기본 URL 파싱을 수행하고, copyURLurl로 설정하며 fragment 상태상태 재정의로 설정합니다.

  7. copyURLfragmentthisurlfragment와 동일한 경우, return합니다.

    이 중단은 스크롤 시 location.hash를 중복으로 설정하는 배포된 컨텐츠와의 호환성을 위해 필요합니다. 이 중단은 location.href 설정자나 location.assign() 같은 다른 프래그먼트 탐색 메커니즘에는 적용되지 않습니다.

  8. Location-객체 탐색thiscopyURL로 설정합니다.

a 요소 및 area 요소에 대한 동등한 API와 달리, hash 설정자는 배포된 스크립트와의 호환성을 유지하기 위해 빈 문자열을 특별하게 처리하지 않습니다.


assign(url) 메소드 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. urlRecordURL 인코딩 파싱의 결과로 설정하고, urlentry settings object에 상대적으로 설정합니다.

  4. urlRecord가 실패라면, "SyntaxError" DOMException을 throw합니다.

  5. Location-객체 탐색thisurlRecord로 설정합니다.

replace(url) 메소드 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, return합니다.

  2. urlRecordURL 인코딩 파싱의 결과로 설정하고, urlentry settings object에 상대적으로 설정합니다.

  3. urlRecord가 실패라면, "SyntaxError" DOMException을 throw합니다.

  4. Location-객체 탐색thisurlRecord로 설정하고, "replace"로 설정합니다.

replace() 메소드에는 의도적으로 보안 검사가 없습니다.

reload() 메소드 단계는 다음과 같습니다:

  1. documentthis관련된 Document로 설정합니다.

  2. document가 null인 경우, return합니다.

  3. documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  4. 리로드 document노드 탐색 가능를 설정합니다.


ancestorOrigins getter 단계는 다음과 같습니다:

  1. this관련된 Document가 null인 경우, 빈 리스트를 반환합니다.

  2. this관련된 Documentoriginsame origin-domain과 같지 않다면, entry settings objectorigin을 사용하여 "SecurityError" DOMException을 throw합니다.

  3. 그렇지 않으면, thisancestor origins 리스트를 반환합니다.

ancestorOrigins 속성이 작동하는 방식에 대한 세부 사항은 여전히 논란의 여지가 있으며 변경될 수 있습니다. 자세한 내용은 이슈 #1918를 참조하십시오.


앞서 설명한 것처럼, Location 특이 객체에는 보안 목적을 위해 IDL 외에 추가 논리가 필요합니다. Location 객체는 명시적으로 다르게 지정된 경우를 제외하고 일반적인 내부 메서드를 사용해야 합니다.

또한, 모든 Location 객체는 생성 시 자신의 속성을 나타내는 [[DefaultProperties]] 내부 슬롯을 가지고 있습니다.

7.2.4.1 [[GetPrototypeOf]] ( )
  1. 만약 IsPlatformObjectSameOrigin(this)가 true라면, ! OrdinaryGetPrototypeOf(this)를 반환합니다.

  2. null을 반환합니다.

7.2.4.2 [[SetPrototypeOf]] ( V )
  1. ! SetImmutablePrototype(this, V)를 반환합니다.

7.2.4.3 [[IsExtensible]] ( )
  1. true를 반환합니다.

7.2.4.4 [[PreventExtensions]] ( )
  1. false를 반환합니다.

7.2.4.5 [[GetOwnProperty]] ( P )
  1. 만약 IsPlatformObjectSameOrigin(this)가 true라면:

    1. descOrdinaryGetOwnProperty(this, P)로 설정합니다.

    2. 만약 this[[DefaultProperties]] 내부 슬롯의 값에 P가 포함되어 있다면, desc.[[Configurable]]을 true로 설정합니다.

    3. desc를 반환합니다.

  2. propertyCrossOriginGetOwnPropertyHelper(this, P)로 설정합니다.

  3. 만약 property가 undefined가 아니라면, property를 반환합니다.

  4. ? CrossOriginPropertyFallback(P)를 반환합니다.

7.2.4.6 [[DefineOwnProperty]] (P, Desc)
  1. 만약 IsPlatformObjectSameOrigin(this)가 true이면:

    1. this[[DefaultProperties]] 내부 슬롯에 P가 포함되어 있다면, false를 반환합니다.

    2. ? OrdinaryDefineOwnProperty(this, P, Desc)를 반환합니다.

  2. "SecurityError" DOMException을 throw합니다.

7.2.4.7 [[Get]] (P, Receiver)
  1. 만약 IsPlatformObjectSameOrigin(this)가 true이면, ? OrdinaryGet(this, P, Receiver)를 반환합니다.

  2. ? CrossOriginGet(this, P, Receiver)를 반환합니다.

7.2.4.8 [[Set]] (P, V, Receiver)
  1. 만약 IsPlatformObjectSameOrigin(this)가 true이면, ? OrdinarySet(this, P, V, Receiver)를 반환합니다.

  2. ? CrossOriginSet(this, P, V, Receiver)를 반환합니다.

7.2.4.9 [[Delete]] (P)
  1. 만약 IsPlatformObjectSameOrigin(this)가 true이면, ? OrdinaryDelete(this, P)를 반환합니다.

  2. "SecurityError" DOMException을 throw합니다.

7.2.4.10 [[OwnPropertyKeys]] ( )
  1. 만약 IsPlatformObjectSameOrigin(this)가 true이면, OrdinaryOwnPropertyKeys(this)를 반환합니다.

  2. CrossOriginOwnPropertyKeys(this)를 반환합니다.

7.2.5 History 인터페이스

History

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Window/history

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
enum ScrollRestoration { "auto", "manual" };

[Exposed=Window]
interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  undefined go(optional long delta = 0);
  undefined back();
  undefined forward();
  undefined pushState(any data, DOMString unused, optional USVString? url = null);
  undefined replaceState(any data, DOMString unused, optional USVString? url = null);
};
history.length

History/length

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 탐색 가능한 항목의 전체 세션 기록 항목의 수를 반환합니다.

history.scrollRestoration

History/scrollRestoration

모든 현재 엔진에서 지원됩니다.

Firefox46+Safari11+Chrome46+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원 안 됨
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

현재 활성 세션 기록 항목스크롤 복원 모드를 반환합니다.

history.scrollRestoration = value

현재 활성 세션 기록 항목스크롤 복원 모드value로 설정합니다.

history.state

History/state

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari6+Chrome19+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 활성 세션 기록 항목클래식 기록 API 상태를 JavaScript 값으로 직렬화하여 반환합니다.

history.go()

현재 페이지를 다시 로드합니다.

history.go(delta)

History/go

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 탐색 가능한 항목의 전체 세션 기록 항목 목록에서 지정된 단계만큼 앞으로 또는 뒤로 이동합니다.

0의 delta는 현재 페이지를 다시 로드합니다.

delta가 범위를 벗어나면 아무 작업도 수행하지 않습니다.

history.back()

History/back

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 탐색 가능한 항목의 전체 세션 기록 항목 목록에서 한 단계 뒤로 이동합니다.

이전 페이지가 없으면 아무 작업도 수행하지 않습니다.

history.forward()

History/forward

모든 현재 엔진에서 지원됩니다.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

현재 탐색 가능한 항목의 전체 세션 기록 항목 목록에서 한 단계 앞으로 이동합니다.

다음 페이지가 없으면 아무 작업도 수행하지 않습니다.

history.pushState(data, "")

History/pushState

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+

data의 직렬화를 클래식 기록 API 상태에 설정하고 새 항목의 URL에 현재 활성 기록 항목URL을 복사하여 세션 기록에 새 항목을 추가합니다.

(두 번째 매개변수는 역사적인 이유로 존재하며, 생략할 수 없습니다. 빈 문자열을 전달하는 것이 전통입니다.)

history.pushState(data, "", url)

data의 직렬화를 클래식 기록 API 상태에 설정하고 url을 URL에 설정하여 세션 기록에 새 항목을 추가합니다.

현재 문서의 URL을 url로 다시 쓸 수 없으면 "SecurityError" DOMException이 발생합니다.

(두 번째 매개변수는 역사적인 이유로 존재하며, 생략할 수 없습니다. 빈 문자열을 전달하는 것이 전통입니다.)

history.replaceState(data, "")

History/replaceState

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+

현재 활성 세션 기록 항목클래식 기록 API 상태data의 구조적 복제로 업데이트합니다.

(두 번째 매개변수는 역사적인 이유로 존재하며, 생략할 수 없습니다. 빈 문자열을 전달하는 것이 전통입니다.)

history.replaceState(data, "", url)

현재 활성 세션 기록 항목클래식 기록 API 상태data의 구조적 복제로 업데이트하고, URL을 url로 설정합니다.

현재 문서의 URL을 url로 다시 쓸 수 없으면 "SecurityError" DOMException이 발생합니다.

(두 번째 매개변수는 역사적인 이유로 존재하며, 생략할 수 없습니다. 빈 문자열을 전달하는 것이 전통입니다.)

문서히스토리 객체History 객체를 가지고 있습니다.

history getter 단계는 this연결된 문서히스토리 객체를 반환하는 것입니다.


History 객체는 처음에 null로 설정된 상태를 가집니다.

History 객체는 처음에 0으로 설정된 비음수 정수인 길이를 가집니다.

History 객체는 처음에 0으로 설정된 비음수 정수인 인덱스를 가집니다.

비록 인덱스가 직접적으로 노출되지 않지만, 동기 탐색 중 길이의 변화로부터 추론할 수 있습니다. 실제로 그것이 사용되는 목적입니다.

길이 getter 단계는 다음과 같습니다:

  1. 만약 this관련 글로벌 객체연결된 문서완전히 활성화되지 않았다면, "SecurityError" DOMException을 던집니다.

  2. this길이를 반환합니다.

스크롤 복원 getter 단계는 다음과 같습니다:

  1. 만약 this관련 글로벌 객체연결된 문서완전히 활성화되지 않았다면, "SecurityError" DOMException을 던집니다.

  2. this탐색 가능한 노드활성 세션 히스토리 항목스크롤 복원 모드를 반환합니다.

스크롤 복원 setter 단계는 다음과 같습니다:

  1. 만약 this관련 글로벌 객체연결된 문서완전히 활성화되지 않았다면, "SecurityError" DOMException을 던집니다.

  2. this탐색 가능한 노드활성 세션 히스토리 항목스크롤 복원 모드를 주어진 값으로 설정합니다.

상태 getter 단계는 다음과 같습니다:

  1. 만약 this관련 글로벌 객체연결된 문서완전히 활성화되지 않았다면, "SecurityError" DOMException을 던집니다.

  2. this상태를 반환합니다.

go(delta) 메서드 단계는 주어진 delta를 가지고 델타 탐색을 수행하는 것입니다.

back() 메서드 단계는 주어진 −1을 가지고 델타 탐색을 수행하는 것입니다.

forward() 메서드 단계는 주어진 +1을 가지고 델타 탐색을 수행하는 것입니다.

History 객체 history를 주어진 정수 delta델타 탐색하려면:

  1. history관련 글로벌 객체연결된 문서document로 설정합니다.

  2. 만약 document완전히 활성화되지 않았다면, "SecurityError" DOMException을 던집니다.

  3. delta가 0이라면, document탐색 가능한 노드다시 로드하고 반환합니다.

  4. document탐색 가능한 노드탐색 가능한 항목, delta를 주어진 상태로 설정하고 소스 문서document로 설정하여 히스토리를 델타로 탐색합니다.

pushState(data, unused, url) 메서드 단계는 공유 히스토리 push/replace 상태 단계this, data, url 및 "push"를 주어진 상태로 실행합니다.

replaceState(data, unused, url) 메서드 단계는 공유 히스토리 push/replace 상태 단계this, data, url 및 "replace"를 주어진 상태로 실행합니다.

공유 히스토리 push/replace 상태 단계History history, 값 data, 스칼라 값 문자열-또는-null url, 및 히스토리 처리 동작 historyHandling을 주어진 상태로 실행합니다.

  1. history의 연결된 문서document로 설정합니다.

  2. 만약 document완전히 활성화되지 않았다면, "SecurityError" DOMException을 던집니다.

  3. 선택적으로 반환합니다. (예를 들어, 사용자 에이전트는 타이머에서 호출된 메서드, 명확한 사용자 작업에 응답하여 트리거되지 않은 이벤트 리스너에서 호출된 메서드 또는 빠르게 연속적으로 호출된 메서드를 허용하지 않을 수 있습니다.)

  4. serializedData저장용 구조화 직렬화(data)로 설정합니다. 예외가 발생하면 다시 던집니다.

  5. newURLdocumentURL로 설정합니다.

  6. 만약 url이 null 또는 빈 문자열이 아니라면:

    1. newURLURL 인코딩-파싱 결과로 설정합니다. urlhistory관련 설정 객체를 기준으로 합니다.

    2. 만약 newURL이 실패라면, "SecurityError" DOMException을 던집니다.

    3. 만약 documentnewURLURL이 다시 작성될 수 없다면, "SecurityError" DOMException을 던집니다.

    여기서 빈 문자열에 대한 특별한 경우는 역사적이며, location.href = "" (빈 문자열에 대해 URL 파싱을 수행)와 history.pushState(null, "", "") (이를 우회)을 비교할 때 다른 결과 URL을 생성하게 됩니다.

  7. history관련 글로벌 객체탐색 APInavigation으로 설정합니다.

  8. 푸시/대체/다시 로드 내비게이트 이벤트navigation에서 발생시키고, 탐색 유형historyHandling으로 설정하고, isSameDocument를 true로 설정하며, 목적지 URLnewURL로 설정하고, classicHistoryAPIStateserializedData로 설정합니다.

  9. 만약 continue가 false라면, 반환합니다.

  10. URL 및 히스토리 업데이트 단계documentnewURL에 대해 실행하고, serializedDataserializedData로 설정하며, historyHandlinghistoryHandling으로 설정합니다.

사용자 에이전트는 페이지당 세션 기록에 추가된 상태 객체의 수를 제한할 수 있습니다. 만약 페이지가 구현 정의 제한에 도달하면, 사용자 에이전트는 새 항목을 추가한 후 세션 기록에서 해당 문서 객체의 첫 번째 항목 직후에 항목을 제거해야 합니다. (따라서 상태 기록은 퇴거를 위한 FIFO 버퍼로 작동하지만 탐색을 위한 LIFO 버퍼로 작동합니다.)

문서 document는 다음 알고리즘이 true를 반환하는 경우에만 URL을 다시 작성할 수 있습니다:

  1. documentURLdocumentURL로 설정합니다.

  2. 만약 targetURLdocumentURL스킴, 사용자 이름, 비밀번호, 호스트, 또는 포트 구성 요소에서 다르다면, false를 반환합니다.

  3. 만약 targetURL스킴HTTP(S) 스킴이라면 true를 반환합니다.

    경로, 쿼리, 및 프래그먼트에서의 차이점은 http:https: URL에 허용됩니다.

  4. 만약 targetURL스킴이 "file"이라면:

    1. 만약 targetURLdocumentURL경로 구성 요소에서 다르다면 false를 반환합니다.

    2. true를 반환합니다.

    쿼리프래그먼트에서의 차이점은 file: URL에서 허용됩니다.

  5. 만약 targetURLdocumentURL경로 구성 요소 또는 쿼리 구성 요소에서 다르다면 false를 반환합니다.

    다른 유형의 URL에서는 프래그먼트에서의 차이점만 허용됩니다.

  6. true를 반환합니다.

documentURL targetURL URL을 다시 작성할 수 있음
https://example.com/home https://example.com/home#about
https://example.com/home https://example.com/home?page=shop
https://example.com/home https://example.com/shop
https://example.com/home https://user:pass@example.com/home
https://example.com/home http://example.com/home
file:///path/to/x file:///path/to/x#hash
file:///path/to/x file:///path/to/x?search
file:///path/to/x file:///path/to/y
about:blank about:blank#hash
about:blank about:blank?search
about:blank about:srcdoc
data:text/html,foo data:text/html,foo#hash
data:text/html,foo data:text/html,foo?search
data:text/html,foo data:text/html,bar
data:text/html,foo data:bar
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43#hash
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43?search
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/anything
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:path

오직 문서URL만 중요한 것이지, 출처는 중요하지 않다는 점에 주목하십시오. about:blank 문서가 상속된 출처를 가지는 경우, 샌드박스된 iframe 또는 document.domain 세터가 사용된 경우에는 출처가 일치하지 않을 수 있습니다.

사용자가 항상 특정 좌표에 있으며, 특정 좌표에 해당하는 페이지를 북마크하여 나중에 다시 방문할 수 있는 게임을 고려해 보십시오.

이 게임에서 x=5 위치를 구현한 정적 페이지는 다음과 같을 수 있습니다:

<!DOCTYPE HTML>
<!-- 여기는 https://example.com/line?x=5 -->
<html lang="en">
<title>라인 게임 - 5</title>
<p>당신은 라인의 5번 좌표에 있습니다.</p>
<p>
 <a href="?x=6">6번 좌표로 이동</a> 또는
 <a href="?x=4">4번 좌표로 후퇴</a>?
</p>

이러한 시스템의 문제점은 사용자가 클릭할 때마다 전체 페이지가 다시 로드되어야 한다는 것입니다. 여기 스크립트를 사용하여 동일한 작업을 수행하는 또 다른 방법이 있습니다:

<!DOCTYPE HTML>
<!-- 여기서 시작: https://example.com/line?x=5 -->
<html lang="en">
<title>라인 게임 - 5</title>
<p>당신은 라인의 <span id="coord">5</span> 번 좌표에 있습니다.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">6번 좌표로 이동</a> 또는
 <a href="?x=4" onclick="go(-1); return false;">4번 좌표로 후퇴</a>?
</p>
<script>
 var currentPage = 5; // 서버에서 채워진 값
 function go(d) {
   setupPage(currentPage + d);
   history.pushState(currentPage, "", '?x=' + currentPage);
 }
 onpopstate = function(event) {
   setupPage(event.state);
 }
 function setupPage(page) {
   currentPage = page;
   document.title = '라인 게임 - ' + currentPage;
   document.getElementById('coord').textContent = currentPage;
   document.links[0].href = '?x=' + (currentPage+1);
   document.links[0].textContent = '6번 좌표로 이동' + (currentPage+1);
   document.links[1].href = '?x=' + (currentPage-1);
   document.links[1].textContent = '4번 좌표로 후퇴' + (currentPage-1);
 }
</script>

스크립트가 없는 시스템에서도 이 예시는 이전 예제와 동일하게 작동합니다. 하지만 스크립트를 지원하는 사용자는 네트워크 접근 없이 더 빠르게 탐색할 수 있습니다. 또한 단순한 스크립트 기반 접근만으로는 사용할 수 없는 북마크 및 세션 기록 탐색 기능이 여전히 작동합니다.

위 예시에서 pushState() 메소드의 data 인자는 서버로 전송될 정보와 동일하지만, 사용하기 더 편리한 형태로 되어 있어 사용자가 탐색할 때마다 스크립트가 URL을 분석할 필요가 없습니다.

대부분의 애플리케이션은 모든 기록 항목에 대해 동일한 스크롤 복원 모드 값을 사용하기를 원합니다. 이를 위해 scrollRestoration 속성을 가능한 빨리 설정할 수 있습니다 (예: 문서의 head 요소에 있는 첫 번째 스크립트 요소에서) 세션 기록에 추가되는 모든 항목이 원하는 스크롤 복원 모드를 가지도록 보장할 수 있습니다.

<head>
  <script>
       if ('scrollRestoration' in history)
            history.scrollRestoration = 'manual';
  </script>
</head>

이 섹션은 비규범적입니다.

네비게이션 API는 글로벌 navigation 속성을 통해 제공되며, 네비게이션 및 기록 항목을 관리하는 웹 애플리케이션 중심의 현대적인 방법을 제공합니다. 이는 고전적인 locationhistory API의 후속입니다.

이 API가 제공하는 기능 중 하나는 세션 기록 항목을 검사하는 것입니다. 예를 들어, 다음 코드는 항목의 URL을 정렬된 목록으로 표시합니다:

const ol = document.createElement("ol");
ol.start = 0; // 목록 항목의 순번이 항목 인덱스와 일치하도록 설정

for (const entry of navigation.entries()) {
  const li = document.createElement("li");

  if (entry.index < navigation.currentEntry.index) {
    li.className = "backward";
  } else if (entry.index > navigation.currentEntry.index) {
    li.className = "forward";
  } else {
    li.className = "current";
  }

  li.textContent = entry.url;
  ol.append(li);
}

navigation.entries() 배열은 NavigationHistoryEntry 인스턴스를 포함하며, 여기에 표시된 urlindex 속성 외에도 유용한 다른 속성들이 있습니다. 이 배열은 현재 navigable을 나타내는 NavigationHistoryEntry 객체만 포함하므로, iframe과 같은 navigable container 내부에서 이루어진 네비게이션이나 parent navigable의 네비게이션이 배열의 내용에 영향을 주지 않습니다. 또한, 동일한 출처를 가지는 세션 기록 항목을 나타내는 NavigationHistoryEntry 객체만 포함하므로, 현재 출처 전후에 다른 출처를 방문한 경우 해당하는 NavigationHistoryEntry가 존재하지 않을 것입니다.


네비게이션 API는 또한 네비게이션, 리로드, 또는 기록을 통해 이동하는 데 사용할 수 있습니다:

<button onclick="navigation.reload()">리로드</button>

<input type="url" id="navigationURL">
<button onclick="navigation.navigate(navigationURL.value)">네비게이트</button>

<button id="backButton" onclick="navigation.back()">뒤로가기</button>
<button id="forwardButton" onclick="navigation.forward()">앞으로가기</button>

<select id="traversalDestinations"></select>
<button id="goButton" onclick="navigation.traverseTo(traversalDestinations.value)">이동하기</button>

<script>
backButton.disabled = !navigation.canGoBack;
forwardButton.disabled = !navigation.canGoForward;

for (const entry of navigation.entries()) {
  traversalDestinations.append(new Option(entry.url, entry.key));
}
</script>

네비게이션은 동일한 출처로 제한된다는 점에 유의하세요. 예를 들어, navigation.canGoBack은 이전 세션 기록 항목이 다른 출처에 속하는 경우 false를 반환합니다.


네비게이션 API의 가장 강력한 기능은 navigate 이벤트로, 현재 navigable에서 거의 모든 네비게이션이나 이동이 발생할 때마다 발생합니다:

navigation.onnavigate = event => {
  console.log(event.navigationType); // "push", "replace", "reload", 또는 "traverse"
  console.log(event.destination.url);
  console.log(event.userInitiated);
  // ... 및 다른 유용한 속성들
};

(이 이벤트는 주소 표시줄에서 시작된 네비게이션이나, 네비게이션의 목적지가 새로운 문서인 경우 다른 창에서 시작된 네비게이션에서는 발생하지 않습니다.)

많은 경우 이 이벤트의 취소 가능 속성은 true이며, 이는 preventDefault()를 사용하여 이 이벤트를 취소할 수 있음을 의미합니다:

navigation.onnavigate = event => {
  if (event.cancelable && isDisallowedURL(event.destination.url)) {
    alert(`이 URL로 이동하지 마세요: ${event.destination.url}!`);
    event.preventDefault();
  }
};

취소 가능 속성은 traverse 네비게이션의 경우, 예를 들어 하위 navigable 내에서 발생하는 경우, 새로운 출처로 이동하는 경우, 또는 사용자가 이전 preventDefault() 호출 후 곧바로 다시 이동하려는 경우 false가 됩니다.

NavigateEventintercept() 메소드를 사용하면 네비게이션을 가로채어 동일 문서 네비게이션으로 변환할 수 있습니다:

navigation.addEventListener("navigate", e => {
  // 일부 네비게이션, 예를 들어 교차 출처 네비게이션은 가로챌 수 없습니다.
  // 브라우저가 이를 정상적으로 처리하도록 합니다.
  if (!e.canIntercept) {
    return;
  }

  // 유사하게, 해시 변경이나 다운로드도 가로채지 않습니다.
  if (e.hashChange || e.downloadRequest !== null) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    e.intercept({
      async handler() {
        // URL이 이미 변경되었으므로 새로운 콘텐츠를 가져오는 동안
        // 자리 표시자를 표시합니다, 예를 들어 로딩 스피너나 로딩 페이지.
        renderArticlePagePlaceholder();

        // 새 콘텐츠를 가져와서 준비되면 표시합니다.
        const articleContent = await getArticleContent(url.pathname, { signal: e.signal });
        renderArticlePage(articleContent);
      }
    });
  }
});

handler 함수는 네비게이션의 비동기 진행 상황, 성공 또는 실패를 나타내는 프라미스를 반환할 수 있다는 점에 유의하세요. 프라미스가 아직 대기 중인 동안, 브라우저 UI는 네비게이션이 진행 중인 것으로 처리할 수 있습니다 (예: 로딩 스피너를 표시함으로써). 네비게이션 API의 다른 부분도 이러한 프라미스에 민감하며, navigation.navigate()의 반환 값도 이에 영향을 받습니다:

const { committed, finished } = await navigation.navigate("/articles/the-navigation-api-is-cool");

// 커밋된 프라미스는 URL이 변경된 즉시 완료됩니다 (NavigateEvent가 취소되지 않는 한).
await committed;

// 완료된 프라미스는 handler() 함수가 완료된 후에 완료되며, 이는 기사가 다운로드되고 렌더링된 후에 발생합니다. (또는 handler() 함수가 실패할 경우 거부됩니다).
await finished;
[Exposed=Window]
interface Navigation : EventTarget {
  sequence<NavigationHistoryEntry> entries();
  readonly attribute NavigationHistoryEntry? currentEntry;
  undefined updateCurrentEntry(NavigationUpdateCurrentEntryOptions options);
  readonly attribute NavigationTransition? transition;
  readonly attribute NavigationActivation? activation;

  readonly attribute boolean canGoBack;
  readonly attribute boolean canGoForward;

  NavigationResult navigate(USVString url, optional NavigationNavigateOptions options = {});
  NavigationResult reload(optional NavigationReloadOptions options = {});

  NavigationResult traverseTo(DOMString key, optional NavigationOptions options = {});
  NavigationResult back(optional NavigationOptions options = {});
  NavigationResult forward(optional NavigationOptions options = {});

  attribute EventHandler onnavigate;
  attribute EventHandler onnavigatesuccess;
  attribute EventHandler onnavigateerror;
  attribute EventHandler oncurrententrychange;
};

dictionary NavigationUpdateCurrentEntryOptions {
  required any state;
};

dictionary NavigationOptions {
  any info;
};

dictionary NavigationNavigateOptions : NavigationOptions {
  any state;
  NavigationHistoryBehavior history = "auto";
};

dictionary NavigationReloadOptions : NavigationOptions {
  any state;
};

dictionary NavigationResult {
  Promise<NavigationHistoryEntry> committed;
  Promise<NavigationHistoryEntry> finished;
};

enum NavigationHistoryBehavior {
  "auto",
  "push",
  "replace"
};

Window는 연결된 navigation API를 가지고 있으며, 이는 Navigation 객체입니다. Window 객체가 생성될 때, 그 객체의 navigation APInew Navigation 객체로 설정되어야 하며, 이는 Window 객체의 relevant realm에서 생성된 것입니다.

navigation getter 단계는 thisnavigation API를 반환하는 것입니다.

다음은 모든 Navigation 인터페이스를 구현하는 객체에서 지원해야 하는 이벤트 핸들러와 그에 상응하는 이벤트 핸들러 이벤트 유형입니다. 이들은 이벤트 핸들러 IDL 속성으로 지원됩니다:

이벤트 핸들러 이벤트 핸들러 이벤트 유형
onnavigate navigate
onnavigatesuccess navigatesuccess
onnavigateerror navigateerror
oncurrententrychange currententrychange

Navigation는 연결된 entry list를 가지고 있으며, 이는 리스트입니다. 이 리스트는 NavigationHistoryEntry 객체들로 구성되며, 초기에는 비어 있습니다.

Navigation는 연결된 current entry index를 가지고 있으며, 이는 초기에는 −1로 설정된 정수입니다.

Navigationnavigationcurrent entry는 다음 단계들을 수행하여 얻은 결과입니다:

  1. 만약 navigationentries and events disabled을 가지고 있다면, null을 반환합니다.

  2. 단언: navigationcurrent entry index가 −1이 아님을 확인합니다.

  3. navigationentry list에서 navigationcurrent entry index에 해당하는 항목을 반환합니다.

Navigationnavigationentries and events disabled 상태인지 확인하려면 다음 단계들을 수행합니다:

  1. navigationrelevant global object관련 Documentdocument로 설정합니다.

  2. 만약 documentfully active 상태가 아니라면, true를 반환합니다.

  3. 만약 document초기 about:blank가 true라면, true를 반환합니다.

  4. 만약 documentorigin불투명(opaque) 상태라면, true를 반환합니다.

  5. false를 반환합니다.

navigation API entry indexsession history entry she 내에서 얻으려면 다음 단계를 수행합니다:

  1. index를 0으로 설정합니다.

  2. 각각의 nhe에 대해 navigationentry list를 순회합니다:

    1. 만약 nhesession history entryshe와 동일하다면, index를 반환합니다.

    2. index를 1 증가시킵니다.

  3. −1을 반환합니다.


navigation API에서 자주 사용되는 주요 유형은 NavigationType 열거형입니다:

enum NavigationType {
 "push",
 "replace",
 "reload",
 "traverse"
};

이 열거형은 웹 개발자가 주로 볼 수 있는 "navigation" 유형들을 캡처하며, 이는 이 표준의 navigate 알고리즘과 정확히 일치하지 않습니다. 각 값의 의미는 다음과 같습니다:

"push"
navigate 호출에 해당하며, 이때 history handling behavior가 "push"로 설정됩니다. 또는 history.pushState() 호출에 해당합니다.
"replace"
navigate 호출에 해당하며, 이때 history handling behavior가 "replace"로 설정됩니다. 또는 history.replaceState() 호출에 해당합니다.
"reload"
reload 호출에 해당합니다.
"traverse"
traverse the history by a delta 호출에 해당합니다.

NavigationType 열거형의 값 공간은 사양 내부의 history handling behavior 유형의 값 공간을 포함합니다. 이 표준의 여러 부분에서 이 겹침을 활용하여, history handling behaviorNavigationType을 기대하는 알고리즘에 전달합니다.

7.2.6.4 엔트리 목록 초기화 및 업데이트

새 문서를 위한 navigation API 엔트리를 초기화하기 위해, Navigation navigation, 엔트리 목록 newSHEs, 및 세션 기록 엔트리 initialSHE가 주어졌을 때, 다음 단계를 수행합니다:

  1. 확인: navigation엔트리 목록비어있는지 확인합니다.

  2. 확인: navigation현재 엔트리 인덱스가 -1인지 확인합니다.

  3. 만약 navigation엔트리와 이벤트가 비활성화되어 있다면, 반환합니다.

  4. 각각의 newSHE에 대해 newSHEs를 반복합니다:

    1. newNHE새로운 NavigationHistoryEntry로 설정합니다. 이 객체는 navigation관련된 영역에서 생성됩니다.

    2. newNHE세션 기록 엔트리newSHE로 설정합니다.

    3. 추가: newNHEnavigation엔트리 목록에 추가합니다.

    newSHEs는 원래 navigation API를 위한 세션 기록 엔트리 가져오기에서 나온 것입니다. 따라서 각 newSHEinitialSHE동일한 출처입니다.

  5. navigation현재 엔트리 인덱스initialSHEnavigation API 엔트리 인덱스 가져오기의 결과로 설정합니다.

navigation API 엔트리를 재활성화를 위해 업데이트하려면, Navigation navigation, 엔트리 목록 newSHEs, 및 세션 기록 엔트리 reactivatedSHE가 주어졌을 때 다음 단계를 수행합니다:

  1. 만약 navigation엔트리와 이벤트가 비활성화되어 있다면, 반환합니다.

  2. newNHEs를 새로운 빈 목록으로 설정합니다.

  3. oldNHEsnavigation엔트리 목록복제본으로 설정합니다.

  4. 각각의 newSHE에 대해 newSHEs를 반복합니다:

    1. newNHE를 null로 설정합니다.

    2. 만약 oldNHEsnewSHE포함하는 NavigationHistoryEntry matchingOldNHE를 포함하고 있다면:

      1. newNHEmatchingOldNHE로 설정합니다.

      2. 삭제: matchingOldNHEoldNHEs에서 삭제합니다.

    3. 그렇지 않으면:

      1. newNHE새로운 NavigationHistoryEntry로 설정합니다. 이 객체는 navigation관련된 영역에서 생성됩니다.

      2. newNHE세션 기록 엔트리newSHE로 설정합니다.

    4. 추가: newNHEnewNHEs에 추가합니다.

    newSHEs는 원래 navigation API를 위한 세션 기록 엔트리 가져오기에서 나온 것입니다. 따라서 각 newSHEreactivatedSHE동일한 출처입니다.

    이 반복이 끝나면, oldNHEs에 남아있는 모든 NavigationHistoryEntry문서bfcache에 있을 때 폐기된 세션 기록 엔트리를 나타냅니다.

  5. navigation엔트리 목록newNHEs로 설정합니다.

  6. navigation현재 엔트리 인덱스reactivatedSHEnavigation API 엔트리 인덱스 가져오기의 결과로 설정합니다.

  7. 글로벌 태스크를 대기열에 추가: navigation관련된 글로벌 객체에서 navigationnavigation 및 탐색 태스크 소스에 다음 단계를 실행합니다:

    1. 각각의 disposedNHE에 대해 oldNHEs를 반복합니다:

      1. 이벤트 발생: disposedNHE에서 dispose 이벤트를 발생시킵니다.

    이 단계를 태스크로 지연시키는 이유는 dispose 이벤트가 pageshow 이벤트 후에 발생하도록 보장하기 위해서입니다. 이렇게 하면 재활성화될 때 페이지가 처음으로 받는 이벤트가 pageshow 이벤트가 됩니다.

    (하지만 이 알고리즘의 나머지 부분은 pageshow 이벤트가 발생하기 전에 실행됩니다. 이렇게 하면 navigation.entries()navigation.currentEntry의 값이 pageshow 이벤트 핸들러 동안 올바르게 업데이트됩니다.)

동일 문서 탐색을 위한 navigation API 엔트리 업데이트하려면, Navigation navigation, 세션 기록 엔트리 destinationSHE, 및 NavigationType navigationType이 주어졌을 때 다음 단계를 수행합니다:

  1. 만약 navigation엔트리와 이벤트가 비활성화되어 있다면, 반환합니다.

  2. oldCurrentNHEnavigation현재 엔트리로 설정합니다.

  3. disposedNHEs를 새로운 빈 목록으로 설정합니다.

  4. 만약 navigationType이 "탐색"이라면:

    1. navigation현재 엔트리 인덱스destinationSHEnavigation API 엔트리 인덱스 가져오기의 결과로 설정합니다.

    2. 확인: navigation현재 엔트리 인덱스가 -1이 아님을 확인합니다.

    이 알고리즘은 동일 문서 탐색에만 호출됩니다. 교차 문서 탐색은 새 문서를 위한 navigation API 엔트리 초기화 또는 navigation API 엔트리를 재활성화를 위해 업데이트를 호출합니다.

  5. 그렇지 않고, navigationType이 "push"이라면:

    1. navigation현재 엔트리 인덱스navigation현재 엔트리 인덱스 + 1로 설정합니다.

    2. inavigation현재 엔트리 인덱스로 설정합니다.

    3. 반복: inavigation엔트리 목록크기보다 작은 동안:

      1. 추가: navigation엔트리 목록[i]을 disposedNHEs에 추가합니다.

      2. ii + 1로 설정합니다.

    4. 삭제: disposedNHEs에 있는 모든 항목을 navigation엔트리 목록에서 삭제합니다.

  6. 그렇지 않고, navigationType이 "replace"라면:

    1. 추가: oldCurrentNHEdisposedNHEs에 추가합니다.

  7. 만약 navigationType이 "push" 또는 "replace"이라면:

    1. newNHE새로운 NavigationHistoryEntry로 설정합니다. 이 객체는 navigation관련된 영역에서 생성됩니다.

    2. newNHE세션 기록 엔트리destinationSHE로 설정합니다.

    3. navigation엔트리 목록[navigation현재 엔트리 인덱스]을 newNHE로 설정합니다.

  8. 만약 navigation진행 중인 API 메서드 추적기가 null이 아니라면, navigation진행 중인 API 메서드 추적기navigation현재 엔트리에 대해 커밋된 엔트리에 대해 알림을 수행합니다.

    이 작업은 dispose 또는 currententrychange 이벤트를 발생시키기 전에 수행하는 것이 중요합니다. 이벤트 핸들러는 또 다른 탐색을 시작하거나 navigation진행 중인 API 메서드 추적기 값을 변경할 수 있습니다.

  9. 스크립트 실행 준비navigation관련된 설정 객체에 대해 수행합니다.

    다른 navigation API 이벤트에 대한 논의를 이해하려면 탐색 이벤트 동안 마이크로태스크 억제에 대한 논의를 참조하십시오.

  10. 이벤트 발생: navigation에서 currententrychange 이벤트를 NavigationCurrentEntryChangeEvent을 사용하여 발생시킵니다. 이 이벤트의 navigationType 속성은 navigationType으로 초기화되며, from 속성은 oldCurrentNHE로 초기화됩니다.

  11. 각각의 disposedNHE에 대해 disposedNHEs를 반복합니다:

    1. 이벤트 발생: disposedNHE에서 dispose 이벤트를 발생시킵니다.

  12. 스크립트 실행 후 정리navigation관련된 설정 객체에 대해 수행합니다.

구현에서는 동일 문서 탐색이 세션 기록 엔트리 목록에서 떨어져 나가면서 세션 기록 엔트리를 폐기할 수 있습니다. 이 경우의 정확한 동작은 아직 위 알고리즘(또는 이 표준의 다른 부분)에서 다루지 않고 있습니다. 이와 관련한 정의 진행 상황은 issue #8620에서 확인할 수 있습니다.

7.2.6.5 NavigationHistoryEntry 인터페이스
[Exposed=Window]
interface NavigationHistoryEntry : EventTarget {
  readonly attribute USVString? url;
  readonly attribute DOMString key;
  readonly attribute DOMString id;
  readonly attribute long long index;
  readonly attribute boolean sameDocument;

  any getState();

  attribute EventHandler ondispose;
};
entry.url

이 탐색 기록 항목의 URL입니다.

이 항목이 현재 문서와 다른 문서에 해당하는 경우(null을 반환할 수 있음), 즉 sameDocument가 false이고 해당 문서가 "no-referrer" 또는 "origin" 리퍼러 정책으로 가져온 경우, 해당 문서는 동일 출처 페이지에서도 URL을 숨기고 있다는 의미입니다.

entry.key

이 탐색 기록 항목의 위치를 나타내는 사용자 에이전트에서 생성된 랜덤 UUID 문자열입니다. 이 값은 "replace" 탐색으로 인해 이 항목을 교체하는 다른 NavigationHistoryEntry 인스턴스에 의해 재사용되며, 페이지 새로고침 및 세션 복구 시에도 유지됩니다.

이 값은 navigation.traverseTo(key)를 사용하여 탐색 기록 목록에서 이 항목으로 다시 이동하는 데 유용합니다.

entry.id

이 특정 탐색 기록 항목을 나타내는 사용자 에이전트에서 생성된 랜덤 UUID 문자열입니다. 이 값은 다른 NavigationHistoryEntry 인스턴스에 의해 재사용되지 않습니다. 이 값은 페이지 새로고침 및 세션 복구 시에도 유지됩니다.

이 값은 다른 저장소 API를 사용하여 이 탐색 기록 항목에 데이터를 연결하는 데 유용합니다.

entry.index

NavigationHistoryEntry의 탐색 기록 목록 내 인덱스입니다. 탐색 기록 목록에 항목이 없으면 −1을 반환합니다.

entry.sameDocument

이 탐색 기록 항목이 현재 문서와 동일한 문서에 해당하는지 여부를 나타냅니다. 예를 들어, 이 항목이 프래그먼트 탐색 또는 단일 페이지 애플리케이션 탐색을 나타내는 경우 true입니다.

entry.getState()

이 항목에 저장된 상태의 역직렬화를 반환합니다. 이 상태는 navigation.navigate() 또는 navigation.updateCurrentEntry()를 사용하여 항목에 추가되었습니다. 이 상태는 페이지 새로고침 및 세션 복구 시에도 유지됩니다.

일반적으로 상태 값이 원시 값이 아닌 경우 entry.getState() !== entry.getState()입니다. 매번 새롭게 역직렬화된 값이 반환되기 때문입니다.

이 상태는 클래식 히스토리 API의 history.state와는 관련이 없습니다.

NavigationHistoryEntry세션 히스토리 항목과 연결되어 있으며, 이는 세션 히스토리 항목입니다.

NavigationHistoryEntry nhe는 다음 알고리즘의 반환 값으로 결정됩니다:

  1. nhe관련 글로벌 객체연결된 문서완전히 활성화되지 않은 경우 빈 문자열을 반환합니다.

  2. nhe세션 히스토리 항목탐색 API 키를 반환합니다.

NavigationHistoryEntry nheID는 다음 알고리즘의 반환 값으로 결정됩니다:

  1. nhe관련 글로벌 객체연결된 문서완전히 활성화되지 않은 경우 빈 문자열을 반환합니다.

  2. nhe세션 히스토리 항목탐색 API ID를 반환합니다.

NavigationHistoryEntry nhe인덱스는 다음 알고리즘의 반환 값으로 결정됩니다:

  1. nhe관련 글로벌 객체연결된 문서완전히 활성화되지 않은 경우 −1을 반환합니다.

  2. nhe세션 히스토리 항목의 탐색 API 항목 인덱스를 가져오는 결과를 반환합니다.

url 접근자 단계는 다음과 같습니다:

  1. documentthis관련 글로벌 객체연결된 문서로 설정합니다.

  2. document완전히 활성화되지 않은 경우 빈 문자열을 반환합니다.

  3. shethis세션 히스토리 항목으로 설정합니다.

  4. she문서document와 같지 않으며, she문서 상태요청 리퍼러 정책이 "no-referrer" 또는 "origin"인 경우 null을 반환합니다.

  5. sheURL직렬화하여 반환합니다.

key 접근자 단계는 다음과 같습니다:

this를 반환합니다.

id 접근자 단계는 다음과 같습니다:

thisID를 반환합니다.

index 접근자 단계는 다음과 같습니다:

this인덱스를 반환합니다.

sameDocument 접근자 단계는 다음과 같습니다:

  1. documentthis관련 글로벌 객체연결된 문서로 설정합니다.

  2. document완전히 활성화되지 않은 경우 false를 반환합니다.

  3. this세션 히스토리 항목문서document와 동일한 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.

getState() 메서드 단계는 다음과 같습니다:

  1. this관련 글로벌 객체연결된 문서완전히 활성화되지 않은 경우 undefined를 반환합니다.

  2. StructuredDeserialize(this세션 히스토리 항목탐색 API 상태)를 반환하고, 모든 예외를 다시 던집니다.

    이론적으로 큰 ArrayBuffer를 역직렬화하려고 할 때 메모리가 부족한 경우 예외가 발생할 수 있습니다.

이벤트 핸들러 (및 해당 이벤트 핸들러 이벤트 타입)는 이벤트 핸들러 IDL 속성으로서 NavigationHistoryEntry 인터페이스를 구현하는 모든 객체에서 지원되어야 합니다:

이벤트 핸들러 이벤트 핸들러 이벤트 타입
ondispose dispose
7.2.6.6 히스토리 엔트리 목록
entries = navigation.entries()

현재 내비게이션 히스토리 엔트리 목록을 나타내는 NavigationHistoryEntry 인스턴스 배열을 반환합니다. 즉, 이 navigable에 대한 모든 세션 히스토리 엔트리가 현재 세션 히스토리 엔트리와 동일한 출처이고 연속적으로 나열됩니다.

navigation.currentEntry

현재 세션 히스토리 엔트리에 해당하는 NavigationHistoryEntry를 반환합니다.

navigation.updateCurrentEntry({ state })

현재 세션 히스토리 엔트리내비게이션 API 상태를 업데이트합니다. navigation.reload()와 같은 탐색 작업을 수행하지 않고도 이 작업을 실행할 수 있습니다.

이 메서드는 이미 발생한 페이지 업데이트를 캡처하고 내비게이션 API 상태에 반영해야 할 때 가장 적합합니다. 상태 업데이트가 페이지 업데이트를 유도하려는 경우에는 대신 navigation.navigate() 또는 navigation.reload()을 사용하십시오. 이는 navigate 이벤트를 트리거합니다.

navigation.canGoBack

현재 세션 히스토리 엔트리 (즉, currentEntry)가 내비게이션 히스토리 엔트리 목록의 첫 번째가 아닌 경우 true를 반환합니다 (즉, entries()에 있음). 이는 현재 문서출처와 동일한 출처인 이전 세션 히스토리 엔트리가 존재함을 의미합니다.

navigation.canGoForward

현재 세션 히스토리 엔트리 (즉, currentEntry)가 내비게이션 히스토리 엔트리 목록의 마지막이 아닌 경우 true를 반환합니다 (즉, entries()에 있음). 이는 현재 문서출처와 동일한 출처인 다음 세션 히스토리 엔트리가 존재함을 의미합니다.

메서드 entries()의 단계는 다음과 같습니다:

  1. this엔트리와 이벤트가 비활성화된 경우, 빈 목록을 반환합니다.

  2. this엔트리 목록을 반환합니다.

    Web IDL의 시퀀스 타입 변환 규칙 때문에, 이는 각 호출 시 새로운 JavaScript 배열 객체를 생성합니다. 즉, navigation.entries() !== navigation.entries()입니다.

currentEntry 속성의 단계는 현재 엔트리this에서 반환하는 것입니다.

updateCurrentEntry(options) 메서드의 단계는 다음과 같습니다:

  1. current현재 엔트리로 설정합니다 this의.

  2. current가 null인 경우, "InvalidStateError" DOMException을 발생시킵니다.

  3. serializedStateStructuredSerializeForStorage(options["state"])로 설정하고, 모든 예외를 다시 던집니다.

  4. current세션 히스토리 엔트리내비게이션 API 상태serializedState로 설정합니다.

  5. 이벤트this에서 currententrychange라는 이름으로 NavigationCurrentEntryChangeEvent를 사용하여 발생시키며, 그 navigationType 속성을 null로 초기화하고, 그 from 속성을 current로 초기화합니다.

canGoBack 속성의 단계는 다음과 같습니다:

  1. this엔트리와 이벤트가 비활성화된 경우, false를 반환합니다.

  2. 단언: this현재 엔트리 인덱스가 −1이 아님을 확인합니다.

  3. this현재 엔트리 인덱스가 0인 경우, false를 반환합니다.

  4. true를 반환합니다.

canGoForward 속성의 단계는 다음과 같습니다:

  1. this엔트리와 이벤트가 비활성화된 경우, false를 반환합니다.

  2. 단언: this현재 엔트리 인덱스가 −1이 아님을 확인합니다.

  3. this현재 엔트리 인덱스this엔트리 목록크기 - 1과 같으면 false를 반환합니다.

  4. true를 반환합니다.

{ committed, finished } = navigation.navigate(url)
{ committed, finished } = navigation.navigate(url, options)

현재 페이지를 주어진 url내비게이트합니다. options에는 다음과 같은 값을 포함할 수 있습니다:

기본적으로는 전체 내비게이션(즉, 교차 문서 내비게이션)을 수행하며, 주어진 URL이 현재 URL과 프래그먼트만 다를 경우에는 예외입니다. navigateEvent.intercept() 메서드를 사용하여 이를 동일 문서 내비게이션으로 변환할 수 있습니다.

반환된 프로미스는 다음과 같이 동작합니다:

모든 경우에서, 반환된 프로미스가 완료될 때는 내비게이트된 NavigationHistoryEntry로 완료됩니다.

{ committed, finished } = navigation.reload(options)

현재 페이지를 리로드합니다. options에는 infostate를 포함할 수 있으며, 이들은 위에서 설명한 대로 동작합니다.

기본적으로 현재 페이지를 네트워크 또는 캐시에서 다시 로드하는 동작은 navigateEvent.intercept() 메서드를 사용하여 오버라이드할 수 있습니다. 이렇게 하면 이 호출은 상태만 업데이트하거나 적절한 info를 전달하고, navigate 이벤트 핸들러가 수행하려는 작업을 수행하게 됩니다.

반환된 프로미스는 다음과 같이 동작합니다:

{ committed, finished } = navigation.traverseTo(key)
{ committed, finished } = navigation.traverseTo(key, { info })

주어진 key와 일치하는 가장 가까운 세션 히스토리 엔트리트래버스합니다. info는 임의의 값으로 설정할 수 있으며, 해당 info 속성을 채웁니다. NavigateEvent

해당 세션 히스토리 엔트리로의 트래버스가 이미 진행 중인 경우, 이 메서드는 원래의 트래버스에 대한 프로미스를 반환하며, info 는 무시됩니다.

반환된 프로미스는 다음과 같이 동작합니다:

{ committed, finished } = navigation.back(key)
{ committed, finished } = navigation.back(key, { info })

가장 가까운 이전 세션 히스토리 엔트리로 트래버스하여 내비게이션 가능한 요소를 이동시킵니다. 즉, 다른 NavigationHistoryEntry와 일치하여 navigation.currentEntry가 변경됩니다. info는 임의의 값으로 설정할 수 있으며, 해당 info 속성을 채웁니다. NavigateEvent

해당 세션 히스토리 엔트리로의 트래버스가 이미 진행 중인 경우, 이 메서드는 원래의 트래버스에 대한 프로미스를 반환하며, info 는 무시됩니다.

반환된 프로미스는 traverseTo()에서 반환된 것과 동일하게 동작합니다.

{ committed, finished } = navigation.forward(key)
{ committed, finished } = navigation.forward(key, { info })

가장 가까운 이후 세션 히스토리 엔트리로 트래버스하여 내비게이션 가능한 요소를 이동시킵니다. 즉, 다른 NavigationHistoryEntry와 일치하여 navigation.currentEntry가 변경됩니다. info는 임의의 값으로 설정할 수 있으며, 해당 info 속성을 채웁니다. NavigateEvent

해당 세션 히스토리 엔트리로의 트래버스가 이미 진행 중인 경우, 이 메서드는 원래의 트래버스에 대한 프로미스를 반환하며, info 는 무시됩니다.

반환된 프로미스는 traverseTo()에서 반환된 것과 동일하게 동작합니다.

navigate(url, options) 메서드 단계는 다음과 같습니다:

  1. urlRecordURL을 구문 분석한 결과로 설정합니다. urlthis관련 설정 객체에 상대적으로 제공합니다.

  2. urlRecord가 실패한 경우, urlRecord에 대해 초기 오류 결과를 반환하고, "SyntaxError" DOMException을 반환합니다.

  3. documentthis관련 글로벌 객체연관된 Document로 설정합니다.

  4. options["history"]가 "push"로 설정되어 있고, urlRecorddocument에 대해 이동이 교체여야 하는 경우, urlRecorddocument에 대해 초기 오류 결과를 반환하고, "NotSupportedError" DOMException을 반환합니다.

  5. stateoptions["state"]로 설정하고, 존재하는 경우 존재합니다; 그렇지 않으면, undefined로 설정합니다.

  6. serializedStateStructuredSerializeForStorage(state)로 설정합니다. 예외가 발생하면, 그 예외에 대해 초기 오류 결과를 반환합니다.

    이 단계는 초기 단계에서 수행되어야 합니다. 왜냐하면 직렬화는 웹 개발자 코드를 호출할 수 있으며, 이는 이후 단계에서 확인하는 여러 가지를 변경할 수 있기 때문입니다.

  7. document완전히 활성화된 상태가 아니라면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  8. document언로드 카운터가 0보다 크다면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  9. infooptions["info"]로 설정하고, 존재하는 경우 존재합니다; 그렇지 않으면, undefined로 설정합니다.

  10. apiMethodTracker향후 비트래버스 API 메서드 트래커 설정 시도의 결과로 설정하고, this에 대해 infoserializedState를 제공합니다.

  11. 내비게이트 document노드 네비게이블urlRecord로 이동하고, document를 사용하며, historyHandlingoptions["history"]에 설정하고, navigationAPIStateserializedState에 설정합니다.

    location.assign()과 같은 기능은 도메인 경계 내 동일 출처 간에 노출되는 반면, navigation.navigate()window.navigation 속성에 대한 직접적인 동기식 접근이 있는 코드만 액세스할 수 있습니다. 따라서, 내비게이션의 소스 문서에 대한 귀속 문제를 피하고, 샌드박싱에 의해 내비게이션이 허용되었는지 확인 및 이에 동반되는 예외 허용 플래그를 처리할 필요가 없습니다. 모든 내비게이션을 이 Document에 해당하는 Navigation 객체 자체에서 나온 것처럼 처리합니다 (즉, document).

  12. this향후 비트래버스 API 메서드 트래커apiMethodTracker라면, 다음을 수행합니다:

    향후 비트래버스 API 메서드 트래커가 여전히 apiMethodTracker인 경우, 이는 navigate 알고리즘이 내부 navigate 이벤트 발사 알고리즘에 도달하기 전에 중단되었음을 의미하며, 이는 향후 API 메서드 트래커를 진행 중으로 승격시킬 수 있었을 것입니다.

    1. this향후 비트래버스 API 메서드 트래커를 null로 설정합니다.

    2. 초기 오류 결과를 ""AbortError""에 대해 반환합니다 DOMException.

  13. API 메서드 트래커 파생 결과apiMethodTracker에 대해 반환합니다.

reload(options) 메서드 단계는 다음과 같습니다:

  1. documentthis관련 글로벌 객체연관된 Document로 설정합니다.

  2. serializedStateStructuredSerializeForStorage(undefined)로 설정합니다.

  3. 만약 options["state"]가 존재한다면, serializedStateStructuredSerializeForStorage(options["state"])로 설정합니다. 만약 이 과정에서 예외가 발생하면, 그 예외에 대한 초기 오류 결과를 반환합니다.

    이 단계는 초기 단계에서 수행되어야 합니다. 직렬화 과정에서 웹 개발자 코드를 호출할 수 있으며, 이는 이후 단계에서 확인할 다양한 요소를 변경할 수 있기 때문입니다.

  4. 그렇지 않으면:

    1. current현재 항목으로 설정합니다. this의 항목으로 설정합니다.

    2. 만약 current가 null이 아니라면, serializedStatecurrent세션 기록 항목내비게이션 API 상태로 설정합니다.

  5. document완전히 활성화된 상태가 아니라면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  6. document언로드 카운터가 0보다 크다면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  7. infooptions["info"]로 설정하고, 존재하는 경우 존재합니다; 그렇지 않으면, undefined로 설정합니다.

  8. apiMethodTracker향후 비트래버스 API 메서드 트래커 설정 시도의 결과로 설정하고, this에 대해 infoserializedState를 제공합니다.

  9. 다시 로드 document노드 네비게이블navigationAPIState로 설정하고, serializedState에 설정합니다.

  10. API 메서드 트래커 파생 결과apiMethodTracker에 대해 반환합니다.

traverseTo(key, options) 메서드 단계는 다음과 같습니다:

  1. this현재 항목 인덱스가 -1이라면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  2. this항목 목록포함되지 않은 NavigationHistoryEntry가 있거나, 해당 세션 기록 항목네비게이션 API 키key와 일치하지 않으면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  3. 네비게이션 API 탐색 수행의 결과를 this, key, options을 주고 반환합니다.

back(options) 메서드 단계는 다음과 같습니다:

  1. this현재 항목 인덱스가 -1 또는 0이면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  2. keythis항목 목록[this현재 항목 인덱스 - 1]의 세션 기록 항목네비게이션 API 키로 설정합니다.

  3. 네비게이션 API 탐색 수행의 결과를 this, key, options을 주고 반환합니다.

forward(options) 메서드 단계는 다음과 같습니다:

  1. this현재 항목 인덱스가 -1이거나, this항목 목록크기 - 1과 같다면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  2. keythis항목 목록[this현재 항목 인덱스 + 1]의 세션 기록 항목네비게이션 API 키로 설정합니다.

  3. 네비게이션 API 탐색 수행의 결과를 this, key, options을 주고 반환합니다.

네비게이션 API 탐색을 수행하기 위해 Navigation navigation, 문자열 key, 및 NavigationOptions options가 주어졌을 때:

  1. documentnavigation관련 글로벌 객체연관된 Document로 설정합니다.

  2. 만약 document완전히 활성화된 상태가 아니라면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  3. 만약 document언로드 카운터가 0보다 크다면, 초기 오류 결과를 반환하고, "InvalidStateError" DOMException을 반환합니다.

  4. currentnavigation현재 항목으로 설정합니다.

  5. 만약 keycurrent세션 기록 항목네비게이션 API 키와 같다면, «[ "committed" → 해결된 약속 current, "finished" → 해결된 약속 current ]»을 반환합니다.

  6. 만약 navigation다가오는 탐색 API 메서드 트래커들[key]가 존재한다면, 네비게이션 API 메서드 트래커 파생 결과navigation다가오는 탐색 API 메서드 트래커들[key]에 대해 반환합니다.

  7. infooptions["info"]로 설정하고, 존재하는 경우 존재합니다; 그렇지 않으면, undefined로 설정합니다.

  8. apiMethodTracker다가오는 탐색 API 메서드 트래커 추가의 결과로 설정하고, navigation에 대해 keyinfo를 제공합니다.

  9. navigabledocument노드 네비게이블로 설정합니다.

  10. traversablenavigable탐색 가능한 네비게이블로 설정합니다.

  11. sourceSnapshotParamsdocument에 대해 소스 스냅샷 매개변수 스냅샷의 결과로 설정합니다.

  12. traversable다음 세션 기록 탐색 단계를 추가합니다:

    1. navigableSHEsnavigable에 대해 세션 기록 항목 가져오기의 결과로 설정합니다.

    2. targetSHEnavigableSHEs 내에서 key와 일치하는 네비게이션 API 키를 가진 세션 기록 항목으로 설정합니다. 만약 그러한 항목이 존재하지 않는다면:

      1. 글로벌 작업 대기열navigation관련 글로벌 객체를 제공하여, apiMethodTracker의 완료된 약속을 거절하고, "InvalidStateError" DOMException을 반환합니다.

      2. 이 단계를 중단합니다.

      이 경로는 navigation항목 목록navigableSHEs와 비교하여 오래된 경우에 선택됩니다. 이는 기록 변경에 대한 반응으로 관련된 모든 스레드와 프로세스가 동기화되는 동안 짧은 기간 동안 발생할 수 있습니다.

    3. 만약 targetSHEnavigable활성 세션 기록 항목이라면, 이 단계를 중단합니다.

      이 경우는 이전에 대기열에 추가된 탐색이 이미 이 세션 기록 항목으로 이동했을 때 발생할 수 있습니다. 이 경우 이전 탐색이 이미 apiMethodTracker를 처리했을 것입니다.

    4. resulttargetSHE단계에 따라 traversable에 대해 탐색 기록 단계를 적용한 결과로 설정하고, sourceSnapshotParams, navigable, 및 "none"을 사용합니다.

    5. 만약 result가 "canceled-by-beforeunload"이라면, 글로벌 작업 대기열navigation관련 글로벌 객체를 제공하여, apiMethodTracker의 완료된 약속을 거절하고, 새로운 "AbortError" DOMExceptionnavigation관련 영역에서 생성합니다.

    6. 만약 result가 "initiator-disallowed"이라면, 글로벌 작업 대기열navigation관련 글로벌 객체를 제공하여, apiMethodTracker의 완료된 약속을 거절하고, 새로운 "SecurityError" DOMExceptionnavigation관련 영역에서 생성합니다.

      result가 "canceled-by-beforeunload" 또는 "initiator-disallowed"일 때, navigate 이벤트는 발생하지 않았으며, 진행 중인 네비게이션 중단은 올바르지 않을 것입니다. 이는 navigateerror 이벤트 없이 이전 navigate 이벤트 없이 발생할 수 있습니다.

      "canceled-by-navigate"의 경우, navigate 이벤트가 발생하지만, 내부 navigate 이벤트 발생 알고리즘진행 중인 네비게이션 중단을 처리할 것입니다.

  13. apiMethodTracker에 대해 네비게이션 API 메서드 트래커 파생 결과를 반환합니다.

초기 오류 결과는 예외 e에 대해 NavigationResult 딕셔너리 인스턴스로 주어지며, «[ "committed" → 거절된 약속 e, "finished" → 거절된 약속 e ]»로 주어집니다.

네비게이션 API 메서드 트래커 파생 결과네비게이션 API 메서드 트래커에 대해 NavigationResult 딕셔너리 인스턴스로 주어지며, «[ "committed" → apiMethodTracker커밋된 약속, "finished" → apiMethodTracker완료된 약속 ]»로 주어집니다.

7.2.6.8 진행 중인 네비게이션 추적

어떤 네비게이션(단어의 광범위한 의미에서)이든, Navigation 객체는 다음을 추적해야 합니다:

모든 네비게이션에 대해
상태 기간 설명
NavigateEvent 이벤트가 발생하는 동안 이벤트가 발생하는 동안 네비게이션이 취소되면, 이벤트를 취소할 수 있도록
이벤트의 중단 컨트롤러 intercept()에 전달된 핸들러에서 반환된 모든 약속이 해결될 때까지 네비게이션이 취소되면 중단 신호를 보낼 수 있도록
새 요소가 포커스된 여부 intercept()에 전달된 모든 약속이 해결될 때까지 만약 포커스가 변경된 경우, 포커스가 리셋되지 않도록
NavigationHistoryEntry에 대한 네비게이션 여부 결정된 후부터 intercept()에 전달된 모든 약속이 해결될 때까지 committedfinished 약속을 무엇으로 해결할지 알 수 있도록
반환된 모든 finished 약속 intercept()에 전달된 모든 약속이 해결될 때까지 적절하게 해결하거나 거절할 수 있도록
"traverse"가 아닌 네비게이션에 대해
상태 기간 설명
state 이벤트가 발생하는 동안 이벤트가 취소되지 않은 채로 발생이 완료되면, 현재 항목의 네비게이션 API 상태를 업데이트할 수 있도록
"traverse" 네비게이션에 대해
상태 기간 설명
info navigate 이벤트를 발생시키는 작업이 대기열에 추가될 때까지 세션 기록 탐색 대기열을 거친 후 navigate 이벤트를 발생시키기 위해 사용될 수 있도록
반환된 모든 committed 약속 세션 기록이 업데이트될 때까지(동일한 작업 내에서) 적절하게 해결하거나 거절할 수 있도록
intercept()가 호출되었는지 여부 세션 기록이 업데이트될 때까지(동일한 작업 내에서) 기본 스크롤 복원 로직을 억제하고 scroll 옵션에 의해 주어진 동작을 따를 수 있도록

또한, 다음과 같은 웹 개발자 코드로 인해 주어진 시간에 단일 네비게이션 요청만 있다고 가정할 수 없습니다:

const p1 = navigation.navigate(url1).finished;
const p2 = navigation.navigate(url2).finished;

즉, 이 시나리오에서는 url2로 네비게이션하는 동안에도 여전히 약속 p1을 유지하여 거절할 수 있어야 합니다. navigate()에 대한 두 번째 호출이 발생하는 순간 진행 중인 네비게이션 약속을 모두 제거할 수는 없습니다.

우리는 이 모든 것을 각 Navigation과 다음을 연관시켜 달성합니다:

여기에서 네비게이션 API 메서드 추적기에 저장되지 않은 상태는 네비게이션 API 메서드에 의해 시작되지 않은 네비게이션에도 추적해야 하는 상태입니다.

네비게이션 API 메서드 추적기는 다음 구조체와 함께 항목들로 구성됩니다:

이 모든 상태는 다음 알고리즘을 통해 관리됩니다.

다가오는 비-트래버스 API 메서드 추적기를 설정할지 여부를 결정하기 위해 Navigation navigation, 자바스크립트 값 info, 그리고 직렬화된 상태 또는 null serializedState를 전달받았을 때:

  1. committedPromisefinishedPromisenavigation관련 영역에서 새롭게 생성된 약속으로 설정합니다.

  2. 처리된 것으로 표시합니다 finishedPromise를.

    웹 개발자는 finishedPromise가 거부되는 것에 반드시 신경 쓰지 않을 수 있습니다:

    • 그들은 committedPromise에만 신경을 쓸 수 있습니다.

    • 같은 작업 내에서 여러 번의 동기 네비게이션을 수행할 수도 있으며, 이 경우 마지막을 제외한 모든 finishedPromise가 중단될 수 있습니다. 이로 인해 응용 프로그램에 버그가 발생할 수 있지만, 다른 부분이 서로의 작업을 덮어쓰는 응용 프로그램의 기능일 수도 있습니다.

    • 그들은 finishedPromise 대신 다른 전환 실패 신호를 듣는 것을 선호할 수 있습니다. 예를 들어 navigateerror 이벤트 또는 navigation.transition.finished 약속.

    따라서 이를 처리된 것으로 표시하여 unhandledrejection 이벤트가 발생하지 않도록 보장합니다.

  3. apiMethodTracker를 다음과 같이 새 네비게이션 API 메서드 추적기로 설정합니다:

    네비게이션 객체
    navigation
    null
    정보
    info
    직렬화된 상태
    serializedState
    커밋된 항목
    null
    커밋된 약속
    committedPromise
    완료된 약속
    finishedPromise
  4. 단언: navigation다가오는 비-트래버스 API 메서드 추적기는 null입니다.

  5. navigation항목 및 이벤트가 비활성화된 상태가 아니면, navigation다가오는 비-트래버스 API 메서드 추적기apiMethodTracker로 설정합니다.

    navigation항목 및 이벤트가 비활성화된 상태인 경우 committedPromisefinishedPromise는 절대 완료되지 않습니다(이러한 NavigationHistoryEntry 객체를 생성하지 않으므로 이를 해결할 방법이 없기 때문입니다); serializedState를 적용할 NavigationHistoryEntry가 없으며, info와 함께 포함될 navigate 이벤트도 없습니다. 따라서 이 API 메서드 호출을 추적할 필요가 없습니다.

  6. apiMethodTracker를 반환합니다.

다가오는 트래버스 API 메서드 추적기 추가하기 위해 Navigation navigation, 문자열 destinationKey, 그리고 자바스크립트 값 info를 전달받았을 때:

  1. committedPromisefinishedPromisenavigation관련 영역에서 새롭게 생성된 약속으로 설정합니다.

  2. 처리된 것으로 표시합니다 finishedPromise를.

    이것이 수행되는 이유에 대한 이전 설명을 참조하세요.

  3. apiMethodTracker를 다음과 같이 새 네비게이션 API 메서드 추적기로 설정합니다:

    네비게이션 객체
    navigation
    destinationKey
    정보
    info
    직렬화된 상태
    null
    커밋된 항목
    null
    커밋된 약속
    committedPromise
    완료된 약속
    finishedPromise
  4. navigation다가오는 트래버스 API 메서드 추적기들[key]을 apiMethodTracker로 설정합니다.

  5. apiMethodTracker를 반환합니다.

Navigation navigation 및 문자열 또는 null destinationKey를 제공받아 다가오는 API 메서드 추적기를 현재 진행 중인 것으로 승격하려면 다음을 수행합니다:

  1. 단언: navigation진행 중인 API 메서드 추적기가 null이어야 합니다.

  2. destinationKey가 null이 아닌 경우:

    1. 단언: navigation다가오는 비-트래버스 API 메서드 추적기가 null이어야 합니다.

    2. 만약 navigation다가오는 트래버스 API 메서드 추적기[destinationKey]가 존재하는 경우:

      1. navigation진행 중인 API 메서드 추적기navigation다가오는 트래버스 API 메서드 추적기[destinationKey]로 설정합니다.

      2. 제거합니다 navigation다가오는 트래버스 API 메서드 추적기[destinationKey].

  3. 그 외의 경우:

    1. navigation진행 중인 API 메서드 추적기navigation다가오는 비-트래버스 API 메서드 추적기로 설정합니다.

    2. navigation다가오는 비-트래버스 API 메서드 추적기를 null로 설정합니다.

정리하려면 navigation API method tracker apiMethodTracker를 다음과 같이 수행하십시오:

  1. apiMethodTrackernavigation 객체navigation으로 설정합니다.

  2. 만약 navigation진행 중인 API 메서드 추적기apiMethodTracker라면, navigation진행 중인 API 메서드 추적기를 null로 설정합니다.

  3. 그렇지 않으면:

    1. apiMethodTrackerkeykey로 설정합니다.

    2. 단언: key가 null이 아닙니다.

    3. 단언: navigation다가오는 트래버스 API 메서드 추적기[key]가 존재하는지 확인합니다.

    4. 제거합니다 navigation다가오는 트래버스 API 메서드 추적기[key].

NavigationHistoryEntry nheNavigation API 메서드 추적기 apiMethodTracker를 제공받아 확정된 항목에 대해 알림을 수행하려면 다음을 수행합니다:

  1. apiMethodTracker확정된 항목nhe로 설정합니다.

  2. 만약 apiMethodTracker직렬화된 상태가 null이 아니라면, nhe세션 기록 항목Navigation API 상태apiMethodTracker직렬화된 상태로 설정합니다.

    이것이 null인 경우, 우리는 navigation.traverseTo()를 통해 nhe로 이동 중입니다. 이는 상태 변경을 허용하지 않습니다.

    이 시점에서 apiMethodTracker직렬화된 상태는 더 이상 필요하지 않습니다. 구현에서는 Navigation API 메서드 추적기의 수명 동안 이를 유지하지 않도록 지우는 것이 좋습니다.

  3. apiMethodTracker확정된 약속nhe로 해결합니다.

    이 시점에서 apiMethodTracker확정된 약속은 저작자 코드에 아직 반환되지 않은 경우에만 필요합니다. 구현에서는 Navigation API 메서드 추적기의 수명 동안 이를 유지하지 않도록 지우는 것이 좋습니다.

navigation API 메서드 추적기 apiMethodTracker완료된 약속을 해결하려면:

  1. apiMethodTracker확정된 약속확정된 항목으로 해결합니다.

    일반적으로 확정된 항목에 대해 알림이 이미 apiMethodTracker에서 호출되었기 때문에, 이 단계는 아무것도 하지 않습니다. 그러나 어떤 경우에는 완료된 약속을 해결이 직접 호출될 수 있으며, 이 단계가 필요합니다.

  2. apiMethodTracker완료된 약속확정된 항목으로 해결합니다.

  3. 정리 apiMethodTracker.

navigation API 메서드 추적기 apiMethodTracker완료된 약속을 거부하려면 JavaScript 값 exception을 사용하여 다음을 수행합니다:

  1. apiMethodTracker확정된 약속exception으로 거부합니다.

    이것은 apiMethodTracker확정된 약속이 이전에 확정된 항목에 대해 알림을 통해 해결된 경우 아무 일도 하지 않습니다.

  2. apiMethodTracker완료된 약속exception으로 거부합니다.

  3. 정리 apiMethodTracker.

옵션 DOMException error와 함께 Navigation navigation진행 중인 탐색을 중단하려면 다음을 수행합니다:

  1. navigation진행 중인 navigate 이벤트event로 설정합니다.

  2. 단언: event가 null이 아닙니다.

  3. navigation진행 중인 탐색 중 포커스 변경됨을 false로 설정합니다.

  4. navigation진행 중인 탐색 중 정상 스크롤 복원 억제를 false로 설정합니다.

  5. error가 제공되지 않은 경우, errornavigation관련 영역에서 생성된 새로운 "AbortError" DOMException으로 설정합니다.

  6. event전달 플래그가 설정된 경우, event취소된 플래그를 true로 설정합니다.

  7. error를 제공한 abortevent중단 컨트롤러에 신호를 보냅니다.

  8. navigation진행 중인 navigate 이벤트를 null로 설정합니다.

  9. error에서 오류 정보 추출의 결과를 errorInfo로 설정합니다.

    예를 들어, 이 알고리즘이 window.stop() 호출로 인해 실행되는 경우, 이러한 속성들은 window.stop()을 호출한 스크립트 줄을 기반으로 초기화될 수 있습니다. 그러나 사용자가 중지 버튼을 클릭한 경우, 이러한 속성들은 빈 문자열 또는 0과 같은 기본 값으로 초기화될 가능성이 큽니다.

  10. 이벤트를 실행하고 navigation에서 navigateerror라는 이름을 사용하여, ErrorEvent를 사용하여 추가 속성을 errorInfo에 따라 초기화합니다.

  11. 만약 navigation진행 중인 API 메서드 추적기가 null이 아닌 경우, 완료된 약속을 거부 apiMethodTracker에 대해 error와 함께 수행합니다.

  12. 만약 navigation전환이 null이 아닌 경우:

    1. navigation전환완료된 약속error로 거부합니다.

    2. navigation전환을 null로 설정합니다.

탐색 취소에 대해 navigation API에 알리려면 탐색 가능한 navigable에서 다음을 수행하십시오:

  1. 이 알고리즘이 navigable활성 창관련 에이전트이벤트 루프에서 실행 중이라면, 다음 단계로 진행합니다. 그렇지 않으면, navigable활성 창에 대해 다음 단계를 실행하도록 전역 작업을 대기열에 추가합니다.

  2. navigationnavigable활성 창탐색 API로 설정합니다.

  3. 만약 navigation진행 중인 navigate 이벤트가 null이면, 반환합니다.

  4. 진행 중인 탐색을 중단navigation에 대해 수행합니다.

자식 탐색 가능 객체 파괴에 대해 탐색 API에 알림탐색 가능 객체 navigable에 대해 수행하려면:

  1. 탐색 중단에 대해 탐색 API에 알림navigable에서 수행합니다.

  2. navigationnavigable활성 창탐색 API로 설정합니다.

  3. traversalAPIMethodTrackersnavigation다가오는 탐색 API 메서드 추적기클론으로 설정합니다.

  4. traversalAPIMethodTrackersapiMethodTracker에 대해 완료된 약속을 거부합니다. "AbortError" DOMExceptionnavigation관련 영역에서 생성됩니다.


진행 중인 탐색 개념은 웹 개발자에게 navigation.transition 속성을 통해 가장 직접적으로 노출됩니다. 이 속성은 NavigationTransition 인터페이스의 인스턴스입니다:

[Exposed=Window]
interface NavigationTransition {
  readonly attribute NavigationType navigationType;
  readonly attribute NavigationHistoryEntry from;
  readonly attribute Promise<undefined> finished;
};
navigation.transition

아직 navigatesuccess 또는 navigateerror 단계에 도달하지 않은 진행 중인 탐색을 나타내는 NavigationTransition 입니다. 이러한 전환이 없으면 null을 반환합니다.

navigation.currentEntry (및 location.href와 같은 다른 속성들)이 탐색 시 즉시 업데이트되므로, 이 navigation.transition 속성은 탐색이 아직 완전히 완료되지 않았는지 확인하는 데 유용합니다.

navigation.transition.navigationType

이 전환이 어떤 유형의 탐색에 해당하는지를 나타내는 "push", "replace", "reload", 또는 "traverse" 중 하나입니다.

navigation.transition.from

전환이 시작된 NavigationHistoryEntry 를 반환합니다. 이는 navigation.currentEntry와 비교하는 데 유용할 수 있습니다.

navigation.transition.finished

이 속성은 navigatesuccess 이벤트가 발생할 때 완료되거나, navigateerror 이벤트가 발생할 때 거부되는 프로미스를 반환합니다.

Navigation 객체는 transition을 가지며, 이는 NavigationTransition 또는 null입니다. 처음에는 null로 설정됩니다.

transition getter 단계는 thistransition을 반환하는 것입니다.

NavigationTransition에는 navigation type이 연결되어 있으며, 이는 NavigationType입니다.

NavigationTransition에는 from entry가 연결되어 있으며, 이는 NavigationHistoryEntry입니다.

NavigationTransition에는 finished promise가 연결되어 있으며, 이는 프로미스입니다.

navigationType getter 단계는 thisnavigation type을 반환하는 것입니다.

from getter 단계는 thisfrom entry를 반환하는 것입니다.

finished getter 단계는 thisfinished promise를 반환하는 것입니다.

[Exposed=Window]
interface NavigationActivation {
  readonly attribute NavigationHistoryEntry? from;
  readonly attribute NavigationHistoryEntry entry;
  readonly attribute NavigationType navigationType;
};
navigation.activation

문서를 "활성화한" 가장 최근의 문서 간 탐색에 대한 정보를 포함하는 NavigationActivation입니다.

navigation.currentEntry문서URL이 동일한 문서 내 탐색으로 인해 정기적으로 업데이트될 수 있는 반면, navigation.activation은 일정하게 유지되며, 문서가 기록에서 다시 활성화될 때만 해당 속성이 업데이트됩니다.

navigation.activation.entry

문서가 활성화될 때의 navigation.currentEntry 속성 값과 동일한 NavigationHistoryEntry입니다.

navigation.activation.from

현재 문서 바로 전에 활성화되었던 문서를 나타내는 NavigationHistoryEntry입니다. 이전 문서가 이 문서와 동일 출처가 아니거나, 초기 about:blank 문서인 경우 null 값을 가집니다.

from 또는 entry NavigationHistoryEntry 객체가 traverseTo() 메서드의 유효한 대상이 되지 않을 수 있는 몇 가지 사례가 있습니다. 예를 들어, 문서location.replace()를 사용하여 활성화되거나, 초기 항목이 history.replaceState()로 대체될 수 있습니다. 그러나 이러한 항목의 url 속성과 getState() 메서드는 여전히 접근 가능합니다.

navigation.activation.navigationType

문서를 활성화한 탐색 유형을 나타내는 "push", "replace", "reload", 또는 "traverse" 중 하나입니다.

Navigation 객체는 관련된 activation을 가지며, 이는 null 또는 NavigationActivation 객체이며, 초기 값은 null입니다.

NavigationActivation은 다음을 가집니다:

activation getter 단계는 thisactivation을 반환하는 것입니다.

from getter 단계는 thisold entry를 반환하는 것입니다.

entry getter 단계는 thisnew entry를 반환하는 것입니다.

navigationType getter 단계는 thisnavigation type을 반환하는 것입니다.

7.2.6.10 navigate 이벤트

네비게이션 API의 주요 기능 중 하나는 navigate 이벤트입니다. 이 이벤트는 (단어의 광범위한 의미에서) 모든 네비게이션에서 발생하여, 웹 개발자가 이러한 외부 네비게이션을 모니터링할 수 있도록 합니다. 많은 경우에 이 이벤트는 취소 가능하며, 이를 통해 네비게이션의 진행을 막을 수 있습니다. 또한, 다른 경우에는 intercept() 메서드를 사용하여 네비게이션을 가로채고 동일 문서 내 네비게이션으로 대체할 수 있습니다.

7.2.6.10.1 NavigateEvent 인터페이스
[Exposed=Window]
interface NavigateEvent : Event {
  constructor(DOMString type, NavigateEventInit eventInitDict);

  readonly attribute NavigationType navigationType;
  readonly attribute NavigationDestination destination;
  readonly attribute boolean canIntercept;
  readonly attribute boolean userInitiated;
  readonly attribute boolean hashChange;
  readonly attribute AbortSignal signal;
  readonly attribute FormData? formData;
  readonly attribute DOMString? downloadRequest;
  readonly attribute any info;
  readonly attribute boolean hasUAVisualTransition;

  undefined intercept(optional NavigationInterceptOptions options = {});
  undefined scroll();
};

dictionary NavigateEventInit : EventInit {
  NavigationType navigationType = "push";
  required NavigationDestination destination;
  boolean canIntercept = false;
  boolean userInitiated = false;
  boolean hashChange = false;
  required AbortSignal signal;
  FormData? formData = null;
  DOMString? downloadRequest = null;
  any info;
  boolean hasUAVisualTransition = false;
};

dictionary NavigationInterceptOptions {
  NavigationInterceptHandler handler;
  NavigationFocusReset focusReset;
  NavigationScrollBehavior scroll;
};

enum NavigationFocusReset {
  "after-transition",
  "manual"
};

enum NavigationScrollBehavior {
  "after-transition",
  "manual"
};

callback NavigationInterceptHandler = Promise<undefined> ();
event.navigationType

"push", "replace", "reload", 또는 "traverse" 중 하나로, 이 네비게이션의 유형을 나타냅니다.

event.destination

네비게이션의 목적지를 나타내는 NavigationDestination입니다.

event.canIntercept

이 네비게이션을 가로채고 동일 문서 내 네비게이션으로 전환할 수 있는 intercept() 메서드를 호출할 수 있는 경우 true, 그렇지 않으면 false입니다.

일반적으로, 현재 문서가 목적지 URL로의 재작성 가능성을 가지고 있는 한, 이 값은 true입니다. 그러나 "문서 간 traverse" 네비게이션의 경우 항상 false입니다.

event.userInitiated

이 네비게이션이 a 요소를 클릭하거나, form 요소를 제출하거나, 브라우저 UI를 사용하여 발생한 경우 true, 그렇지 않으면 false입니다.

event.hashChange

프래그먼트 네비게이션의 경우 true, 그렇지 않으면 false입니다.

event.signal

사용자가 브라우저의 "중지" 버튼을 누르거나 다른 네비게이션이 이 네비게이션을 방해하는 등으로 인해 네비게이션이 취소되면 중단되는 AbortSignal입니다.

개발자가 이 네비게이션을 처리하는 과정에서 수행하는 비동기 작업에 대해 이 신호를 전달하는 것이 권장됩니다. 예를 들어, fetch()를 호출할 때 이 신호를 전달할 수 있습니다.

event.formData

이 네비게이션이 "push" 또는 "replace" 네비게이션으로, 양식 제출을 나타내는 경우, 제출된 양식 항목을 나타내는 FormData입니다. 그렇지 않으면 null입니다.

(특히, 원래 양식 제출로 생성된 세션 기록 항목을 다시 방문하는 "reload" 또는 "traverse" 네비게이션의 경우에도 이 값은 null입니다.)

event.downloadRequest

이 네비게이션이 a 또는 area 요소의 download 속성을 사용하여 다운로드로 요청되었는지를 나타냅니다:

다운로드가 요청되었다고 해서 항상 다운로드가 발생하는 것은 아닙니다. 예를 들어, 다운로드가 브라우저 보안 정책에 의해 차단되거나 "push" 네비게이션으로 처리될 수 있습니다.

마찬가지로, 다운로드가 요청되지 않았더라도, 목적지 서버가 `Content-Disposition: attachment` 헤더를 반환하여 다운로드가 발생할 수 있습니다.

마지막으로, 브라우저 UI 기능을 사용하여 시작된 다운로드에 대해서는 navigate 이벤트가 전혀 발생하지 않는다는 점에 유의하세요. 예를 들어, 마우스 오른쪽 버튼을 클릭하고 링크의 대상을 저장하는 것을 선택하는 경우가 이에 해당합니다.

event.info

이 네비게이션을 시작한 네비게이션 API 메서드 중 하나를 통해 전달된 임의의 JavaScript 값입니다. 사용자가 직접 시작했거나 다른 API에 의해 시작된 경우에는 undefined입니다.

event.hasUAVisualTransition

사용자 에이전트가 이 네비게이션에 대해 시각적 전환을 수행한 후에 이 이벤트가 디스패치되었는지 여부를 나타내며, 이 값이 true인 경우, 저자가 DOM을 즉시 포스트 네비게이션 상태로 업데이트하는 것이 최상의 사용자 경험을 제공합니다.

event.intercept({ handler, focusReset, scroll })

이 네비게이션을 가로채고, 이를 일반적인 처리 대신 목적지 URL로의 동일 문서 내 네비게이션으로 변환합니다.

handler 옵션은 프로미스를 반환하는 함수일 수 있습니다. 이 함수는 navigate 이벤트가 완료된 후 실행되며, navigation.currentEntry 속성이 동기적으로 업데이트된 후에 실행됩니다. 이 반환된 프로미스는 네비게이션의 지속 시간과 성공 또는 실패를 신호하는 데 사용됩니다. 프로미스가 완료된 후, 브라우저는 로딩 스피너 UI 또는 보조 기술을 통해 네비게이션이 완료되었음을 사용자에게 신호합니다. 또한, 적절한 경우 navigatesuccess 또는 navigateerror 이벤트를 발생시켜 웹 애플리케이션의 다른 부분이 이에 응답할 수 있습니다.

기본적으로, 이 메서드를 사용하면 반환된 프로미스가 완료될 때 포커스가 초기화됩니다. 포커스는 autofocus 속성이 설정된 첫 번째 요소로 리셋되거나, 해당 속성이 없는 경우 body 요소로 리셋됩니다. focusReset 옵션을 "manual"로 설정하여 이 동작을 피할 수 있습니다.

기본적으로, 이 메서드를 사용하면 "traverse" 또는 "reload" 네비게이션의 경우 브라우저의 스크롤 복원 로직이, "push" 또는 "replace" 네비게이션의 경우 스크롤 리셋/프래그먼트로의 스크롤 로직이 지연됩니다. 이 지연은 모든 핸들러의 반환된 프로미스가 완료될 때까지 유지됩니다. scroll 옵션을 "manual"로 설정하여 이 네비게이션에 대해 브라우저 구동 스크롤 동작을 완전히 비활성화할 수 있으며, 또는 scroll() 메서드를 프로미스가 완료되기 전에 호출하여 이 동작을 조기에 트리거할 수 있습니다.

이 메서드는 canIntercept 값이 false이거나 isTrusted 값이 false인 경우 ""SecurityError" DOMException" 예외를 발생시킵니다. 또한, 이벤트 디스패치 중에 동기적으로 호출되지 않은 경우 ""InvalidStateError" DOMException" 예외를 발생시킵니다.

event.scroll()

"traverse" 또는 "reload" 네비게이션의 경우, 브라우저의 일반적인 스크롤 복원 로직을 사용하여 스크롤 위치를 복원합니다.

"push" 또는 "replace" 네비게이션의 경우, 문서 상단으로 스크롤 위치를 리셋하거나, 프래그먼트가 있는 경우 destination.url에 지정된 프래그먼트로 스크롤합니다.

이 메서드가 여러 번 호출되거나 자동 포스트 전환 스크롤 처리가 scroll 옵션이 "after-transition"로 설정된 경우, 또는 네비게이션이 커밋되기 전에 호출되면 이 메서드는 ""InvalidStateError" DOMException" 예외를 발생시킵니다.

NavigateEvent는 "none", "intercepted", "committed", "scrolled", 또는 "finished" 중 하나인 인터셉션 상태를 가지며, 초기 값은 "none"입니다.

NavigateEvent네비게이션 핸들러 목록을 가지며, 이는 NavigationInterceptHandler 콜백의 리스트로, 초기에는 비어 있습니다.

NavigateEvent포커스 리셋 동작을 가지며, 이는 NavigationFocusReset 또는 null로, 초기 값은 null입니다.

NavigateEvent스크롤 동작을 가지며, 이는 NavigationScrollBehavior 또는 null로, 초기 값은 null입니다.

NavigateEvent중단 컨트롤러를 가지며, 이는 AbortController 또는 null로, 초기 값은 null입니다.

NavigateEvent클래식 히스토리 API 상태를 가지며, 이는 직렬화된 상태 또는 null입니다. 이 상태는 이벤트의 navigationType이 "push" 또는 "replace"인 경우에만 사용되며, 이벤트가 발생할 때 적절하게 설정됩니다.

navigationType, destination, canIntercept, userInitiated, hashChange, signal, formData, downloadRequest, info, 및 hasUAVisualTransition 속성은 초기화된 값을 반환해야 합니다.

intercept(options) 메서드 단계는 다음과 같습니다:

  1. 공유된 체크 수행this로 실행합니다.

  2. thiscanIntercept 속성이 false로 초기화된 경우, ""SecurityError" DOMException"을 발생시킵니다.

  3. this디스패치 플래그가 설정되지 않은 경우, ""InvalidStateError" DOMException"을 발생시킵니다.

  4. 단언합니다: this인터셉션 상태가 "none" 또는 "intercepted"인 경우입니다.

  5. this인터셉션 상태를 "intercepted"로 설정합니다.

  6. 만약 options["handler"]가 존재하는 경우, 리스트에 추가합니다 this네비게이션 핸들러 목록에 추가합니다.

  7. 만약 options["focusReset"]이 존재하는 경우, 다음을 실행합니다:

    1. this포커스 리셋 동작이 null이 아니며, options["focusReset"]과 동일하지 않은 경우, 사용자 에이전트는 콘솔에 경고를 보고하여 이전에 intercept() 호출 시 설정된 focusReset 옵션이 이 새로운 값으로 덮어쓰여졌음을 알리고, 이전 값을 무시할 수 있습니다.

    2. this포커스 리셋 동작options["focusReset"]으로 설정합니다.

  8. 만약 options["scroll"]이 존재하는 경우, 다음을 실행합니다:

    1. this스크롤 동작이 null이 아니며, options["scroll"]과 동일하지 않은 경우, 사용자 에이전트는 콘솔에 경고를 보고하여 이전에 intercept() 호출 시 설정된 scroll 옵션이 이 새로운 값으로 덮어쓰여졌음을 알리고, 이전 값을 무시할 수 있습니다.

    2. this스크롤 동작options["scroll"]으로 설정합니다.

scroll() 메서드 단계는 다음과 같습니다:

  1. 공유된 체크 수행this로 실행합니다.

  2. this인터셉션 상태가 "committed"가 아닌 경우, ""InvalidStateError" DOMException"을 발생시킵니다.

  3. 스크롤 동작 처리this로 실행합니다.

공유된 체크 수행NavigateEvent event에 대해 실행하려면:

  1. 만약 event관련 글로벌 객체관련된 Document완전히 활성화된 상태가 아니라면, ""InvalidStateError" DOMException"을 발생시킵니다.

  2. 만약 eventisTrusted 속성이 false로 초기화된 경우, ""SecurityError" DOMException"을 발생시킵니다.

  3. 만약 event취소 플래그가 설정된 경우, ""InvalidStateError" DOMException"을 발생시킵니다.

7.2.6.10.2 NavigationDestination 인터페이스
[Exposed=Window]
interface NavigationDestination {
  readonly attribute USVString url;
  readonly attribute DOMString key;
  readonly attribute DOMString id;
  readonly attribute long long index;
  readonly attribute boolean sameDocument;

  any getState();
};
event.destination.url

네비게이션할 URL입니다.

event.destination.key

이 네비게이션이 "traverse" 네비게이션인 경우, 목적지 NavigationHistoryEntrykey 속성 값입니다. 그렇지 않은 경우 빈 문자열입니다.

event.destination.id

이 네비게이션이 "traverse" 네비게이션인 경우, 목적지 NavigationHistoryEntryid 속성 값입니다. 그렇지 않은 경우 빈 문자열입니다.

event.destination.index

이 네비게이션이 "traverse" 네비게이션인 경우, 목적지 NavigationHistoryEntryindex 속성 값입니다. 그렇지 않은 경우 -1입니다.

event.destination.sameDocument

이 네비게이션이 현재 문서와 동일한 문서로의 네비게이션인지를 나타냅니다. 예를 들어, 프래그먼트 네비게이션이나 history.pushState() 네비게이션의 경우 true가 됩니다.

이 속성은 네비게이션의 원래 성격을 나타낸다는 점을 유의하세요. 만약 교차 문서 네비게이션이 navigateEvent.intercept() 메서드를 사용하여 동일 문서 네비게이션으로 변환되더라도 이 속성의 값은 변경되지 않습니다.

event.destination.getState()

"traverse" 네비게이션의 경우, 목적지 세션 기록 항목에 저장된 상태의 디직렬화 값을 반환합니다.

"push" 또는 "replace" 네비게이션의 경우, 이 네비게이션이 navigation.navigate() 메서드를 사용하여 시작되었다면 전달된 상태의 디직렬화 값을 반환하며, 그렇지 않으면 undefined를 반환합니다.

"reload" 네비게이션의 경우, 이 다시 로드가 navigation.reload() 메서드를 사용하여 시작되었다면 전달된 상태의 디직렬화 값을 반환하며, 그렇지 않으면 undefined를 반환합니다.

NavigationDestinationURLURL을 가집니다.

NavigationDestinationNavigationHistoryEntry 또는 null인 엔트리를 가집니다.

이것은 오직 NavigationDestination가 "traverse" 네비게이션과 일치하는 경우에만 null이 아닌 값을 가집니다.

NavigationDestination직렬화된 상태상태를 가집니다.

NavigationDestination는 boolean인 동일 문서 여부를 가집니다.


url 게터 단계는 thisURL직렬화된 상태로 반환하는 것입니다.

key 게터 단계는 다음과 같습니다:

  1. this엔트리가 null인 경우, 빈 문자열을 반환합니다.

  2. this엔트리key를 반환합니다.

id 게터 단계는 다음과 같습니다:

  1. this엔트리가 null인 경우, 빈 문자열을 반환합니다.

  2. this엔트리ID를 반환합니다.

index 게터 단계는 다음과 같습니다:

  1. this엔트리가 null인 경우, -1을 반환합니다.

  2. this엔트리index를 반환합니다.

sameDocument 게터 단계는 this동일 문서 여부를 반환하는 것입니다.

getState() 메서드 단계는 StructuredDeserializethisstate로 실행하는 것입니다.

표준의 다른 부분들은 이 섹션에 주어진 일련의 래퍼 알고리즘을 통해 navigate 이벤트를 발생시킵니다.

navigate 이벤트를 트래버스하여 발생시키기 위해 Navigation navigation과 주어진 세션 기록 항목 destinationSHE, 그리고 선택적으로 사용자 네비게이션 개입 userInvolvement (기본값 "없음")을 사용하여:

  1. navigation관련된 영역에서 NavigateEvent 를 주어 이벤트 생성의 결과로 event를 할당합니다.

  2. event클래식 역사 API 상태를 null로 설정합니다.

  3. navigation관련된 영역에서 새로 생성된 NavigationDestinationdestination을 할당합니다.

  4. destinationURLdestinationSHEURL로 설정합니다.

  5. destinationNHEnavigation항목 목록에 있는 NavigationHistoryEntry로 설정합니다. 해당 항목의 세션 기록 항목destinationSHE와 일치하거나 그러한 NavigationHistoryEntry가 존재하지 않는 경우 null로 설정합니다.

  6. destinationNHE가 null이 아닌 경우:

    1. destination항목destinationNHE로 설정합니다.

    2. destination상태destinationSHE네비게이션 API 상태로 설정합니다.

  7. 그 외의 경우,

    1. destination항목을 null로 설정합니다.

    2. destination상태StructuredSerializeForStorage(null)로 설정합니다.

  8. destinationSHE문서navigation관련된 글로벌 객체관련된 문서와 동일한 경우 destination동일 문서 여부를 true로 설정합니다. 그렇지 않은 경우 false로 설정합니다.

  9. 내부 navigate 이벤트 발생 알고리즘을 실행한 결과를 반환합니다. navigation, "트래버스", event, destination, userInvolvement, null, 그리고 null을 전달합니다.

push/replace/reload navigate 이벤트를 발생시키기 위해 Navigation navigation, 주어진 NavigationType navigationType, URL destinationURL, boolean isSameDocument, 선택적 사용자 네비게이션 개입 userInvolvement (기본값 "없음"), 선택적 항목 목록-또는-null formDataEntryList (기본값 null), 선택적 직렬화된 상태 navigationAPIState (기본값 StructuredSerializeForStorage(null)), 그리고 선택적 직렬화된 상태-또는-null classicHistoryAPIState (기본값 null)을 사용합니다:

  1. navigation관련된 영역에서 NavigateEvent를 주어 이벤트 생성의 결과로 event를 할당합니다.

  2. event클래식 역사 API 상태classicHistoryAPIState로 설정합니다.

  3. navigation관련된 영역에서 새로 생성된 NavigationDestinationdestination을 할당합니다.

  4. destinationURLdestinationURL로 설정합니다.

  5. destination항목을 null로 설정합니다.

  6. destination상태navigationAPIState로 설정합니다.

  7. destination동일 문서 여부isSameDocument로 설정합니다.

  8. 내부 navigate 이벤트 발생 알고리즘을 실행한 결과를 반환합니다. navigation, navigationType, event, destination, userInvolvement, formDataEntryList, 그리고 null을 전달합니다.

다운로드 요청 navigate 이벤트를 발생시키기 위해 Navigation navigation, 주어진 URL destinationURL, 사용자 네비게이션 개입 userInvolvement, 그리고 문자열 filename을 사용합니다:

  1. navigation관련된 영역에서 NavigateEvent를 주어 이벤트 생성의 결과로 event를 할당합니다.

  2. event클래식 역사 API 상태를 null로 설정합니다.

  3. navigation관련된 영역에서 새로 생성된 NavigationDestinationdestination을 할당합니다.

  4. destinationURLdestinationURL로 설정합니다.

  5. destination항목을 null로 설정합니다.

  6. destination상태StructuredSerializeForStorage(null)로 설정합니다.

  7. destination동일 문서 여부를 false로 설정합니다.

  8. 내부 navigate 이벤트 발생 알고리즘을 실행한 결과를 반환합니다. navigation, "push", event, destination, userInvolvement, null, 그리고 filename을 전달합니다.

내부 navigate 이벤트 발생 알고리즘Navigation navigation, NavigationType navigationType, NavigateEvent event, NavigationDestination destination, 사용자 네비게이션 개입 userInvolvement, 항목 목록-또는-null formDataEntryList, 그리고 문자열-또는-null downloadRequestFilename을 사용하여 다음 단계를 포함합니다:

  1. 만약 navigation엔트리 및 이벤트 비활성화 상태라면:

    1. 확인: navigation진행 중인 API 메서드 트래커가 null이어야 합니다.

    2. 확인: navigation비트래버스 API 메서드 트래커가 null이어야 합니다.

    3. 확인: navigation트래버스 API 메서드 트래커 목록이 비어 있어야 합니다.

    4. True를 반환합니다.

    이러한 확인은 traverseTo(), back(), 그리고 forward() 가 엔트리 및 이벤트가 비활성화된 경우에는 즉시 실패하기 때문에 유효합니다(탐색할 엔트리가 없으므로). 만약 시작점이 navigate() 또는 reload() 라면, 우리는 애초에 비트래버스 API 메서드 트래커 설정을 피했습니다.

  2. destinationKey를 null로 설정합니다.

  3. 만약 destination엔트리가 null이 아니면, destinationKeydestination엔트리로 설정합니다.

  4. 확인: destinationKey가 빈 문자열이 아님을 확인합니다.

  5. 예정된 API 메서드 트래커를 진행 중으로 승격 합니다, navigationdestinationKey를 인자로 전달합니다.

  6. apiMethodTrackernavigation진행 중인 API 메서드 트래커로 설정합니다.

  7. navigablenavigation관련된 전역 객체navigable로 설정합니다.

  8. documentnavigation관련된 전역 객체관련된 문서로 설정합니다.

  9. 만약 documentURL을 재작성할 수 있고 destinationURL로 설정될 수 있다면, 그리고 destination동일 문서가 true이거나 navigationType이 "traverse"가 아니라면, event canIntercept를 true로 초기화합니다. 그렇지 않으면 false로 초기화합니다.

  10. 다음 조건들 중 하나라도 true라면:

    그렇다면 event 취소 가능 여부를 true로 초기화합니다. 그렇지 않으면 false로 초기화합니다.

  11. event 유형을 "navigate"로 초기화합니다.

  12. event navigationTypenavigationType으로 초기화합니다.

  13. event 목적지destination으로 초기화합니다.

  14. event 다운로드 요청downloadRequestFilename으로 초기화합니다.

  15. 만약 apiMethodTracker가 null이 아니라면, eventinfoapiMethodTracker정보로 초기화합니다. 그렇지 않다면 undefined로 초기화합니다.

    이 시점에서 apiMethodTracker정보는 더 이상 필요하지 않으며, 네비게이션 API 메서드 트래커의 수명 동안 이를 유지하는 대신 null로 설정할 수 있습니다.

  16. 만약 사용자 에이전트가 document최신 항목의 캐시된 렌더링 상태를 표시하는 시각적 전환을 수행한 경우, event hasUAVisualTransition을 true로 초기화합니다. 그렇지 않다면 false로 초기화합니다.

  17. event중단 컨트롤러navigation관련된 영역에서 생성된 새로운 AbortController로 설정합니다.

  18. event 신호event중단 컨트롤러신호로 초기화합니다.

  19. currentURLdocumentURL로 설정합니다.

  20. 만약 다음 조건들이 모두 true라면:

    그렇다면 event hashChange를 true로 초기화합니다. 그렇지 않다면 false로 초기화합니다.

    첫 번째 조건은 hashChange프래그먼트 탐색에 대해 true로 설정되지만, history.pushState(undefined, "", "#fragment")와 같은 경우에는 false로 설정됩니다.

  21. 만약 userInvolvement이 " none"이 아니라면, eventuserInitiated를 true로 초기화합니다. 그렇지 않다면 false로 초기화합니다.

  22. 만약 formDataEntryList가 null이 아니라면, eventformDatanavigation관련된 영역에서 생성된 새로운 FormDataformDataEntryList와 연결하여 초기화합니다. 그렇지 않다면 null로 초기화합니다.

  23. 확인: navigation진행 중인 navigate 이벤트가 null임을 확인합니다.

  24. navigation진행 중인 navigate 이벤트event로 설정합니다.

  25. navigation진행 중인 탐색 동안 포커스 변경 여부를 false로 설정합니다.

  26. navigation진행 중인 탐색 동안 정상 스크롤 복원 억제 여부를 false로 설정합니다.

  27. dispatchResult이벤트 디스패치의 결과로 설정합니다. 이 때, navigation에서 event를 디스패치합니다.

  28. 만약 dispatchResult가 false라면:

    1. 만약 navigationType이 " traverse"이라면, navigation관련된 전역 객체에 대해 히스토리 액션 사용자 활성화 소비를 수행합니다.

    2. 만약 event중단 컨트롤러신호중단되지 않은 경우, navigation에 대해 진행 중인 탐색 중단을 수행합니다.

    3. false를 반환합니다.

  29. endResultIsSameDocumentevent가로채기 상태가 "none"이 아니거나, event 목적지동일 문서 여부가 true인 경우, true로 설정합니다.

  30. navigation관련된 설정 객체를 사용하여 스크립트를 실행할 준비를 합니다.

    이 작업은 자바스크립트 실행 컨텍스트 스택URL 및 히스토리 업데이트 단계의 결과로 발생할 수 있는 currententrychange 이벤트 핸들러가 실행된 직후 비어 있는 상태가 되는 것을 방지하기 위해 수행됩니다. 스택이 이 시점에서 비어 있다면, 즉시 마이크로태스크 체크포인트를 수행하여, 다양한 프로미스 이행 핸들러가 이벤트 핸들러와 섞여 실행되며, navigateEvent.intercept()에 전달된 핸들러보다 먼저 실행될 수 있습니다. 이는 탐색이 사용자에 의해 발생하는 경우(예: 탐색이 사용자가 시작한 경우)와 자바스크립트 API 호출에 의해 발생하는 경우 (예: 탐색이 자바스크립트에 의해 발생한 경우) 간의 프로미스 핸들러 순서가 달라지게 되어 바람직하지 않습니다.

    이 단계에서 불필요한 자바스크립트 실행 컨텍스트를 스택에 추가함으로써, 마이크로태스크 체크포인트를 수행 알고리즘을 나중까지 억제하여, 항상 currententrychange 이벤트 핸들러, intercept() 핸들러, 그리고 프로미스 핸들러의 순서로 실행되도록 보장합니다.

  31. 만약 event가로채기 상태가 "none"이 아니라면:

    1. event가로채기 상태를 "committed"로 설정합니다.

    2. fromNHEnavigation현재 엔트리로 설정합니다.

    3. 확인: fromNHE이 null이 아님을 확인합니다.

    4. navigation전환navigation관련된 영역에서 생성된 새로운 NavigationTransition으로 설정합니다. 이 때, 탐색 유형navigationType으로, from 엔트리fromNHE로, 완료된 프로미스navigation관련된 영역에서 생성된 새로운 프로미스로 설정합니다.

    5. 처리된 것으로 표시 navigation전환완료된 프로미스를.

      이 작업이 수행되는 이유는 다른 완료된 프로미스에 대한 논의를 참조하세요.

    6. 만약 navigationType이 " traverse"라면, navigation진행 중인 탐색 동안 정상 스크롤 복원 억제 여부를 true로 설정합니다.

      만약 event스크롤 동작이 " 전환 후"로 설정된 경우, 스크롤 복원은 관련 NavigateEvent을 완료하는 동안 수행됩니다. 그렇지 않다면 스크롤 복원은 수행되지 않습니다. 즉, intercept()로 가로채진 탐색은 정상적인 스크롤 복원 과정을 거치지 않으며, 이러한 탐색의 스크롤 복원은 웹 개발자가 수동으로 수행하거나 전환 후에 수행됩니다.

    7. 만약 navigationType이 " push" 또는 " replace"라면, documentevent 목적지URL을 사용하여 URL 및 히스토리 업데이트 단계를 수행합니다. 이 때 직렬화된 데이터event클래식 역사 API 상태로, 역사 처리navigationType으로 설정됩니다.

      만약 navigationType이 " reload"라면, 우리는 reload를 "동일 문서 재로드"로 변환하고 있으며, URL 및 히스토리 업데이트 단계는 적절하지 않습니다. 네비게이션 API와 관련된 작업은 여전히 수행되며, 예를 들어 활성 세션 히스토리 엔트리네비게이션 API 상태가 업데이트되거나, 이 작업이 navigation.reload() 호출로 인해 발생한 경우 진행 중인 탐색 추적과 같은 작업이 수행됩니다.

      만약 navigationType이 " traverse"라면, 이 이벤트 발사는 탐색 과정의 일부로 발생하고 있으며, 이 과정에서 적절한 세션 히스토리 엔트리 업데이트가 수행될 것입니다.

  32. 만약 endResultIsSameDocument가 true라면:

    1. promisesList를 빈 리스트로 설정합니다.

    2. 각각의 handlerevent네비게이션 핸들러 목록에서:

      1. 추가합니다, 콜백 함수 호출의 결과를, 빈 인수 목록을 사용하여 promisesList에 추가합니다.

    3. 만약 promisesList크기가 0이라면, promisesList를 « undefined로 해결된 프로미스 »로 설정합니다.

      여기서 모든 프로미스 대기가 0개의 프로미스를 받았을 때와 1개 이상의 프로미스를 받았을 때 성공 및 실패 단계를 예약하는 방식 사이에 미묘한 타이밍 차이가 있습니다. 대부분의 경우 모든 프로미스 대기의 사용에 있어서는 중요하지 않지만, 이 API의 경우에는 너무 많은 이벤트와 프로미스 핸들러가 거의 동시에 실행될 수 있어, 차이가 쉽게 관찰될 수 있습니다. 이는 이벤트/프로미스 핸들러 순서에 영향을 미칠 수 있습니다. (예를 들어, navigatesuccess / navigateerror, currententrychange, dispose, apiMethodTracker의 프로미스, 그리고 navigation.transition.finished 프로미스와 같은 이벤트 및 프로미스를 포함합니다.)

    4. 모든 promisesList를 대기하고, 다음과 같은 성공 단계를 수행합니다:

      1. 만약 event관련된 전역 객체완전히 활성화되지 않았다면, 이 단계를 중단합니다.

      2. 만약 event중단 컨트롤러신호중단되었다면, 이 단계를 중단합니다.

      3. 확인: eventnavigation진행 중인 navigate 이벤트와 동일함을 확인합니다.

      4. navigation진행 중인 navigate 이벤트를 null로 설정합니다.

      5. event을 완료하고, true를 인자로 전달합니다.

      6. 이벤트를 발동하고, 이름을 navigatesuccess로 설정합니다. navigation에서 발동됩니다.

      7. 만약 navigation전환이 null이 아니라면, navigation전환완료된 프로미스를 undefined로 해결합니다.

      8. navigation전환을 null로 설정합니다.

      9. 만약 apiMethodTracker가 null이 아니라면, 완료된 프로미스 해결apiMethodTracker에 대해 수행합니다.

      다음과 같은 실패 단계를, rejectionReason을 인자로 하여 수행합니다:

      1. 만약 event관련된 전역 객체완전히 활성화되지 않았다면, 이 단계를 중단합니다.

      2. 만약 event중단 컨트롤러신호중단되었다면, 이 단계를 중단합니다.

      3. 확인: eventnavigation진행 중인 navigate 이벤트와 동일함을 확인합니다.

      4. navigation진행 중인 navigate 이벤트를 null로 설정합니다.

      5. event를 완료하고, false를 인자로 전달합니다.

      6. errorInfo rejectionReason에서 오류 정보를 추출한 결과로 설정합니다.

      7. 이벤트를 발동하고, 이름을 navigateerror로 설정합니다. navigation에서 발동되며, 추가 속성은 errorInfo에 따라 초기화됩니다.

      8. 만약 navigation전환이 null이 아니라면, navigation전환완료된 프로미스rejectionReason으로 거부합니다.

      9. navigation전환을 null로 설정합니다.

      10. 만약 apiMethodTracker가 null이 아니라면, 완료된 프로미스 거부apiMethodTracker에 대해 rejectionReason으로 수행합니다.

  33. 그렇지 않다면, apiMethodTracker가 null이 아니면, API 메서드 트래커 정리를 수행합니다.

  34. 스크립트 실행 후 정리를 수행하며, navigation관련된 설정 객체를 사용합니다.

    이전 메모에 따라, 이는 잠재적인 프로미스 핸들러 마이크로태스크 억제를 중지시켜, 이를 이 시점 이후에 실행하게 합니다.

  35. 만약 event가로채기 상태가 "none"이라면, true를 반환합니다.

  36. false를 반환합니다.

navigateEvent.intercept()를 호출하여, 웹 개발자는 동일 문서 내 네비게이션의 일반적인 스크롤 및 포커스 동작을 억제하고, 대신 나중에 교차 문서 네비게이션과 같은 동작을 호출할 수 있습니다. 이 섹션의 알고리즘은 나중에 적절한 시점에 호출됩니다.

부울 didFulfill이 주어진 NavigateEvent event완료하려면:

  1. 단언: event인터셉션 상태가 "intercepted" 또는 "finished"가 아님.

  2. 만약 event인터셉션 상태가 "none"이라면, 반환합니다.

  3. 포커스를 잠재적으로 리셋 합니다 event를 기반으로.

  4. 만약 didFulfill이 true라면, 스크롤 동작을 잠재적으로 처리 합니다 event를 기반으로.

  5. event인터셉션 상태를 "finished"로 설정합니다.

포커스를 잠재적으로 리셋하려면, NavigateEvent event을 기반으로:

  1. 단언: event인터셉션 상태가 "committed" 또는 "scrolled"임.

  2. navigationevent관련 글로벌 객체네비게이션 API로 설정합니다.

  3. focusChangednavigation진행 중인 네비게이션 동안 포커스 변경으로 설정합니다.

  4. navigation진행 중인 네비게이션 동안 포커스 변경을 false로 설정합니다.

  5. 만약 focusChanged이 true라면, 반환합니다.

  6. 만약 event포커스 리셋 동작이 "manual"이라면, 반환합니다.

    만약 null로 설정되었다면, 우리는 이를 "전환 후"로 간주하고, 계속 진행합니다.

  7. documentevent관련 글로벌 객체연결된 Document로 설정합니다.

  8. focusTargetdocument자동 포커스 대리자로 설정합니다.

  9. 만약 focusTarget이 null이라면, focusTargetdocument바디 요소로 설정합니다.

  10. 만약 focusTarget이 null이라면, focusTargetdocument문서 요소로 설정합니다.

  11. document뷰포트fallback target으로 사용하여 포커싱 단계를 실행합니다.

  12. 순차 포커스 네비게이션 시작점focusTarget으로 이동합니다.

잠재적으로 스크롤 동작을 처리하려면, NavigateEvent event을 기반으로:

  1. 단언: event인터셉션 상태가 "committed" 또는 "scrolled"임.

  2. 만약 event인터셉션 상태가 "scrolled"이라면, 반환합니다.

  3. 만약 event스크롤 동작이 "manual"이라면, 반환합니다.

    만약 null로 설정되었다면, 우리는 이를 "전환 후"로 간주하고, 계속 진행합니다.

  4. 스크롤 동작 처리event을 기반으로 수행합니다.

스크롤 동작 처리를 수행하려면, NavigateEvent event을 기반으로:

  1. 단언: event인터셉션 상태가 "committed"임.

  2. event인터셉션 상태를 "scrolled"로 설정합니다.

  3. 만약 eventnavigationType이 "traverse" 또는 "reload"로 초기화되었다면, 스크롤 위치 데이터 복원event관련 글로벌 객체네비게이션 가능활성 세션 기록 항목을 기반으로 수행합니다.

  4. 그 외에는:

    1. documentevent관련 글로벌 객체연결된 Document로 설정합니다.

    2. 만약 document지정된 부분이 null이라면, 문서의 시작 부분으로 스크롤을 수행합니다 document을 기반으로. [CSSOMVIEW]

    3. 그 외에는, 프래그먼트로 스크롤document을 기반으로 수행합니다.

NavigateEvent 인터페이스는 그 복잡성 때문에 자체 전용 섹션이 있습니다.

7.2.7.1 NavigationCurrentEntryChangeEvent 인터페이스
[Exposed=Window]
interface NavigationCurrentEntryChangeEvent : Event {
  constructor(DOMString type, NavigationCurrentEntryChangeEventInit eventInitDict);

  readonly attribute NavigationType? navigationType;
  readonly attribute NavigationHistoryEntry from;
};

dictionary NavigationCurrentEntryChangeEventInit : EventInit {
  NavigationType? navigationType = null;
  required NavigationHistoryEntry from;
};
event.navigationType

현재 항목이 변경된 원인이 된 탐색 유형을 반환하거나, 변경이 navigation.updateCurrentEntry()로 인한 경우 null을 반환합니다.

event.from

현재 항목이 변경되기 전의 navigation.currentEntry의 이전 값을 반환합니다.

만약 navigationType 이 null이거나 "reload"인 경우, 이 값은 navigation.currentEntry와 동일합니다. 이 경우, 우리는 새 항목으로 이동하거나 현재 항목을 교체하지 않았더라도 이벤트는 항목의 내용이 변경되었음을 의미합니다.

navigationTypefrom 속성은 초기화된 값을 반환해야 합니다.

7.2.7.2 PopStateEvent 인터페이스

PopStateEvent/PopStateEvent

모든 현재 엔진에서 지원됩니다.

Firefox11+Safari6+Chrome16+
Opera?Edge79+
Edge (Legacy)14+Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

PopStateEvent

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari6+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface PopStateEvent : Event {
  constructor(DOMString type, optional PopStateEventInit eventInitDict = {});

  readonly attribute any state;
  readonly attribute boolean hasUAVisualTransition;
};

dictionary PopStateEventInit : EventInit {
  any state = null;
  boolean hasUAVisualTransition = false;
};
event.state

PopStateEvent/state

모든 현재 엔진에서 지원됩니다.

Firefox4+Safari6+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

pushState()replaceState()에 제공된 정보의 복사본을 반환합니다.

event.hasUAVisualTransition

이 탐색에 대해 사용자 에이전트가 시각적 전환을 수행했는지 여부를 반환합니다. true인 경우, 작성자가 탐색 후 상태로 DOM을 동기식으로 업데이트하면 최고의 사용자 경험을 얻을 수 있습니다.

state 속성은 초기화된 값을 반환해야 합니다. 이 속성은 이벤트의 컨텍스트 정보를 나타내며, 만약 상태가 문서의 초기 상태를 나타내는 경우 null을 반환합니다.

hasUAVisualTransition 속성은 초기화된 값을 반환해야 합니다.

7.2.7.3 HashChangeEvent 인터페이스

HashChangeEvent/HashChangeEvent

모든 현재 엔진에서 지원됩니다.

Firefox11+Safari6+Chrome16+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HashChangeEvent

모든 현재 엔진에서 지원됩니다.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Exposed=Window]
interface HashChangeEvent : Event {
  constructor(DOMString type, optional HashChangeEventInit eventInitDict = {});

  readonly attribute USVString oldURL;
  readonly attribute USVString newURL;
};

dictionary HashChangeEventInit : EventInit {
  USVString oldURL = "";
  USVString newURL = "";
};
event.oldURL

HashChangeEvent/oldURL

모든 현재 엔진에서 지원됩니다.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이전에 현재였던 세션 기록 항목의 URL을 반환합니다.

event.newURL

HashChangeEvent/newURL

모든 현재 엔진에서 지원됩니다.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

이제 현재인 세션 기록 항목의 URL을 반환합니다.

oldURL 속성은 초기화된 값을 반환해야 합니다. 이 속성은 탐색한 세션 기록 항목의 URL을 나타내는 이벤트의 컨텍스트 정보를 나타냅니다.

newURL 속성은 초기화된 값을 반환해야 합니다. 이 속성은 탐색된 세션 기록 항목의 URL을 나타내는 이벤트의 컨텍스트 정보를 나타냅니다.

7.2.7.4 PageSwapEvent 인터페이스
[Exposed=Window]
interface PageSwapEvent : Event {
  constructor(DOMString type, optional PageSwapEventInit eventInitDict = {});
  readonly attribute NavigationActivation? activation;
  readonly attribute ViewTransition? viewTransition;
};

dictionary PageSwapEventInit : EventInit {
  NavigationActivation? activation = null;
  ViewTransition? viewTransition = null;
};
event.activation

NavigationActivation 객체는 문서 간 탐색의 목적지와 유형을 나타냅니다. 이 객체는 교차 출처 탐색에 대해서는 null이 됩니다.

event.activation.entry

NavigationHistoryEntry 객체로, 활성화되기 직전의 문서를 나타냅니다.

event.activation.from

이 값은 이벤트가 발생할 당시 navigation.currentEntry 속성의 값과 동일한 NavigationHistoryEntry 객체입니다.

event.activation.navigationType

페이지 전환을 초래할 탐색의 유형을 나타내는 "push", "replace", "reload", 또는 "traverse" 중 하나입니다.

event.viewTransition

이벤트가 발생할 때 활성 상태인 경우, 문서 간 보기 전환을 나타내는 ViewTransition 객체를 반환합니다. 그렇지 않으면 null을 반환합니다.

activation 속성과 viewTransition 속성은 초기화된 값을 반환해야 합니다.

7.2.7.5 PageRevealEvent 인터페이스
[Exposed=Window]
interface PageRevealEvent : Event {
  constructor(DOMString type, optional PageRevealEventInit eventInitDict = {});
  readonly attribute ViewTransition? viewTransition;
};

dictionary PageRevealEventInit : EventInit {
  ViewTransition? viewTransition = null;
};
event.viewTransition

이벤트가 발생할 때 활성 상태인 경우, 문서 간 보기 전환을 나타내는 ViewTransition 객체를 반환합니다. 그렇지 않으면 null을 반환합니다.

viewTransition 속성은 초기화된 값을 반환해야 합니다.

7.2.7.6 PageTransitionEvent 인터페이스

PageTransitionEvent/PageTransitionEvent

모든 현재 엔진에서 지원됩니다.

Firefox11+Safari6+Chrome16+
Opera?Edge79+
Edge (Legacy)?Internet Explorer지원되지 않음
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

PageTransitionEvent

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari5+Chrome4+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
[Exposed=Window]
interface PageTransitionEvent : Event {
  constructor(DOMString type, optional PageTransitionEventInit eventInitDict = {});

  readonly attribute boolean persisted;
};

dictionary PageTransitionEventInit : EventInit {
  boolean persisted = false;
};
event.persisted

PageTransitionEvent/persisted

모든 현재 엔진에서 지원됩니다.

Firefox11+Safari5+Chrome4+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android?

pageshow 이벤트의 경우, 페이지가 새로 로드되고 있는 경우 false를 반환하며(load 이벤트가 발생할 예정임), 그렇지 않으면 true를 반환합니다.

pagehide 이벤트의 경우, 페이지가 마지막으로 사라지고 있는 경우 false를 반환합니다. 그렇지 않으면 true를 반환하며, 이 경우 사용자가 이 페이지로 다시 탐색할 때 페이지가 재사용될 수 있음을 의미합니다(만약 문서salvageable 상태가 true로 유지되는 경우).

페이지를 재사용할 수 없게 만드는 요인들에는 다음이 포함됩니다:

persisted 속성은 초기화된 값을 반환해야 합니다. 이 속성은 이벤트의 컨텍스트 정보를 나타냅니다.

페이지 전환 이벤트eventName으로 Window 객체에서 발생시키려면, window에서 이벤트를 발생시키고, PageTransitionEvent 객체를 사용하며, persisted 속성을 persisted로 초기화하고, cancelable 속성을 true로 초기화하며, bubbles 속성을 true로 초기화하고, 레거시 타겟 오버라이드 플래그를 설정합니다.

cancelablebubbles 속성의 값은 역사적인 이유로 true로 설정되어 있지만, 이벤트를 취소해도 아무런 영향이 없고, Window 객체를 넘어서 전파되는 것도 불가능하므로 의미가 없습니다.

7.2.7.7 BeforeUnloadEvent 인터페이스

BeforeUnloadEvent

모든 현재 엔진에서 지원됩니다.

Firefox1.5+Safari7+Chrome30+
Opera?Edge79+
Edge (Legacy)?Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet3.0+Opera Android?
[Exposed=Window]
interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};

BeforeUnloadEvent에 특화된 초기화 메서드는 없습니다.

BeforeUnloadEvent 인터페이스는 이벤트를 취소하는 것뿐만 아니라 returnValue 속성을 빈 문자열이 아닌 값으로 설정하여 언로드가 취소되었는지 확인할 수 있도록 하는 레거시 인터페이스입니다. 작성자는 preventDefault() 메서드 또는 다른 이벤트 취소 수단을 사용해야 하며, returnValue를 사용하는 것은 피해야 합니다.

returnValue 속성은 언로드가 취소되었는지 확인하는 과정을 제어합니다. 이벤트가 생성될 때 이 속성은 빈 문자열로 설정되어야 합니다. 이 속성을 가져올 때는 마지막으로 설정된 값을 반환해야 하며, 설정할 때는 새 값으로 설정되어야 합니다.

이 속성은 역사적인 이유로 DOMString입니다. 빈 문자열이 아닌 값은 모두 사용자에게 확인을 요청하는 것으로 처리됩니다.

7.2.8 NotRestoredReasons 인터페이스

[Exposed=Window]
interface NotRestoredReasonDetails {
  readonly attribute DOMString reason;
  [Default] object toJSON();
};

[Exposed=Window]
interface NotRestoredReasons {
  readonly attribute DOMString? src;
  readonly attribute DOMString? id;
  readonly attribute DOMString? name;
  readonly attribute DOMString? url;
  readonly attribute FrozenArray<NotRestoredReasonDetails>? reasons;
  readonly attribute FrozenArray<NotRestoredReasons>? children;
  [Default] object toJSON();
};
notRestoredReasonDetails.reason

문서가 앞뒤 캐시에서 제공되지 못하게 한 이유를 설명하는 문자열을 반환합니다. 가능한 문자열 값에 대한 정의는 bfcache 차단 세부 정보에서 확인할 수 있습니다.

notRestoredReasons.src

문서의 탐색 가능 노드컨테이너에서 src 속성을 반환합니다(iframe 요소인 경우). 이 속성이 설정되지 않았거나 iframe 요소가 아닌 경우 null일 수 있습니다.

notRestoredReasons.id

문서의 탐색 가능 노드컨테이너에서 id 속성을 반환합니다(iframe 요소인 경우). 이 속성이 설정되지 않았거나 iframe 요소가 아닌 경우 null일 수 있습니다.

notRestoredReasons.name

문서의 탐색 가능 노드컨테이너에서 name 속성을 반환합니다(iframe 요소인 경우). 이 속성이 설정되지 않았거나 iframe 요소가 아닌 경우 null일 수 있습니다.

notRestoredReasons.url

문서의 URL을 반환합니다. 문서가 교차 출처 iframe에 있는 경우 null을 반환할 수 있습니다. 이것은 src외에 보고되며, iframe이 초기 src 설정 이후로 탐색된 경우가 있기 때문입니다.

notRestoredReasons.reasons

문서의 NotRestoredReasonDetails 배열을 반환합니다. 문서가 교차 출처 iframe에 있는 경우 이는 null일 수 있습니다.

notRestoredReasons.children

문서의 하위 항목에 대한 NotRestoredReasons 배열을 반환합니다. 문서가 교차 출처 iframe에 있는 경우 이는 null일 수 있습니다.

NotRestoredReasonDetails 개체는 지원 구조체, 복원되지 않은 이유 세부 정보 또는 null을 가집니다(초기 값은 null).

reason getter 단계는 this지원 구조체reason을 반환합니다.

NotRestoredReasonDetails 개체를 생성하려면 복원되지 않은 이유 세부 정보 backingStructrealm realm이 필요합니다:

  1. notRestoredReasonDetails를 새로운 NotRestoredReasonDetails 개체로 realm에서 생성합니다.

  2. notRestoredReasonDetails지원 구조체backingStruct로 설정합니다.

  3. notRestoredReasonDetails를 반환합니다.

복원되지 않은 이유 세부 정보는 다음 구조체 항목으로 구성된 구조체입니다:

reason은 페이지가 앞뒤 캐시에서 복원되지 못하게 한 이유를 나타내는 문자열입니다. 문자열은 다음 중 하나일 수 있습니다:

"fetch"
이 문서가 언로드되는 동안 Document에 의해 시작된 fetch가 아직 진행 중이었으며 취소되어 페이지가 안정적인 상태에 있지 않았기 때문에 앞뒤 캐시에 저장되지 않았습니다.
"navigation-failure"
이 문서를 생성한 원래 탐색이 오류가 발생했으므로 앞뒤 캐시에 오류 문서를 저장하는 것이 방지되었습니다.
"parser-aborted"
이 문서가 초기 HTML 구문 분석을 완료하지 않았기 때문에 미완성 문서를 앞뒤 캐시에 저장하는 것이 방지되었습니다.
"websocket"
언로드되는 동안 열려 있던 WebSocket 연결이 종료되어 페이지가 안정적인 상태에 있지 않았기 때문에 앞뒤 캐시에 저장되지 않았습니다. [WEBSOCKETS]
"lock"
언로드되는 동안 보유된 잠금잠금 요청이 종료되어 페이지가 안정적인 상태에 있지 않았기 때문에 앞뒤 캐시에 저장되지 않았습니다. [WEBLOCKS]
"masked"
이 문서에는 교차 출처 iframe에 있는 자식이 있으며, 이들이 앞뒤 캐시를 방지했거나, 이 문서가 사용자 에이전트별 이유로 인해 앞뒤 캐시되지 못했습니다.

NotRestoredReasons 개체는 지원 구조체, 복원되지 않은 이유 또는 null을 가집니다(초기 값은 null).

NotRestoredReasons 개체는 reasons 배열을 가집니다. 이 배열은 FrozenArray<NotRestoredReasonDetails> 또는 null일 수 있으며, 초기 값은 null입니다.

NotRestoredReasons 개체는 children 배열을 가집니다. 이 배열은 FrozenArray<NotRestoredReasons> 또는 null일 수 있으며, 초기 값은 null입니다.

src getter 단계는 this지원 구조체src을 반환하는 것입니다.

id getter 단계는 this지원 구조체id를 반환하는 것입니다.

name getter 단계는 this지원 구조체name을 반환하는 것입니다.

url getter 단계는 다음과 같습니다:

  1. this지원 구조체URL이 null인 경우, null을 반환합니다.

  2. this지원 구조체URL직렬화하여 반환합니다.

reasons getter 단계는 thisreasons 배열을 반환하는 것입니다.

children getter 단계는 thischildren 배열을 반환하는 것입니다.

NotRestoredReasons 개체를 생성하려면 복원되지 않은 이유 backingStructrealm realm이 필요합니다:

  1. notRestoredReasons를 새로운 NotRestoredReasons 개체로 realm에서 생성합니다.

  2. notRestoredReasons지원 구조체backingStruct로 설정합니다.

  3. backingStructreasons가 null인 경우, notRestoredReasonsreasons 배열을 null로 설정합니다.

  4. 그렇지 않은 경우:

    1. reasonsArray를 빈 리스트로 설정합니다.

    2. reason에 대해 backingStructreasons를 반복합니다:

      1. NotRestoredReasonDetails 개체reasonrealm을 기준으로 생성하고, 이를 reasonsArray추가합니다.

    3. notRestoredReasonsreasons 배열고정된 배열을 생성하여 reasonsArray로 설정합니다.

  5. backingStructchildren가 null인 경우, notRestoredReasonschildren 배열을 null로 설정합니다.

  6. 그렇지 않은 경우:

    1. childrenArray를 빈 리스트로 설정합니다.

    2. child에 대해 backingStructchildren를 반복합니다:

      1. NotRestoredReasons 개체childrealm을 기준으로 생성하고, 이를 childrenArray추가합니다.

    3. notRestoredReasonschildren 배열고정된 배열을 생성하여 childrenArray로 설정합니다.

  7. notRestoredReasons을 반환합니다.

복원되지 않은 이유는 다음 구조체 항목으로 구성된 구조체입니다:

Document의 복원되지 않은 이유탐색 가능 노드활성 세션 히스토리 항목문서 상태복원되지 않은 이유이며, Document탐색 가능 노드최상위 탐색 가능 항목일 경우에만 존재하며; 그렇지 않으면 null입니다.

7.3 문서 시퀀스의 인프라스트럭처

이 표준에는 문서 시퀀스를 그룹화하기 위한 여러 관련 개념이 포함되어 있습니다. 간단한 비규범적 요약:

이 표준의 대부분은 탐색 가능 항목의 언어로 작업하지만, 특정 API는 탐색 컨텍스트 전환의 존재를 드러내며, 따라서 표준의 일부는 탐색 컨텍스트를 기준으로 작업해야 합니다.

탐색 가능 항목활성 세션 기록 항목을 통해 사용자에게 문서를 제공합니다. 각 탐색 가능 항목에는 다음이 포함됩니다:

현재 세션 기록 항목활성 세션 기록 항목은 일반적으로 동일하지만, 다음과 같은 경우 동기화되지 않을 수 있습니다:


탐색 가능 항목활성 문서활성 세션 기록 항목문서입니다.

이 값은 탐색 가능 항목의 최상위 탐색 가능 항목세션 기록 탐색 큐 내에서 안전하게 읽을 수 있습니다. 탐색 가능 항목활성 세션 기록 항목이 동기적으로 변경될 수 있지만, 새로운 항목은 항상 동일한 문서를 가질 것입니다.

탐색 가능 항목활성 탐색 컨텍스트활성 문서탐색 컨텍스트입니다. 이 탐색 가능 항목탐색 가능한 탐색 항목인 경우, 활성 탐색 컨텍스트최상위 탐색 컨텍스트가 됩니다.

탐색 가능 항목활성 WindowProxy활성 탐색 컨텍스트에 연결된 WindowProxy입니다.

탐색 가능 항목활성 윈도우활성 WindowProxy[[Window]]입니다.

이 값은 항상 탐색 가능 항목의 활성 문서관련 글로벌 객체와 동일합니다. 이는 활성화 알고리즘에 의해 동기화됩니다.

탐색 가능대상 이름활성 세션 기록 항목문서 상태탐색 가능한 대상 이름입니다.


노드 node노드 탐색 가능을 가져오려면, node노드 문서활성화된 문서탐색 가능을 반환하거나, 해당 탐색 가능이 없으면 null을 반환합니다.


탐색 가능 navigable초기화하려면, 문서 상태 documentState와 선택적으로 탐색 가능-또는-null parent (기본값은 null)를 제공합니다.

  1. 단언: documentState문서가 null이 아님을 확인합니다.

  2. entry를 새 세션 기록 항목으로 설정하고, 다음을 포함합니다:

    URL
    documentState문서URL
    문서 상태
    documentState

    이 알고리즘의 호출자는 entry단계를 초기화할 책임이 있습니다. 이 항목은 초기화될 때까지 "대기 중"으로 유지됩니다.

  3. navigable현재 세션 기록 항목entry로 설정합니다.

  4. navigable활성 세션 기록 항목entry로 설정합니다.

  5. navigable부모parent로 설정합니다.

7.3.1.1 탐색 가능한 탐색 항목

탐색 가능한 탐색 항목탐색 가능 항목으로, 자신과 자손 탐색 가능 항목들에 대해 현재 세션 기록 항목활성 세션 기록 항목으로 지정할 세션 기록 항목을 제어하는 역할을 합니다.

탐색 가능 항목의 속성 외에도, 탐색 가능한 탐색 항목은 다음과 같은 속성을 가집니다:

특정 탐색 가능 항목탐색 가능한 탐색 항목을 가져오기 위해:

  1. navigableinputNavigable로 설정합니다.

  2. navigable탐색 가능한 탐색 항목이 아닐 때마다, navigablenavigable부모로 설정합니다.

  3. navigable을 반환합니다.

7.3.1.2 최상위 탐색 가능 항목

최상위 탐색 가능 항목탐색 가능한 탐색 항목으로, 부모가 null인 경우를 말합니다.

현재, 모든 탐색 가능한 탐색 항목들최상위 탐색 가능 항목들입니다. 미래의 제안들은 비-최상위 탐색 가능 항목들을 도입하는 것을 상정하고 있습니다.

사용자 에이전트는 최상위 탐색 가능 항목 집합 (즉, 집합으로서의 최상위 탐색 가능 항목들)을 가지고 있습니다. 이는 보통 브라우저 창이나 탭의 형태로 사용자에게 제공됩니다.

특정 탐색 가능 항목최상위 탐색 가능 항목을 가져오기 위해:

  1. navigableinputNavigable로 설정합니다.

  2. navigable부모가 null이 아닐 때마다, navigablenavigable부모로 설정합니다.

  3. navigable을 반환합니다.

새로운 최상위 탐색 가능 항목을 생성하기 위해, 탐색 컨텍스트-또는-null opener, 문자열 targetName 및 선택적으로 탐색 가능 항목 openerNavigableForWebDriver를 주어진 경우:

  1. document를 null로 설정합니다.

  2. opener가 null인 경우, document새로운 최상위 탐색 컨텍스트 및 문서 생성의 두 번째 반환값으로 설정합니다.

  3. 그렇지 않으면, document새로운 보조 탐색 컨텍스트 및 문서 생성의 두 번째 반환값으로 설정합니다.

  4. documentState를 새로운 문서 상태로 설정하고, 다음을 포함합니다:

    문서
    document
    초기화자 출처
    null (만약 opener가 null인 경우); 그렇지 않으면 document출처
    출처
    document출처
    탐색 대상 이름
    targetName
    about 기본 URL
    documentabout 기본 URL
  5. traversable을 새로운 탐색 가능한 탐색 항목으로 설정합니다.

  6. 탐색 가능 항목 초기화documentState를 주어 traversable을 초기화합니다.

  7. initialHistoryEntrytraversable활성 세션 기록 항목으로 설정합니다.

  8. initialHistoryEntry단계를 0으로 설정합니다.

  9. 목록에 추가 initialHistoryEntrytraversable세션 기록 항목들에 추가합니다.

  10. opener가 null이 아닌 경우, 탐색 가능한 저장소 클론opener최상위 탐색 가능 항목traversable을 주어 수행합니다. [STORAGE]

  11. 목록에 추가 traversable를 사용자 에이전트의 최상위 탐색 가능 항목 집합에 추가합니다.

  12. WebDriver BiDi 탐색 가능 항목 생성traversableopenerNavigableForWebDriver을 주어 호출합니다.

  13. traversable을 반환합니다.

새로운 최상위 탐색 가능 항목 생성하기 위해, URL initialNavigationURL과 선택적으로 POST 자원-또는-null initialNavigationPostResource (기본값 null)을 주어진 경우:

  1. traversable새로운 최상위 탐색 가능 항목 생성의 결과로서 설정하고, null과 빈 문자열을 사용합니다.

  2. 탐색 traversableinitialNavigationURL로, traversable활성 문서를 사용하여 탐색하며, 문서 자원initialNavigationPostResource로 설정합니다.

    이 초기 탐색들은 traversable이 스스로 탐색하는 것으로 간주되어, 관련된 모든 보안 검사가 통과되도록 합니다.

  3. traversable을 반환합니다.

7.3.1.3 자식 내비게이블

특정 요소(예: iframe 요소)는 사용자에게 navigable을 표시할 수 있습니다. 이러한 요소들을 navigable 컨테이너라고 합니다.

navigable 컨테이너content navigable을 가지며, 이는 navigable이거나 null입니다. 초기값은 null입니다.

navigable navigable컨테이너navigable 컨테이너로, 해당 content navigablenavigable입니다. 해당 요소가 없으면 null입니다.

navigable navigable컨테이너 문서를 구하는 단계는 다음과 같습니다:

  1. navigable컨테이너가 null인 경우 null을 반환합니다.

  2. navigable컨테이너노드 문서를 반환합니다.

    이는 navigable컨테이너섀도우 포함 루트와 동일합니다. navigable컨테이너연결됨이어야 하기 때문입니다.

문서 document컨테이너 문서를 구하는 단계는 다음과 같습니다:

  1. document노드 내비게이블이 null인 경우 null을 반환합니다.

  2. document노드 내비게이블컨테이너 문서를 반환합니다.

navigable navigable은 다른 potentialParent 내비게이블의 자식 내비게이블일 때, 즉 navigable부모potentialParent일 때 자식 내비게이블이라고 할 수 있습니다. 또한, navigable이 "자식 내비게이블"이라고 표현할 수도 있으며, 이는 해당 부모가 null이 아님을 의미합니다.

모든 자식 내비게이블은 해당 컨테이너content navigable입니다.

navigable 컨테이너 container컨텐츠 문서를 구하는 단계는 다음과 같습니다:

  1. containercontent navigable이 null인 경우 null을 반환합니다.

  2. containercontent navigable활성 문서document로 설정합니다.

  3. document원본container노드 문서원본동일 출처 도메인이 아닌 경우 null을 반환합니다.

  4. document를 반환합니다.

navigable 컨테이너 container컨텐츠 창을 구하는 단계는 다음과 같습니다:

  1. containercontent navigable이 null인 경우 null을 반환합니다.

  2. containercontent navigable활성 WindowProxy의 객체를 반환합니다.


요소 element를 주어진 상태에서 새로운 자식 내비게이블을 생성하려면:

  1. element노드 내비게이블parentNavigable로 설정합니다.

  2. element노드 문서브라우징 컨텍스트최상위 브라우징 컨텍스트그룹group으로 설정합니다.

  3. element노드 문서, elementgroup을 사용하여 새 브라우징 컨텍스트와 문서를 생성한 결과를 browsingContextdocument로 설정합니다.

  4. targetName을 null로 설정합니다.

  5. elementname 콘텐츠 속성이 있는 경우 해당 속성의 값을 targetName으로 설정합니다.

  6. 다음과 같은 속성을 가진 새로운 문서 상태documentState로 설정합니다:

    문서
    document
    이니시에이터 원본
    document원본
    원본
    document원본
    내비게이블 대상 이름
    targetName
    about 기본 URL
    documentabout 기본 URL
  7. 새로운 navigablenavigable로 설정합니다.

  8. navigable 초기화를 수행하여 navigabledocumentStateparentNavigable에 따라 초기화합니다.

  9. elementcontent navigablenavigable로 설정합니다.

  10. navigable활성 세션 히스토리 항목historyEntry로 설정합니다.

  11. parentNavigabletraversable navigabletraversable로 설정합니다.

  12. 다음 세션 히스토리 탐색 단계를 추가합니다 traversable에 대해:

    1. parentNavigable활성 세션 히스토리 항목문서 상태parentDocState로 설정합니다.

    2. parentNavigable의 세션 히스토리 항목을 얻기 위해 세션 히스토리 항목을 가져오기의 결과를 parentNavigableEntries로 설정합니다.

    3. parentNavigableEntries에서 parentDocState와 동일한 세션 히스토리 항목인 첫 번째 항목을 targetStepSHE로 설정합니다.

    4. historyEntry단계targetStepSHE단계로 설정합니다.

    5. navigableidnestedHistory의 id로 설정하고, nestedHistory항목 목록을 « historyEntry »로 설정한 새 중첩된 히스토리를 생성합니다.

    6. 추가합니다 nestedHistoryparentDocState중첩된 히스토리에.

    7. 내비게이블 생성/삭제에 대해 업데이트합니다 traversable에 대해.

  13. WebDriver BiDi navigable createdtraversable에 대해 호출합니다.

7.3.1.4 Jake 다이어그램

문서의 시퀀스, 특히 navigables와 그들의 세션 히스토리 항목을 시각화하는 유용한 방법은 Jake 다이어그램입니다. 일반적인 Jake 다이어그램은 다음과 같습니다:

0 1 2 3 4
top /t-a /t-a#foo /t-b
frames[0] /i-0-a /i-0-b
frames[1] /i-1-a /i-1-b

여기에서 각 번호가 매겨진 열은 트래버서블의 세션 히스토리 단계의 가능한 값을 나타냅니다. 각 라벨이 붙은 행은 navigable이 서로 다른 URL 및 문서 사이를 전환하는 것을 묘사합니다. 첫 번째는 최상위 트래버서블로 라벨이 붙은 top이고, 나머지는 자식 내비게이블입니다. 문서는 각 셀의 배경 색상으로 표시되며, 새로운 배경 색상은 해당 navigable에서 새로운 문서를 나타냅니다. URL은 셀의 텍스트 콘텐츠로 제공되며, 일반적으로 교차 출처 사례가 특별히 조사되지 않는 한 간결하게 상대 URL로 제공됩니다. 특정 navigable이 특정 단계에 존재하지 않을 경우 해당 셀은 비어 있습니다. 굵은 이탤릭체의 단계 번호는 트래버서블의 현재 세션 히스토리 단계를 나타내며, 굵은 이탤릭체의 URL이 있는 모든 셀은 해당 행의 navigable의 현재 세션 히스토리 항목을 나타냅니다.

따라서 위의 Jake 다이어그램은 다음과 같은 일련의 사건을 묘사합니다:

  1. 최상위 트래버서블이 생성되며, URL /t-a에서 시작하고 두 개의 자식 내비게이블이 각각 /i-0-a/i-1-a에서 시작합니다.

  2. 첫 번째 자식 내비게이블이 URL /i-0-b내비게이션됩니다.

  3. 두 번째 자식 내비게이블이 URL /i-1-b내비게이션됩니다.

  4. 최상위 트래버서블이 동일한 문서로 내비게이션되어 URL이 /t-a#foo로 업데이트됩니다.

  5. 최상위 트래버서블이 다른 문서로 내비게이션되어 URL이 /t-b가 됩니다. (이 문서는 물론 이전 문서의 자식 내비게이블을 그대로 가지고 있지 않습니다.)

  6. 트래버서블이 −3의 델타로 탐색되어 1단계로 돌아갑니다.

Jake 다이어그램은 여러 navigable, 내비게이션 및 탐색의 상호 작용을 시각화하는 강력한 도구입니다. 모든 상호 작용을 캡처할 수 있는 것은 아니지만 — 예를 들어, Jake 다이어그램은 중첩의 단일 수준에서만 작동합니다 — 이 표준에서 여러 복잡한 상황을 설명하는 데 사용될 수 있습니다.

Jake 다이어그램은 그 창시자이자 비할 데 없는 Jake Archibald의 이름을 따서 명명되었습니다.

이 표준의 알고리즘에서는 주어진 Document에서 시작하는 navigables 컬렉션을 보는 것이 종종 도움이 됩니다. 이 섹션은 그러한 내비게이블을 수집하기 위한 알고리즘의 선별된 집합을 포함하고 있습니다.

이들 알고리즘의 반환 값은 부모가 자식보다 먼저 나타나도록 정렬됩니다. 호출자는 이 정렬에 의존합니다.

Document에서 시작하는 것이 일반적으로 더 나은데, 이는 호출자가 완전히 활성화된 Document에서 시작하는지 여부를 인식하게 만들기 때문입니다. 비록 비-완전히 활성화된 Document도 상위 및 하위 내비게이블을 가지고 있지만, 이들은 종종 존재하지 않는 것처럼 동작합니다(예: window.parent getter에서).

Document document상위 내비게이블은 다음 단계에 따라 제공됩니다:

  1. document노드 내비게이블부모navigable로 설정합니다.

  2. ancestors를 빈 목록으로 설정합니다.

  3. navigable이 null이 아닐 때까지:

    1. Prepend navigableancestors에 추가합니다.

    2. navigablenavigable부모로 설정합니다.

  4. ancestors를 반환합니다.

Document document포함된 상위 내비게이블은 다음 단계에 따라 제공됩니다:

  1. document상위 내비게이블navigables로 설정합니다.

  2. Append document노드 내비게이블navigables에 추가합니다.

  3. navigables를 반환합니다.

Document document하위 내비게이블은 다음 단계에 따라 제공됩니다:

  1. navigables를 새로운 목록으로 설정합니다.

  2. navigableContainersdocument섀도우 포함 하위 요소들내비게이블 컨테이너인 요소들의 섀도우 포함 트리 순서에 따른 목록으로 설정합니다.

  3. 각각의 navigableContainer에 대해:

    1. navigableContainer내용 내비게이블이 null인 경우, 계속 진행합니다.

    2. 확장 navigablesnavigableContainer내용 내비게이블활성 문서포함된 하위 내비게이블을 추가합니다.

  4. navigables를 반환합니다.

Document document포함된 하위 내비게이블은 다음 단계에 따라 제공됩니다:

  1. navigables를 « document노드 내비게이블 »로 설정합니다.

  2. 확장 navigablesdocument하위 내비게이블을 추가합니다.

  3. navigables를 반환합니다.

이 하위 요소 수집 알고리즘은 하위 Document 객체의 DOM 트리를 보는 것으로 설명됩니다. 실제로는 호출자가 알고리즘을 호출할 때 DOM 트리가 다른 프로세스에 있을 수 있기 때문에 이는 종종 가능하지 않습니다. 대신 구현에서는 일반적으로 적절한 트리를 프로세스 간에 복제합니다.

Document document문서 트리 자식 내비게이블은 다음 단계에 따라 제공됩니다:

  1. document노드 내비게이블이 null인 경우, 빈 목록을 반환합니다.

  2. navigables를 새로운 목록으로 설정합니다.

  3. navigableContainersdocument하위 요소들내비게이블 컨테이너인 요소들의 트리 순서에 따른 목록으로 설정합니다.

  4. 각각의 navigableContainer에 대해:

    1. navigableContainer내용 내비게이블이 null인 경우, 계속 진행합니다.

    2. Append navigableContainer내용 내비게이블navigables에 추가합니다.

  5. navigables를 반환합니다.

7.3.1.6 내비게이블 파괴

container라는 내비게이블 컨테이너가 주어졌을 때, 자식 내비게이블을 파괴하려면:

  1. container콘텐츠 내비게이블navigable로 설정합니다.

  2. navigable이 null인 경우, 반환합니다.

  3. container콘텐츠 내비게이블을 null로 설정합니다.

  4. 자식 내비게이블 파괴에 대해 네비게이션 API에 알립니다를 호출합니다.

  5. 문서와 그 하위 요소들을 파괴navigable활성 문서에 대해 호출합니다.

  6. container노드 내비게이블활성 세션 히스토리 항목문서 상태parentDocState로 설정합니다.

  7. 제거 navigable중첩된 기록parentDocState중첩된 기록들에서 제거합니다.

  8. container노드 내비게이블내비게이블 트래버설traversable로 설정합니다.

  9. 세션 히스토리 트래버설 단계를 추가합니다 traversable에:

    1. 내비게이블 생성/파괴에 대해 업데이트traversable에 대해 호출합니다.

  10. WebDriver BiDi 내비게이블 파괴navigable에 대해 호출합니다.

traversable이라는 최상위 내비게이블이 주어졌을 때, 최상위 내비게이블을 파괴하려면:

  1. traversable활성 브라우징 컨텍스트browsingContext로 설정합니다.

  2. 각각의 historyEntry에 대해 traversable세션 히스토리 항목들에서 다음을 수행합니다:

    1. historyEntry문서document로 설정합니다.

    2. document가 null이 아닌 경우, 문서와 그 하위 요소들을 파괴document에 대해 호출합니다.

  3. 제거 browsingContext를 호출합니다.

  4. 탭 브라우저에서 탭을 닫거나 숨기는 등의 방법으로 사용자 인터페이스에서 traversable을 제거합니다.

  5. 제거 traversable을 사용자 에이전트의 최상위 내비게이블 집합에서 제거합니다.

  6. WebDriver BiDi 내비게이블 파괴traversable에 대해 호출합니다.

사용자 에이전트는 언제든지 (일반적으로 사용자 요청에 응답하여) 최상위 내비게이블을 파괴할 수 있습니다.

traversable이라는 최상위 내비게이블을 닫으려면:

  1. traversableis closing이 true인 경우, 반환합니다.

  2. traversable활성 문서포함된 하위 내비게이블들toUnload로 설정합니다.

  3. toUnload에 대해 언로드가 취소되었는지 확인을 수행한 결과가 true인 경우, 반환합니다.

  4. 세션 히스토리 트래버설 단계를 추가합니다 traversable에:

    1. traversable파괴하는 알고리즘 단계를 afterAllUnloads로 설정합니다.

    2. traversable활성 문서에 대해 null 및 afterAllUnloads를 사용하여 문서와 그 하위 요소들을 언로드합니다.

내비게이블대상 이름을 가질 수 있습니다. 이는 문자열로서 window.open()이나 a 요소의 target 속성 등 특정 API가 그 내비게이블에서 내비게이션을 대상으로 할 수 있도록 합니다.

유효한 내비게이블 대상 이름ASCII 탭 또는 줄바꿈과 U+003C (<)을 모두 포함하지 않고, U+005F (_)로 시작하지 않는 하나 이상의 문자가 포함된 문자열입니다. (U+005F (_)로 시작하는 이름은 특별한 키워드에 예약되어 있습니다.)

유효한 내비게이블 대상 이름 또는 키워드유효한 내비게이블 대상 이름이거나 _blank, _self, _parent, _top 중 하나와 ASCII 대소문자 무시 매치가 되는 문자열입니다.

이 값들은 페이지가 샌드박스 처리되었는지 여부에 따라 다른 의미를 가집니다. 아래 표는 요약된 비규범적인 예입니다. 이 표에서 "current"는 링크 또는 스크립트가 위치한 내비게이블, "parent"는 링크 또는 스크립트가 위치한 내비게이블부모를 의미하며, "top"은 링크 또는 스크립트가 위치한 내비게이블최상위 트래버서블을 의미합니다. "new"는 부모가 null인 새로운 트래버서블 내비게이블을 의미하며 (이는 사용자 설정과 사용자 에이전트 정책에 따라 보조 브라우징 컨텍스트를 사용할 수 있음), "none"은 아무 일도 일어나지 않음을 의미하며, "maybe new"는 "allow-popups" 키워드가 sandbox 속성에 지정된 경우 "new"와 동일하며, 그렇지 않으면 "none"과 동일합니다.

키워드 일반 효과 ...를 가진 iframe에서의 효과
sandbox="" sandbox="allow-top-navigation"
링크 및 폼 제출을 위한 지정되지 않은 경우 current current current
빈 문자열 current current current
_blank new maybe new maybe new
_self current current current
_parent 부모가 없는 경우 current current current
_parent 부모가 최상위인 경우 parent/top none parent/top
_parent 부모가 있고 최상위가 아닌 경우 parent none none
_top 최상위가 현재인 경우 current current current
_top 최상위가 현재가 아닌 경우 top none top
존재하지 않는 이름 new maybe new maybe new
존재하고 하위 요소인 이름 지정된 하위 요소 지정된 하위 요소 지정된 하위 요소
존재하고 현재인 이름 current current current
존재하고 최상위인 조상인 이름 지정된 조상 none 지정된 조상/최상위
존재하고 최상위가 아닌 조상인 이름 지정된 조상 none none
공통 최상위를 가진 다른 이름 지정된 none none
다른 최상위를 가진 이름, 익숙한 경우 및 허용된 샌드박스 내비게이터가 있는 경우 지정된 지정된 지정된
다른 최상위를 가진 이름, 익숙한 경우, 그러나 허용된 샌드박스 내비게이터가 없는 경우 지정된 none none
다른 최상위를 가진 이름, 익숙하지 않은 경우 new maybe new maybe new

샌드박스 처리된 브라우징 컨텍스트에 대한 대부분의 제한은 내비게이션 알고리즘 등 다른 알고리즘에 의해 적용되며, 아래에 주어진 내비게이블 선택 규칙에서는 적용되지 않습니다.


내비게이블 선택 규칙은 문자열 name, 내비게이블 currentNavigable, 그리고 부울 값 noopener를 주어진 조건으로 사용합니다:

  1. chosen을 null로 설정합니다.

  2. windowType을 "existing or none"으로 설정합니다.

  3. sandboxingFlagSetcurrentNavigable활성 문서활성 샌드박스 플래그 집합으로 설정합니다.

  4. name이 빈 문자열이거나 "_self"와 ASCII 대소문자 무시 매치가 되는 경우, chosencurrentNavigable로 설정합니다.

  5. 그렇지 않으면, name이 "_parent"와 ASCII 대소문자 무시 매치가 되는 경우, chosencurrentNavigable부모로 설정하고, 없다면 currentNavigable로 설정합니다.

  6. 그렇지 않으면, name이 "_top"와 ASCII 대소문자 무시 매치가 되는 경우, chosencurrentNavigable트래버서블 내비게이블로 설정합니다.

  7. 그렇지 않으면, name이 "_blank"와 ASCII 대소문자 무시 매치가 되지 않으며, name과 동일한 내비게이블을 가진 내비게이블이 존재하고, currentNavigable활성 브라우징 컨텍스트가 해당 내비게이블활성 브라우징 컨텍스트익숙한 상태이며, 두 브라우징 컨텍스트가 서로 접근해도 괜찮다고 사용자 에이전트가 판단하는 경우, chosen을 그 내비게이블로 설정합니다. 일치하는 내비게이블이 여러 개 있는 경우, 사용자 에이전트는 가장 최근에 열렸거나, 가장 최근에 포커스된 것이나, 더 가까운 관련성을 가진 것을 선택하여 chosen으로 설정해야 합니다.

    이 부분은 issue #313에서 더 명확하게 정리될 것입니다.

  8. 그렇지 않으면, 새 최상위 트래버서블이 요청 중이며, 이는 사용자 에이전트의 설정과 능력에 따라 결정되며, 아래의 첫 번째 적용 가능한 옵션에 따른 규칙에 의해 결정됩니다:

    사용자 에이전트는 사용자가 팝업이 차단되었다고 알릴 수 있습니다.

    sandboxingFlagSet샌드박스된 보조 내비게이션 브라우징 컨텍스트 플래그가 설정된 경우

    사용자 에이전트는 개발자 콘솔에 팝업이 차단되었다고 보고할 수 있습니다.

    사용자 에이전트가 이 경우 새로운 최상위 트래버서블을 생성하도록 설정된 경우
    1. windowType을 "new and unrestricted"로 설정합니다.

    2. currentDocumentcurrentNavigable활성 문서로 설정합니다.

    3. 만약 currentDocument교차 출처 오프너 정책이 "same-origin" 또는 "same-origin-plus-COEP"이고, currentDocument출처currentDocument관련 설정 객체최상위 출처동일 출처가 아닌 경우:

      1. noopener를 true로 설정합니다.

      2. name을 "_blank"로 설정합니다.

      3. windowType을 "new with no opener"로 설정합니다.

      교차 출처 오프너 정책이 있는 경우, 최상위 브라우징 컨텍스트의 활성 문서와 교차 출처인 중첩 문서는 항상 noopener를 true로 설정합니다.

    4. chosen을 null로 설정합니다.

    5. targetName을 빈 문자열로 설정합니다.

    6. 만약 name이 "_blank"와 ASCII 대소문자 무시 매치가 되지 않는다면, targetNamename으로 설정합니다.

    7. 만약 noopener가 true인 경우, chosen을 null로 주어진 새로운 최상위 트래버서블 생성의 결과로 설정합니다.

    8. 그렇지 않으면:

      1. chosen을 주어진 최상위 트래버서블 생성의 결과로 설정합니다. currentNavigable활성 브라우징 컨텍스트, targetName, 그리고 currentNavigable을 기반으로 합니다.

      2. 만약 sandboxingFlagSet샌드박스된 내비게이션 브라우징 컨텍스트 플래그가 설정된 경우, chosen활성 브라우징 컨텍스트허용된 하나의 샌드박스된 내비게이터currentNavigable활성 브라우징 컨텍스트로 설정합니다.

    9. 만약 sandboxingFlagSet샌드박스가 보조 브라우징 컨텍스트로 전파됨 플래그가 설정된 경우, sandboxingFlagSet에 설정된 모든 플래그는 chosen활성 브라우징 컨텍스트팝업 샌드박싱 플래그 세트에도 설정되어야 합니다.

    새로 생성된 내비게이블 chosen이 즉시 내비게이션되는 경우, 내비게이션은 "replace" 내비게이션으로 수행됩니다.

    사용자 에이전트가 이 경우 currentNavigable을 선택하도록 설정된 경우

    chosencurrentNavigable로 설정합니다.

    사용자 에이전트가 이 경우 내비게이블을 찾지 않도록 설정된 경우

    아무것도 하지 않습니다.

    사용자 에이전트는 사용자가 항상 currentNavigable을 선택하도록 설정할 수 있는 방법을 제공하는 것이 권장됩니다.

  9. chosenwindowType을 반환합니다.

7.3.2 브라우징 컨텍스트

브라우징 컨텍스트는 일련의 문서를 프로그래밍적으로 표현한 것으로, 여러 문서가 단일 탐색 가능 항목 내에 존재할 수 있습니다. 각 브라우징 컨텍스트는 해당하는 WindowProxy 객체와 다음을 포함합니다:

브라우징 컨텍스트활성 창은 해당 WindowProxy 객체의 [[Window]] 내부 슬롯 값입니다. 브라우징 컨텍스트활성 문서활성 창연결된 Document입니다.

브라우징 컨텍스트최상위 탐색 가능 항목활성 문서노드 탐색 가능 항목최상위 탐색 가능 항목입니다.

브라우징 컨텍스트보조 여부가 true인 경우, 이를 보조 브라우징 컨텍스트라고 합니다. 보조 브라우징 컨텍스트는 항상 최상위 브라우징 컨텍스트입니다.

별도의 보조 여부 개념이 필요한지 불확실합니다. 이슈 #5680에서는 오프너 브라우징 컨텍스트가 null인지 여부를 사용하여 이를 간소화할 수 있을 것이라고 언급했습니다.

최신 명세는 대부분의 경우 브라우징 컨텍스트 개념을 사용하는 것을 피해야 합니다. 대신 Document탐색 가능 항목 개념이 더 적합한 경우가 많습니다.


Document의 브라우징 컨텍스트브라우징 컨텍스트 또는 null이며, 초기값은 null입니다.

Document는 반드시 비-null 브라우징 컨텍스트를 가지는 것은 아닙니다. 특히, 데이터 마이닝 도구는 브라우징 컨텍스트를 인스턴스화하지 않을 가능성이 큽니다. DocumentcreateDocument()와 같은 API를 사용해 생성된 경우, 브라우징 컨텍스트는 절대 비-null이 되지 않습니다. Document는 원래 iframe 요소를 위해 생성되었으나, 그 문서에서 제거된 후에는 관련 브라우징 컨텍스트가 더 이상 존재하지 않으므로 비-null 브라우징 컨텍스트를 가지지 않습니다.

일반적으로 Window 객체와 Document 객체 간에는 1:1 매핑이 존재하며, Document 객체가 비-null 브라우징 컨텍스트를 가지는 한, 이 매핑이 유지됩니다. 하나의 예외는 동일한 브라우징 컨텍스트에서 두 번째 Document의 표현을 위해 Window가 재사용될 수 있다는 점입니다. 이 경우, 매핑은 1:2로 변경됩니다. 이는 브라우징 컨텍스트가 초기 about:blank Document에서 다른 문서로 탐색될 때 발생하며, 이 탐색은 교체 방식으로 수행됩니다.

7.3.2.1 브라우징 컨텍스트 생성

다음과 같은 경우에 새 브라우징 컨텍스트와 문서를 생성합니다: null 또는 문서 객체 creator, null 또는 엘리먼트 embedder, 그리고 브라우징 컨텍스트 그룹 group을 제공하는 경우:

  1. browsingContext를 새로운 브라우징 컨텍스트로 설정합니다.

  2. unsafeContextCreationTime공유된 현재 시간(unsafe shared current time)으로 설정합니다.

  3. creatorOrigin을 null로 설정합니다.

  4. creatorBaseURL을 null로 설정합니다.

  5. creator가 null이 아닌 경우 다음을 수행합니다:

    1. creatorOrigincreatororigin으로 설정합니다.

    2. creatorBaseURLcreator문서 기본 URL로 설정합니다.

    3. browsingContext가상 브라우징 컨텍스트 그룹 IDcreator브라우징 컨텍스트최상위 브라우징 컨텍스트가상 브라우징 컨텍스트 그룹 ID로 설정합니다.

  6. sandboxFlagsbrowsingContextembedder를 사용해 생성 샌드박싱 플래그 결정의 결과로 설정합니다.

  7. originabout:blanksandboxFlags, 그리고 creatorOrigin을 사용해 원본 결정의 결과로 설정합니다.

  8. permissionsPolicyembedderorigin을 사용해 권한 정책 생성의 결과로 설정합니다. [PERMISSIONSPOLICY]

  9. agentorigin, group, 그리고 false를 사용해 유사 출처 창 에이전트 획득의 결과로 설정합니다.

  10. realm execution contextagent와 다음 커스터마이징을 사용해 새로운 자바스크립트 렐름 생성의 결과로 설정합니다:

  11. topLevelCreationURLabout:blank로 설정합니다; embedder가 null이 아닌 경우, embedder관련 설정 객체최상위 생성 URL로 설정합니다.

  12. topLevelOriginorigin으로 설정합니다; embedder가 null이 아닌 경우, embedder관련 설정 객체최상위 출처로 설정합니다.

  13. Window 환경 설정 객체 설정about:blank, realm execution context, null, topLevelCreationURL, 그리고 topLevelOrigin과 함께 실행합니다.

  14. loadTimingInfo를 새로운 문서 로드 타이밍 정보로 설정하고, 그 탐색 시작 시간시간 조정을 호출한 결과로 설정합니다.

  15. document를 새로운 문서로 설정하고, 다음을 포함합니다:

    유형
    "html"
    콘텐츠 유형
    "text/html"
    모드
    "quirks"
    출처
    origin
    브라우징 컨텍스트
    browsingContext
    권한 정책
    permissionsPolicy
    활성화된 샌드박싱 플래그 세트
    sandboxFlags
    로드 타이밍 정보
    loadTimingInfo
    초기 about:blank 상태
    True
    기본 URL
    creatorBaseURL
    선언적 쉐도우 루트 허용
    True
  16. creator가 null이 아닌 경우 다음을 수행합니다:

    1. documentreferrerURL 직렬화(serialization)로 설정합니다.

    2. document정책 컨테이너복제하여 creator정책 컨테이너로 설정합니다.

    3. creator출처동일 출처인 경우 document교차 출처 열기 정책creator브라우징 컨텍스트최상위 브라우징 컨텍스트활성화된 문서교차 출처 열기 정책으로 설정합니다.

  17. 확인(assert): documentURLdocument관련 설정 객체생성 URLabout:blank임을 확인합니다.

  18. document로드 후 작업을 위한 준비 완료 상태로 표시합니다.

  19. document에 대해 html/head/body로 채우기를 실행합니다.

  20. document활성화합니다.

  21. 로드를 완전히 완료한 후 document를 반환합니다.

  22. browsingContextdocument를 반환합니다.

새로운 최상위 브라우징 컨텍스트와 문서를 생성하려면:

  1. groupdocument새로운 브라우징 컨텍스트 그룹 및 문서 생성의 결과로 설정합니다.

  2. group브라우징 컨텍스트 집합[0]과 document를 반환합니다.

새로운 보조 브라우징 컨텍스트와 문서를 생성하려면, 주어진 브라우징 컨텍스트 opener를 사용합니다:

  1. openerTopLevelBrowsingContextopener최상위 탐색 가능활성화된 브라우징 컨텍스트로 설정합니다.

  2. groupopenerTopLevelBrowsingContext그룹으로 설정합니다.

  3. 확인(assert): group이 null이 아닌지 확인합니다, 탐색은 이를 직접 호출합니다.

  4. browsingContextdocument새로운 브라우징 컨텍스트 및 문서 생성의 결과로 설정합니다, opener활성화된 문서를 사용합니다.

  5. browsingContext보조 여부를 true로 설정합니다.

  6. 추가: browsingContextgroup에 추가합니다.

  7. browsingContextopener 브라우징 컨텍스트opener로 설정합니다.

  8. browsingContext가상 브라우징 컨텍스트 그룹 IDopenerTopLevelBrowsingContext가상 브라우징 컨텍스트 그룹 ID로 설정합니다.

  9. browsingContext생성 시 opener 출처opener활성화된 문서출처로 설정합니다.

  10. browsingContextdocument를 반환합니다.

출처 결정을 위해, 주어진 URL url, 샌드박싱 플래그 세트 sandboxFlags, 및 출처 또는 null sourceOrigin을 사용합니다:

  1. sandboxFlags샌드박스된 출처 브라우징 컨텍스트 플래그가 설정된 경우, 새 불투명 출처를 반환합니다.

  2. url이 null인 경우, 새 불투명 출처를 반환합니다.

  3. urlabout:srcdoc인 경우:

    1. 확인(assert): sourceOrigin이 null이 아닌지 확인합니다.

    2. sourceOrigin을 반환합니다.

  4. urlabout:blank와 일치하고 sourceOrigin이 null이 아닌 경우, sourceOrigin을 반환합니다.

  5. url출처를 반환합니다.

위의 sourceOrigin을 반환하는 경우에는 두 문서가 동일한 출처를 가지게 되므로, document.domain이 둘 다에 영향을 미칩니다.

7.3.2.2 관련 브라우징 컨텍스트

브라우징 컨텍스트 potentialDescendantpotentialAncestor상위 컨텍스트라고 할 수 있는 경우는 다음 알고리즘이 true를 반환할 때입니다:

  1. potentialDescendantDocumentpotentialDescendant활성 문서로 설정합니다.

  2. 만약 potentialDescendantDocument완전히 활성화된 상태가 아니라면, false를 반환합니다.

  3. ancestorBCspotentialDescendantDocument상위 내비게이팅 요소들의 각 요소의 활성 문서에서 브라우징 컨텍스트를 가져와서 구성된 목록으로 설정합니다.

  4. 만약 ancestorBCspotentialAncestor포함되어 있다면, true를 반환합니다.

  5. false를 반환합니다.

최상위 브라우징 컨텍스트브라우징 컨텍스트이며, 그 활성 문서노드 내비게이팅 요소탐색 가능한 내비게이팅 요소인 경우를 의미합니다.

이는 최상위 탐색 가능 항목일 필요는 없습니다.

브라우징 컨텍스트 start최상위 브라우징 컨텍스트는 다음 알고리즘의 결과입니다:

  1. start활성 문서완전히 활성화되지 않은 경우, null을 반환합니다.

  2. navigablestart활성 문서노드 탐색 가능 항목으로 설정합니다.

  3. navigable부모가 null이 아닐 때까지 navigablenavigable부모로 설정합니다.

  4. navigable활성 브라우징 컨텍스트를 반환합니다.


브라우징 컨텍스트 A는 다음 알고리즘이 true를 반환하는 경우 두 번째 브라우징 컨텍스트 B친숙하다고 할 수 있습니다:

  1. 만약 A활성 문서originB활성 문서origin동일 출처인 경우, true를 반환합니다.

  2. 만약 A최상위 브라우징 컨텍스트B인 경우, true를 반환합니다.

  3. 만약 B보조 브라우징 컨텍스트이고, AB열기 브라우징 컨텍스트친숙한 경우, true를 반환합니다.

  4. 만약 B상위 브라우징 컨텍스트 중 하나가 A활성 문서동일한 출처를 가진 활성 문서를 가지고 있는 경우, true를 반환합니다.

    이 경우에는 AB상위 브라우징 컨텍스트인 경우도 포함됩니다.

  5. false를 반환합니다.

7.3.2.3 브라우징 컨텍스트의 그룹화

최상위 브라우징 컨텍스트는 연관된 그룹(null 또는 브라우징 컨텍스트 그룹)을 가집니다. 이는 초기에는 null입니다.

사용자 에이전트는 브라우징 컨텍스트 그룹 세트(집합으로 구성된 브라우징 컨텍스트 그룹)을 보유합니다.

브라우징 컨텍스트 그룹브라우징 컨텍스트 세트(집합으로 구성된 최상위 브라우징 컨텍스트)을 보유합니다.

최상위 브라우징 컨텍스트는 그룹이 생성될 때 그룹에 추가됩니다. 이후에 그룹에 추가되는 모든 최상위 브라우징 컨텍스트보조 브라우징 컨텍스트가 됩니다.

브라우징 컨텍스트 그룹은 연관된 에이전트 클러스터 맵(으로 구성된 에이전트 클러스터 키에이전트 클러스터)를 보유합니다. 사용자 에이전트는 더 이상 접근할 수 없다고 판단되면 에이전트 클러스터를 수집할 책임이 있습니다.

브라우징 컨텍스트 그룹은 연관된 히스토리컬 에이전트 클러스터 키 맵을 가지며, 이는 으로 구성된 출처에이전트 클러스터 키입니다. 이 맵은 주어진 출처에 대해 이전에 사용된 에이전트 클러스터 키를 기록하여 출처 기반 에이전트 클러스터 기능의 일관성을 보장하는 데 사용됩니다.

히스토리컬 에이전트 클러스터 키 맵은 브라우징 컨텍스트 그룹의 수명 동안 항목이 추가될 수 있습니다.

브라우징 컨텍스트 그룹은 연관된 크로스 오리진 격리 모드를 가지며, 이는 크로스 오리진 격리 모드입니다. 이는 처음에 "없음"으로 설정됩니다.

크로스 오리진 격리 모드는 "없음", "논리적", 또는 "구체적"의 세 가지 값 중 하나일 수 있습니다.

"논리적" 및 "구체적"은 비슷합니다. 두 모드 모두 다음과 같은 브라우징 컨텍스트 그룹에 사용됩니다:

일부 플랫폼에서는 크로스 오리진 격리 기능에 의해 게이트된 API에 안전하게 접근할 수 있는 보안 속성을 제공하기 어렵습니다. 따라서 "구체적"만이 이 기능에 접근할 수 있게 합니다. "논리적"은 이 기능을 지원하지 않는 플랫폼에서 사용되며, 크로스 오리진 격리에 의해 부과된 다양한 제한은 적용되지만 이 기능은 제공되지 않습니다.

새로운 브라우징 컨텍스트 그룹과 문서를 생성하려면 다음을 수행합니다:

  1. 새로운 브라우징 컨텍스트 그룹을 생성합니다.

  2. 추가합니다. 사용자 에이전트의 브라우징 컨텍스트 그룹 세트group을 추가합니다.

  3. null, null 및 group을 사용하여 새로운 브라우징 컨텍스트와 문서를 생성하고, browsingContextdocument를 반환합니다.

  4. 추가합니다. browsingContextgroup에 추가합니다.

  5. groupdocument를 반환합니다.

최상위 브라우징 컨텍스트 browsingContext브라우징 컨텍스트 그룹 group추가하려면 다음을 따릅니다:

  1. 추가합니다. browsingContextgroup브라우징 컨텍스트 세트에 추가합니다.

  2. browsingContext그룹group으로 설정합니다.

최상위 브라우징 컨텍스트 browsingContext제거하려면 다음을 따릅니다:

  1. 확인: browsingContext그룹이 null이 아님을 확인합니다.

  2. browsingContext그룹group으로 설정합니다.

  3. browsingContext그룹을 null로 설정합니다.

  4. 제거합니다. browsingContextgroup브라우징 컨텍스트 세트에서 제거합니다.

  5. 만약 group브라우징 컨텍스트 세트비어있는 경우, 사용자 에이전트의 브라우징 컨텍스트 그룹 세트에서 group제거합니다.

추가제거브라우징 컨텍스트 그룹의 수명을 정의하는 기본 작업입니다. 이들은 문서브라우징 컨텍스트의 생성 및 소멸 작업에 의해 호출됩니다.

주어진 브라우징 컨텍스트와 동일한 문서 객체가 없을 때(즉, 해당 문서가 모두 파괴된 경우) 그리고 해당 브라우징 컨텍스트WindowProxy가 가비지 수집 대상일 경우, 해당 브라우징 컨텍스트는 다시는 접근되지 않습니다. 만약 그것이 최상위 브라우징 컨텍스트라면, 이 시점에서 사용자 에이전트는 이를 제거해야 합니다.

7.3.3 완전히 활성화된 문서

Document d완전히 활성화되었다고 할 때, d활성 문서탐색 가능한 navigable이며, navigable최상위 탐색 가능 또는 navigable컨테이너 문서완전히 활성화된 경우를 의미합니다.

요소와 연결되어 있기 때문에, 자식 탐색 가능 요소는 항상 특정 Document컨테이너 문서에 연결되어 있으며, 이들은 상위 탐색 가능 요소 안에 있습니다. 사용자 에이전트는 사용자가 자식 탐색 가능 요소와 상호작용하는 것을 허용해서는 안 됩니다. 컨테이너 문서완전히 활성화되지 않은 경우에는 말입니다.

다음 예제는 Document활성 문서이면서도 완전히 활성화되지 않은 경우를 보여줍니다. 여기서 a.html은 브라우저 창에 로드되고, b-1.htmliframe 안에 로드되며, b-2.htmlc.html은 생략됩니다(그들은 단순히 빈 문서일 수 있습니다).

<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<title>Navigable A</title>

<iframe src="b-1.html"></iframe>
<button onclick="frames[0].location.href = 'b-2.html'">Click me</button>

<!-- b-1.html -->
<!DOCTYPE html>
<html lang="en">
<title>Navigable B</title>

<iframe src="c.html"></iframe>

이 시점에서 a.html, b-1.html, 그리고 c.html 문서들은 모두 각자의 활성 문서입니다. 또한 모두 완전히 활성화되었습니다.

버튼을 클릭하여 탐색 가능 B에 새로운 Documentb-2.html을 로드한 후, 다음과 같은 결과가 나타납니다:

용의 입에 오신 것을 환영합니다. 내비게이션, 세션 기록, 그리고 그 세션 기록을 통한 탐색은 이 표준에서 가장 복잡한 부분 중 일부입니다.

기본 개념은 그리 어렵지 않아 보일 수 있습니다:

여기에서 탐색이 세션 기록을 통해 탐색(즉, 저장된 URL로의 네트워크 가져오기)을 유발할 수 있는 방식과, 탐색이 완료되면 사용자가 올바른 내용을 보고 있는지 확인하기 위해 세션 기록 목록과 상호 작용해야 하는 방식에서 얽힌 복잡성이 일부 드러납니다. 하지만 실제 문제는 다양한 엣지 케이스와 상호 작용하는 웹 플랫폼 기능에서 발생합니다:

다음 내용에서는 이러한 복잡성을 적절히 구분된 섹션과 알고리즘에 배치하고, 가능한 곳에서 적절한 설명을 제공하여 독자가 이러한 복잡성을 이해할 수 있도록 안내하려고 노력했습니다. 그럼에도 불구하고 내비게이션 및 세션 기록을 진정으로 이해하고자 한다면, 일반적인 조언이 매우 유용할 것입니다.

7.4.1 세션 기록

7.4.1.1 세션 기록 항목

세션 기록 항목은 다음 구조체항목을 포함하는 구조체입니다:

세션 기록 항목문서를 가져오려면, 해당 문서 상태문서를 반환합니다.


직렬화된 상태StructuredSerializeForStorage를 통해 객체를 직렬화한 것으로, 사용자 인터페이스 상태를 나타냅니다. 우리는 때때로 "상태 객체"라고 비공식적으로 부르기도 하는데, 이는 작성자가 제공한 사용자 인터페이스 상태를 나타내는 객체이거나, 직렬화된 상태를 StructuredDeserialize를 통해 역직렬화하여 생성된 객체입니다.

페이지는 세션 기록에 추가할 수 있는 직렬화된 상태를 추가할 수 있습니다. 그런 다음, 사용자가 (또는 스크립트가) 기록을 탐색할 때, 이 상태들은 역직렬화되어 스크립트로 반환되므로, 작성자는 단일 페이지 애플리케이션에서도 "내비게이션" 메타포를 사용할 수 있습니다.

직렬화된 상태는 두 가지 주요 목적을 위해 사용될 의도가 있습니다. 첫째, 작성자가 구문 분석을 하지 않아도 되도록 URL에 상태에 대한 사전 구문 분석된 설명을 저장하는 것입니다 (하지만 사용자가 전달하는 URL을 처리하려면 여전히 구문 분석이 필요하므로, 이는 단지 작은 최적화일 뿐입니다). 둘째, 현재 Document 인스턴스에만 적용되는 상태를 저장할 수 있도록 하는 것입니다. 이는 새로운 Document가 열리면 다시 구성해야 할 수도 있습니다.

후자의 예로는 팝업 div가 애니메이션을 시작한 정확한 좌표를 추적하는 것이 있으며, 사용자가 다시 돌아갔을 때 동일한 위치로 애니메이션이 실행될 수 있도록 할 수 있습니다. 또는 서버에서 URL의 정보를 기반으로 가져올 데이터를 가리키는 포인터를 유지하는 데 사용할 수 있으며, 이렇게 하면 뒤로 및 앞으로 이동할 때 정보를 다시 가져올 필요가 없습니다.


스크롤 복원 모드는 사용자가 세션 기록 항목으로 탐색할 때, 사용자 에이전트가 저장된 스크롤 위치(있는 경우)를 복원해야 하는지 여부를 나타냅니다. 스크롤 복원 모드는 다음 중 하나입니다:

"auto"
사용자 에이전트가 내비게이션 시 스크롤 위치를 복원할 책임이 있습니다.
"manual"
페이지가 스크롤 위치를 복원할 책임이 있으며, 사용자 에이전트는 이를 자동으로 수행하지 않습니다.
7.4.1.2 문서 상태

문서 상태Document를 표시하고, 필요시 이를 재생성하는 방법에 대한 정보를 세션 기록 항목에 저장합니다. 문서 상태는 다음과 같은 내용을 포함합니다:

사용자 에이전트는 문서 및 그 하위 문서들을 파괴할 수 있으며, 문서 상태문서가 null이 아니고, 해당 Document완전히 활성화되지 않은 경우에 한합니다.

이 제한 사항 외에도, 이 표준은 사용자 에이전트가 문서 상태에 저장된 문서를 언제 파괴할지, 캐시에 유지할지를 지정하지 않습니다.


POST 리소스는 다음을 포함합니다:


중첩된 히스토리는 다음을 포함합니다:

이후에 자식 탐색 가능 요소를 리로드할 때 식별하는 방법이 여기에 포함될 것입니다.


세션 기록에서 몇 개의 연속적인 항목이 동일한 문서 상태를 공유할 수 있습니다. 이는 첫 번째 항목이 일반 탐색을 통해 도달하고, 이후의 항목이 history.pushState()를 통해 추가될 때 발생할 수 있습니다. 또는 프래그먼트로의 탐색을 통해 발생할 수 있습니다.

동일한 문서 상태를 공유하는 모든 항목(따라서 특정 문서의 서로 다른 상태일 뿐인 항목)은 구조적으로 연속적입니다.


Document최신 항목을 가지며, 이는 세션 기록 항목 또는 null입니다.

이는 주어진 Document에 의해 가장 최근에 표현된 항목입니다. 하나의 Document는 시간이 지나면서 여러 세션 기록 항목들을 나타낼 수 있으며, 위에서 설명한 것처럼 여러 연속적인 세션 기록 항목들이 동일한 문서 상태를 공유할 수 있습니다.

7.4.1.3 세션 기록의 중앙 집중식 수정

탐색 가능 요소세션 기록 항목을 수정하려면, 모든 수정 작업이 동기화되어야 하며, 이를 통해 단일 진실 소스를 유지할 수 있습니다. 이는 세션 기록이 하위 탐색 가능 요소들과 여러 이벤트 루프에 의해 영향을 받기 때문에 특히 중요합니다. 이를 달성하기 위해, 우리는 세션 기록 탐색 병렬 큐 구조를 사용합니다.

세션 기록 탐색 병렬 큐병렬 큐와 매우 유사합니다. 이 큐는 알고리즘 집합정렬된 집합을 가지고 있습니다.

항목들세션 기록 탐색 병렬 큐알고리즘 집합에 포함되며, 이들은 알고리즘 단계이거나 동기 탐색 단계입니다. 동기 탐색 단계는 특정 대상 탐색 가능 요소(탐색 가능 요소)를 포함하는 알고리즘 단계의 일종입니다.

알고리즘 단계 steps가 주어졌을 때, 탐색 가능 요소 traversable에 대해 세션 기록 탐색 단계를 추가하려면, 추가합니다 stepstraversable세션 기록 탐색 큐알고리즘 집합에.

특정 탐색 가능 요소 targetNavigable와 관련된 세션 기록 동기 탐색 단계탐색 가능 요소 traversable에 추가하려면, 추가합니다 steps동기 탐색 단계로서 targetNavigable 대상 탐색 가능 요소를 목표로 traversable세션 기록 탐색 큐알고리즘 집합에 추가합니다.

새로운 세션 기록 탐색 병렬 큐 시작하기:

  1. sessionHistoryTraversalQueue를 새 세션 기록 탐색 병렬 큐로 설정합니다.

  2. 다음 단계를 병렬로 실행합니다:

    1. 계속 반복:

      1. 만약 sessionHistoryTraversalQueue알고리즘 집합이 비어 있으면, 계속합니다.

      2. stepssessionHistoryTraversalQueue알고리즘 집합에서 디큐한 결과로 설정합니다.

      3. steps를 실행합니다.

  3. sessionHistoryTraversalQueue를 반환합니다.

동기 탐색 단계알고리즘 집합에서 태그로 지정되어 조건부로 "큐를 건너뛰기"할 수 있습니다. 이는 히스토리 단계 적용에서 처리됩니다.

다음 Jake 다이어그램에서 나타난 공동 세션 기록을 상상해 보십시오:

0 1
top /a /b

그리고 최상위 수준에서 다음 코드가 실행됩니다:

history.back();
location.href = '#foo';

원하는 결과는 다음과 같습니다:

0 1 2
top /a /b /b#foo

이 결과를 달성하려면, 다음이 발생합니다:

  1. history.back()단계를 큐에 추가하여 -1 델타로 탐색하도록 합니다.

  2. location.href = '#foo'는 동기적으로 활성 세션 기록 항목을 새로 생성된 항목으로 변경합니다. 이 항목은 URL /b#foo를 가지고 있으며, 중앙 집중식 진실 소스에 이 새로운 항목을 알리기 위해 동기 단계를 추가합니다. 이때 현재 세션 기록 항목, 현재 세션 기록 단계, 또는 세션 기록 항목 목록은 아직 동기적으로 업데이트되지 않습니다. 이러한 업데이트는 큐에 대기 중인 단계의 일부로 처리되어야 합니다.

  3. 세션 기록 탐색 병렬 큐에서 history.back()에 의해 큐에 추가된 단계가 실행됩니다:

    1. 대상 히스토리 단계가 0으로 결정됩니다: 현재 세션 기록 단계(i.e., 1)에서 -1을 더한 값입니다.

    2. 메인 히스토리 단계 적용 알고리즘을 시작합니다.

      단계 0에서, /a URL에 대한 항목의 문서가 채워집니다.

      동시에 큐는 동기 탐색 단계를 확인합니다. 이제 location.href 설정자에 의해 큐에 추가된 단계가 실행되며, 문서 채우기 외에 탐색이 문서를 언로드하고 활성 기록 항목을 전환하는 등의 효과를 수행하지 않도록 차단합니다. 이 단계에서는 다음이 발생합니다:

      1. URL /b#foo를 가진 항목이 추가되며, 단계는 2로 결정됩니다: 현재 세션 기록 단계(i.e., 1)에서 1을 더한 값입니다.

      2. 우리는 완전히 새로 추가된 항목으로 전환하며, 여기에는 히스토리 단계 적용을 포함한 모든 작업이 포함됩니다. 결국 문서를 업데이트하여 hashchange와 같은 이벤트를 디스패치합니다.

      이 모든 작업이 완료되고 /a 히스토리 항목이 문서로 완전히 채워지면, 우리는 0 단계에 대한 히스토리 단계 적용을 진행합니다.

      이 시점에서 URL /b#foo를 가진 Document언로드되며, 우리는 목표 히스토리 단계 0으로 이동을 완료합니다. 이로 인해 URL /a를 가진 항목이 활성 세션 기록 항목이 되고, 0이 현재 세션 기록 단계가 됩니다.

다음은 두 개의 다른 iframe을 채우는 것과 하나의 iframe이 로드된 후 동기 탐색 간의 경쟁을 포함하는 더 복잡한 예제입니다. 우리는 다음과 같은 설정으로 시작합니다:

0 1 2
top /t
frames[0] /i-0-a /i-0-b
frames[1] /i-1-a /i-1-b

그런 다음 history.go(-2)를 호출합니다. 그러면 다음이 발생합니다:

  1. history.go(-2)는 -2 델타로 탐색하려는 단계를 추가합니다. 해당 단계가 실행되면:

    1. 대상 단계는 2 + (−2) = 0으로 결정됩니다.

    2. 병렬로 두 iframe을 채우기 위한 페치가 시작되며, 각각 /i-0-a/i-1-a를 가져옵니다.

      동시에 큐는 동기 탐색 단계를 확인합니다. 현재로서는 없습니다.

    3. 페치 경쟁에서 /i-0-a의 페치가 이깁니다. 우리는 frames[0] 탐색 가능 요소에 대한 모든 작업을 완료하고, URL이 /i-0-a인 항목으로 활성 세션 기록 항목을 업데이트합니다.

    4. /i-1-a에 대한 페치가 완료되기 전에, frames[0] 탐색 가능 요소활성 문서에서 새로 생성된 문서에 대해 스크립트가 실행될 수 있는 지점에 도달합니다. 어떤 스크립트가 실행됩니다:

      location.href = '#foo'

      이것은 동기적으로 frames[0] 탐색 가능 요소의 활성 세션 기록 항목을 새로 생성된 항목으로 변경하며, 이 항목은 URL /i-0-a#foo를 가지고 있습니다. 그런 다음 중앙 집중식 진실 소스에 이 새로운 항목을 알리기 위해 동기 단계를 추가합니다.

      이전 예제와 달리, 이러한 동기 단계는 "큐를 건너뛰지" 않으며, /i-1-a의 페치를 완료하기 전에 탐색 가능 요소를 업데이트하지 않습니다. 이는 frames[0]이 이미 탐색의 일환으로 변경되었기 때문에, 현재 세션 기록 단계가 2인 상황에서 새로운 항목을 3단계로 추가하는 것이 말이 되지 않기 때문입니다.

    5. 마침내 /i-1-a에 대한 페치가 완료되면, 우리는 frames[1] 탐색 가능 요소에 대한 탐색을 완료하고, URL이 /i-1-a인 항목으로 활성 세션 기록 항목을 업데이트합니다.

    6. 이제 두 탐색 가능 요소 모두 탐색 처리를 완료했으므로, 우리는 현재 세션 기록 단계를 대상 단계인 0으로 업데이트합니다.

  2. 이제 동기 탐색에 대해 큐에 대기 중이었던 단계를 처리할 수 있습니다:

    1. /i-0-a#foo 항목이 추가되며, 그 단계는 1로 결정됩니다: 현재 세션 기록 단계(즉, 0)에서 1을 더한 값입니다. 이는 또한 기존의 앞으로의 세션 기록을 삭제합니다.

    2. 우리는 새로 추가된 항목으로 완전히 전환하며, 히스토리 단계를 적용하는 것을 포함합니다. 이 결과는 문서를 업데이트하고 hashchange와 같은 이벤트를 디스패치합니다. 또한 현재 세션 기록 단계를 대상 단계인 1로 업데이트합니다.

최종 결과는 다음과 같습니다:

0 1
top /t
frames[0] /i-0-a /i-0-a#foo
frames[1] /i-1-a
7.4.1.4 세션 기록에 대한 저수준 작업

이 섹션은 세션 기록을 조작할 때 표준 전체에서 수행하는 다양한 작업들을 포함하고 있습니다. 이들이 무엇을 하는지 파악하는 가장 좋은 방법은 호출 위치를 살펴보는 것입니다.

세션 기록 항목 가져오기을 위해 navigable navigable을 호출합니다:

  1. navigabletraversable navigabletraversable로 설정합니다.

  2. 단언: 이 작업은 traversable세션 기록 탐색 큐 내에서 실행됩니다.

  3. navigabletraversable인 경우, traversable세션 기록 항목을 반환합니다.

  4. docStates를 빈 정렬된 세트로 설정하고, 문서 상태를 추가합니다.

  5. traversable세션 기록 항목에서 각 entry에 대해, 추가entry문서 상태docStates에 추가합니다.

  6. docState에 대해:

    1. nestedHistory에 대해 docState중첩된 기록을 가져옵니다:

      1. nestedHistoryidnavigableid와 동일하면 nestedHistory항목을 반환합니다.

      2. nestedHistory항목에서 각 entry에 대해, 추가entry문서 상태docStates에 추가합니다.

  7. 단언: 이 단계는 도달하지 않습니다.

네비게이션 API를 위한 세션 기록 항목 가져오기을 위해 navigable navigable에 대해 targetStep을 호출합니다:

  1. navigable에 대해 세션 기록 항목 가져오기의 결과를 rawEntries로 설정합니다.

  2. entriesForNavigationAPI를 빈 목록으로 설정합니다.

  3. targetStep보다 작거나 같은 가장 큰 단계를 가진 rawEntries세션 기록 항목의 인덱스를 startingIndex로 설정합니다.

    이 예제를 참조하여 왜 targetStep보다 작거나 같은 가장 큰 단계인지 이해할 수 있습니다.

  4. 추가rawEntries[startingIndex]를 entriesForNavigationAPI에 추가합니다.

  5. rawEntries[startingIndex]의 문서 상태출처startingOrigin으로 설정합니다.

  6. istartingIndex − 1로 설정합니다.

  7. i > 0일 때:

    1. rawEntries[i]의 문서 상태출처startingOrigin같은 출처가 아니라면, 중단합니다.

    2. 앞에 추가rawEntries[i]를 entriesForNavigationAPI에 추가합니다.

    3. ii − 1로 설정합니다.

  8. istartingIndex + 1로 설정합니다.

  9. i < rawEntries크기일 때:

    1. rawEntries[i]의 문서 상태출처startingOrigin같은 출처가 아니라면, 중단합니다.

    2. 추가rawEntries[i]를 entriesForNavigationAPI에 추가합니다.

    3. ii + 1로 설정합니다.

  10. entriesForNavigationAPI를 반환합니다.

앞으로의 세션 기록 지우기을 위해 traversable navigable navigable에 대해 호출합니다:

  1. 단언: 이 작업은 navigable세션 기록 탐색 큐 내에서 실행됩니다.

  2. navigable현재 세션 기록 단계step으로 설정합니다.

  3. entryLists정렬된 세트 «navigable세션 기록 항목»으로 설정합니다.

  4. entryList에 대해:

    1. 제거step보다 큰 세션 기록 항목entryList에서 제거합니다.

    2. entry에 대해:

      1. entry문서 상태중첩된 기록nestedHistoryentryLists에 추가합니다.

모든 사용된 기록 단계 가져오기을 위해 traversable navigable traversable에 대해 호출합니다:

  1. 단언: 이 작업은 traversable세션 기록 탐색 큐 내에서 실행됩니다.

  2. steps를 빈 정렬된 세트로 설정하고, 비음수가 아닌 정수를 포함합니다.

  3. entryLists정렬된 세트 «traversable세션 기록 항목»으로 설정합니다.

  4. entryList에 대해:

    1. entry에 대해:

      1. 추가entry단계steps에 추가합니다.

      2. entry문서 상태중첩된 기록nestedHistoryentryLists에 추가합니다.

  5. steps를 반환합니다. 오름차순으로 정렬된 상태로.

Certain actions cause a navigable to navigate to a new resource.

For example, following a hyperlink, form submission, and the window.open() and location.assign() methods can all cause navigation.

Although in this standard the word "navigation" refers specifically to the navigate algorithm, this doesn't always line up with web developer or user perceptions. For example:

Before we can jump into the navigation algorithm itself, we need to establish several important structures that it uses.

The source snapshot params struct is used to capture data from a Document initiating a navigation. It is snapshotted at the beginning of a navigation and used throughout the navigation's lifetime. It has the following items:

has transient activation
a boolean
sandboxing flags
a sandboxing flag set
allows downloading
a boolean
fetch client
an environment settings object, only to be used as a request client
source policy container
a policy container

To snapshot source snapshot params given a Document sourceDocument, return a new source snapshot params with

has transient activation
true if sourceDocument's relevant global object has transient activation; otherwise false
sandboxing flags
sourceDocument's active sandboxing flag set
allows downloading
false if sourceDocument's active sandboxing flag set has the sandboxed downloads browsing context flag set; otherwise true
fetch client
sourceDocument's relevant settings object
source policy container
sourceDocument's policy container

The target snapshot params struct is used to capture data from a navigable being navigated. Like source snapshot params, it is snapshotted at the beginning of a navigation and used throughout the navigation's lifetime. It has the following items:

sandboxing flags
a sandboxing flag set

To snapshot target snapshot params given a navigable targetNavigable, return a new target snapshot params with sandboxing flags set to the result of determining the creation sandboxing flags given targetNavigable's active browsing context and targetNavigable's container.


Much of the navigation process is concerned with determining how to create a new Document, which ultimately happens in the create and initialize a Document object algorithm. The parameters to that algorithm are tracked via a navigation params struct, which has the following items:

id
null or a navigation ID
navigable
the navigable to be navigated
request
null or a request that started the navigation
response
a response that ultimately was navigated to (potentially a network error)
fetch controller
null or a fetch controller
commit early hints
null or an algorithm accepting a Document, once it has been created
COOP enforcement result
a cross-origin opener policy enforcement result, used for reporting and potentially for causing a browsing context group switch
reserved environment
null or an environment reserved for the new Document
origin
an origin to use for the new Document
policy container
a policy container to use for the new Document
final sandboxing flag set
a sandboxing flag set to impose on the new Document
cross-origin opener policy
a cross-origin opener policy to use for the new Document
navigation timing type
a NavigationTimingType used for creating the navigation timing entry for the new Document
about base URL
a URL or null used to populate the new Document's about base URL

Once a navigation params struct is created, this standard does not mutate any of its items. They are only passed onward to other algorithms.


A navigation ID is a UUID string generated during navigation. It is used to interface with the WebDriver BiDi specification as well as to track the ongoing navigation. [WEBDRIVERBIDI]


After Document creation, the relevant traversable navigable's session history gets updated. The NavigationHistoryBehavior enumeration is used to indicate the desired type of session history update to the navigate algorithm. It is one of the following:

"push"
A regular navigation which adds a new session history entry, and will clear the forward session history.
"replace"
A navigation that will replace the active session history entry.
"auto"
The default value, which will be converted very early in the navigate algorithm into "push" or "replace". Usually it becomes "push", but under certain circumstances it becomes "replace" instead.

A history handling behavior is a NavigationHistoryBehavior that is either "push" or "replace", i.e., that has been resolved away from any initial "auto" value.

The navigation must be a replace, given a URL url and a Document document, if any of the following are true:

Other cases that often, but not always, force a "replace" navigation are:


Various parts of the platform track whether a user is involved in a navigation. A user navigation involvement is one of the following:

"browser UI"
The navigation was initiated by the user via browser UI mechanisms.
"activation"
The navigation was initiated by the user via the activation behavior of an element.
"none"
The navigation was not initiated by the user.

For convenience at certain call sites, the user navigation involvement for an Event event is defined as follows:

  1. Assert: this algorithm is being called as part of an activation behavior definition.

  2. Assert: event's type is "click".

  3. If event's isTrusted is initialized to true, then return "activation".

  4. Return "none".

7.4.2.2 Beginning navigation

To navigate a navigable navigable to a URL url using a Document sourceDocument, with an optional POST resource, string, or null documentResource (default null), an optional response-or-null response (default null), an optional boolean exceptionsEnabled (default false), an optional NavigationHistoryBehavior historyHandling (default "auto"), an optional serialized state-or-null navigationAPIState (default null), an optional entry list or null formDataEntryList (default null), an optional referrer policy referrerPolicy (default the empty string), and an optional user navigation involvement userInvolvement (default "none"):

  1. Let cspNavigationType be "form-submission" if formDataEntryList is non-null; otherwise "other".

  2. Let sourceSnapshotParams be the result of snapshotting source snapshot params given sourceDocument.

  3. Let initiatorOriginSnapshot be sourceDocument's origin.

  4. Let initiatorBaseURLSnapshot be sourceDocument's document base URL.

  5. Let navigationId be the result of generating a random UUID. [WEBCRYPTO]

  6. If the surrounding agent is equal to navigable's active document's relevant agent, then continue these steps. Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to continue these steps.

    We do this because we are about to look at a lot of properties of navigable's active document, which are in theory only accessible over in the appropriate event loop. (But, we do not want to unconditionally queue a task, since — for example — same-event-loop fragment navigations need to take effect synchronously.)

    Another implementation strategy would be to replicate the relevant information across event loops, or into a canonical "browser process", so that it can be consulted without queueing a task. This could give different results than what we specify here in edge cases, where the relevant properties have changed over in the target event loop but not yet been replicated. Further testing is needed to determine which of these strategies best matches browser behavior, in such racy edge cases.

  7. If navigable's active document's unload counter is greater than 0, then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url, and return.

  8. Let container be navigable's container.

  9. If container is an iframe element and will lazy load element steps given container returns true, then stop intersection-observing a lazy loading element container and set container's lazy load resumption steps to null.

  10. If the navigation must be a replace given url and navigable's active document, then set historyHandling to "replace".

  11. If navigable's parent is non-null, then set navigable's is delaying load events to true.

  12. Let targetBrowsingContext be navigable's active browsing context.

  13. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.

  14. Invoke WebDriver BiDi navigation started with targetBrowsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, status is "pending", and url is url.

  15. If navigable's ongoing navigation is "traversal", then:

    1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url.

    2. Return.

    Any attempts to navigate a navigable that is currently traversing are ignored.

  16. Set the ongoing navigation for navigable to navigationId.

    This will have the effect of aborting other ongoing navigations of navigable, since at certain points during navigation changes to the ongoing navigation will cause further work to be abandoned.

  17. If url's scheme is "javascript", then:

    1. Queue a global task on the navigation and traversal task source given navigable's active window to navigate to a javascript: URL given navigable, url, historyHandling, initiatorOriginSnapshot, and cspNavigationType.

    2. Return.

  18. If all of the following are true:

    then:

    1. Let navigation be navigable's active window's navigation API.

    2. Let entryListForFiring be formDataEntryList if documentResource is a POST resource; otherwise, null.

    3. Let navigationAPIStateForFiring be navigationAPIState if navigationAPIState is not null; otherwise, StructuredSerializeForStorage(undefined).

    4. Let continue be the result of firing a push/replace/reload navigate event at navigation with navigationType set to historyHandling, isSameDocument set to false, userInvolvement set to userInvolvement, formDataEntryList set to entryListForFiring, destinationURL set to url, and navigationAPIState set to navigationAPIStateForFiring.

    5. If continue is false, then return.

    It is possible for navigations with userInvolvement of "browser UI" or initiated by a cross origin-domain sourceDocument to fire navigate events, if they go through the earlier navigate to a fragment path.

  19. In parallel, run these steps:

    1. Let unloadPromptCanceled be the result of checking if unloading is canceled for navigable's active document's inclusive descendant navigables.

    2. If unloadPromptCanceled is true, or navigable's ongoing navigation is no longer navigationId, then:

      1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url.

      2. Abort these steps.

    3. Queue a global task on the navigation and traversal task source given navigable's active window to abort a document and its descendants given navigable's active document.

    4. If url matches about:blank or is about:srcdoc, then:

      1. Set documentState's origin to initiatorOriginSnapshot.

      2. Set documentState's about base URL to initiatorBaseURLSnapshot.

    5. Let historyEntry be a new session history entry, with its URL set to url and its document state set to documentState.

    6. Let navigationParams be null.

    7. If response is non-null:

      The navigate algorithm is only supplied with a response as part of the object and embed processing models, or for processing parts of multipart/x-mixed-replace responses after the initial response.

      1. Let policyContainer be the result of determining navigation params policy container given response's URL, null, a clone of the sourceDocument's policy container, navigable's container document's policy container, and null.

      2. Let finalSandboxFlags be the union of targetSnapshotParams's sandboxing flags and policyContainer's CSP list's CSP-derived sandboxing flags.

      3. Let responseOrigin be the result of determining the origin given response's URL, finalSandboxFlags, and documentState's initiator origin.

      4. Let coop be a new cross-origin opener policy.

      5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with

        url
        response's URL
        origin
        responseOrigin
        cross-origin opener policy
        coop
      6. Set navigationParams to a new navigation params, with

        id
        navigationId
        navigable
        navigable
        request
        null
        response
        response
        fetch controller
        null
        commit early hints
        null
        COOP enforcement result
        coopEnforcementResult
        reserved environment
        null
        origin
        responseOrigin
        policy container
        policyContainer
        final sandboxing flag set
        finalSandboxFlags
        cross-origin opener policy
        coop
        navigation timing type
        "navigate"
        about base URL
        documentState's about base URL
    8. Attempt to populate the history entry's document for historyEntry, given navigable, "navigate", sourceSnapshotParams, targetSnapshotParams, navigationId, navigationParams, cspNavigationType, with allowPOST set to true and completionSteps set to the following step:

      1. Append session history traversal steps to navigable's traversable to finalize a cross-document navigation given navigable, historyHandling, and historyEntry.

7.4.2.3 Ending navigation

Although the usual cross-document navigation case will first foray into populating a session history entry with a Document, all navigations that don't get aborted will ultimately end up calling into one of the below algorithms.

7.4.2.3.1 The usual cross-document navigation case

To finalize a cross-document navigation given a navigable navigable, history handling behavior historyHandling, and session history entry historyEntry:

  1. Assert: this is running on navigable's traversable navigable's session history traversal queue.

  2. Set navigable's is delaying load events to false.

  3. If historyEntry's document is null, then return.

    This means that attempting to populate the history entry's document ended up not creating a document, as a result of e.g., the navigation being canceled by a subsequent navigation, a 204 No Content response, etc.

  4. If all of the following are true:

    then set historyEntry's document state's navigable target name to the empty string.

  5. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.

  6. Let traversable be navigable's traversable navigable.

  7. Let targetStep be null.

  8. Let targetEntries be the result of getting session history entries for navigable.

  9. If entryToReplace is null, then:

    1. Clear the forward session history of traversable.

    2. Set targetStep to traversable's current session history step + 1.

    3. Set historyEntry's step to targetStep.

    4. Append historyEntry to targetEntries.

    Otherwise:

    1. Replace entryToReplace with historyEntry in targetEntries.

    2. Set historyEntry's step to entryToReplace's step.

    3. If historyEntry's document state's origin is same origin with entryToReplace's document state's origin, then set historyEntry's navigation API key to entryToReplace's navigation API key.

    4. Set targetStep to traversable's current session history step.

  10. Apply the push/replace history step targetStep to traversable given historyHandling.

7.4.2.3.2 The javascript: URL special case

javascript: URLs have a dedicated label on the issue tracker documenting various problems with their specification.

To navigate to a javascript: URL, given a navigable targetNavigable, a URL url, a history handling behavior historyHandling, an origin initiatorOrigin, and a string cspNavigationType:

  1. Assert: historyHandling is "replace".

  2. Set the ongoing navigation for targetNavigable to null.

  3. If initiatorOrigin is not same origin-domain with targetNavigable's active document's origin, then return.

  4. Let request be a new request whose URL is url.

    This is a synthetic request solely for plumbing into the next step. It will never hit the network.

  5. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then return. [CSP]

  6. Let newDocument be the result of evaluating a javascript: URL given targetNavigable, url, and initiatorOrigin.

  7. If newDocument is null, then return.

    In this case, some JavaScript code was executed, but no new Document was created, so we will not perform a navigation.

  8. Assert: initiatorOrigin is newDocument's origin.

  9. Let entryToReplace be targetNavigable's active session history entry.

  10. Let oldDocState be entryToReplace's document state.

  11. Let documentState be a new document state with

    document
    newDocument
    history policy container
    a clone of the oldDocState's history policy container if it is non-null; null otherwise
    request referrer
    oldDocState's request referrer
    request referrer policy
    oldDocState's request referrer policy or should this be the referrerPolicy that was passed to navigate?
    initiator origin
    initiatorOrigin
    origin
    initiatorOrigin
    about base URL
    oldDocState's about base URL
    resource
    null
    ever populated
    true
    navigable target name
    oldDocState's navigable target name
  12. Let historyEntry be a new session history entry, with

    URL
    entryToReplace's URL
    document state
    documentState

    For the URL, we do not use url, i.e. the actual javascript: URL that the navigate algorithm was called with. This means javascript: URLs are never stored in session history, and so can never be traversed to.

  13. Append session history traversal steps to targetNavigable's traversable to finalize a cross-document navigation with targetNavigable, historyHandling, and historyEntry.

To evaluate a javascript: URL given a navigable targetNavigable, a URL url, and an origin newDocumentOrigin:

  1. Let urlString be the result of running the URL serializer on url.

  2. Let encodedScriptSource be the result of removing the leading "javascript:" from urlString.

  3. Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource.

  4. Let settings be targetNavigable's active document's relevant settings object.

  5. Let baseURL be settings's API base URL.

  6. Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.

  7. Let evaluationStatus be the result of running the classic script script.

  8. Let result be null.

  9. If evaluationStatus is a normal completion, and evaluationStatus.[[Value]] is a String, then set result to evaluationStatus.[[Value]].

  10. Otherwise, return null.

  11. Let response be a new response with

    URL
    targetNavigable's active document's URL
    header list
    « (`Content-Type`, `text/html;charset=utf-8`) »
    body
    the UTF-8 encoding of result, as a body

    The encoding to UTF-8 means that unpaired surrogates will not roundtrip, once the HTML parser decodes the response body.

  12. Let policyContainer be targetNavigable's active document's policy container.

  13. Let finalSandboxFlags be policyContainer's CSP list's CSP-derived sandboxing flags.

  14. Let coop be targetNavigable's active document's cross-origin opener policy.

  15. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with

    url
    url
    origin
    newDocumentOrigin
    cross-origin opener policy
    coop
  16. Let navigationParams be a new navigation params, with

    id
    navigationId
    navigable
    targetNavigable
    request
    null this will cause the referrer of the resulting Document to be null; is that correct?
    response
    response
    fetch controller
    null
    commit early hints
    null
    COOP enforcement result
    coopEnforcementResult
    reserved environment
    null
    origin
    newDocumentOrigin
    policy container
    policyContainer
    final sandboxing flag set
    finalSandboxFlags
    cross-origin opener policy
    coop
    navigation timing type
    "navigate"
    about base URL
    targetNavigable's active document's about base URL
  17. Return the result of loading an HTML document given navigationParams.

7.4.2.3.3 Fragment navigations

To navigate to a fragment given a navigable navigable, a URL url, a history handling behavior historyHandling, a user navigation involvement userInvolvement, a serialized state-or-null navigationAPIState, and a navigation ID navigationId:

  1. Let navigation be navigable's active window's navigation API.

  2. Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.

  3. If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.

  4. Let continue be the result of firing a push/replace/reload navigate event at navigation with navigationType set to historyHandling, isSameDocument set to true, userInvolvement set to userInvolvement, destinationURL set to url, and navigationAPIState set to destinationNavigationAPIState.

  5. If continue is false, then return.

  6. Let historyEntry be a new session history entry, with

    URL
    url
    document state
    navigable's active session history entry's document state
    navigation API state
    destinationNavigationAPIState
    scroll restoration mode
    navigable's active session history entry's scroll restoration mode

    For navigations peformed with navigation.navigate(), the value provided by the state option is used for the new navigation API state. (This will set it to the serialization of undefined, if no value is provided for that option.) For other fragment navigations, including user-initiated ones, the navigation API state is carried over from the previous entry.

    The classic history API state is never carried over.

  7. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.

  8. Let history be navigable's active document's history object.

  9. Let scriptHistoryIndex be history's index.

  10. Let scriptHistoryLength be history's length.

  11. If historyHandling is "push", then:

    1. Set history's state to null.

    2. Increment scriptHistoryIndex.

    3. Set scriptHistoryLength to scriptHistoryIndex + 1.

  12. Set navigable's active document's URL to url.

  13. Set navigable's active session history entry to historyEntry.

  14. Update document for history step application given navigable's active document, historyEntry, true, scriptHistoryIndex, scriptHistoryLength, and historyHandling.

    This algorithm will be called twice as a result of a single fragment navigation: once synchronously, where best-guess values scriptHistoryIndex and scriptHistoryLength are set, history.state is nulled out, and various events are fired; and once asynchronously, where the final values for index and length are set, history.state remains untouched, and no events are fired.

  15. Scroll to the fragment given navigable's active document.

    If the scrolling fails because the Document is new and the relevant ID has not yet been parsed, then the second asynchronous call to update document for history step application will take care of scrolling.

  16. Let traversable be navigable's traversable navigable.

  17. Append the following session history synchronous navigation steps involving navigable to traversable:

    1. Finalize a same-document navigation given traversable, navigable, historyEntry, entryToReplace, and historyHandling.

    2. Invoke WebDriver BiDi fragment navigated with navigable's active browsing context and a new WebDriver BiDi navigation status whose id is navigationId, url is url, and status is "complete".

To finalize a same-document navigation given a traversable navigable traversable, a navigable targetNavigable, a session history entry targetEntry, a session history entry-or-null entryToReplace, and a history handling behavior historyHandling:

This is used by both fragment navigations and by the URL and history update steps, which are the only synchronous updates to session history. By virtue of being synchronous, those algorithms are performed outside of the top-level traversable's session history traversal queue. This puts them out of sync with the top-level traversable's current session history step, so this algorithm is used to resolve conflicts due to race conditions.

  1. Assert: this is running on traversable's session history traversal queue.

  2. If targetNavigable's active session history entry is not targetEntry, then return.

  3. Let targetStep be null.

  4. Let targetEntries be the result of getting session history entries for targetNavigable.

  5. If entryToReplace is null, then:

    1. Clear the forward session history of traversable.

    2. Set targetStep to traversable's current session history step + 1.

    3. Set targetEntry's step to targetStep.

    4. Append targetEntry to targetEntries.

    Otherwise:

    1. Replace entryToReplace with targetEntry in targetEntries.

    2. Set targetEntry's step to entryToReplace's step.

    3. Set targetStep to traversable's current session history step.

  6. Apply the push/replace history step targetStep to traversable given historyHandling.

    This is done even for "replace" navigations, as it resolves race conditions across multiple synchronous navigations.

7.4.2.3.4 Non-fetch schemes and external software

The input to attempt to create a non-fetch scheme document is the non-fetch scheme navigation params struct. It is a lightweight version of navigation params which only carries parameters relevant to the non-fetch scheme navigation case. It has the following items:

id
null or a navigation ID
navigable
the navigable experiencing the navigation
URL
a URL
target snapshot sandboxing flags
the target snapshot params's sandboxing flags present during navigation
source snapshot has transient activation
a copy of the source snapshot params's has transient activation boolean present during activation
initiator origin

an origin possibly for use in a user-facing prompt to confirm the invocation of an external software package

This differs slightly from a document state's initiator origin in that a non-fetch scheme navigation params's initiator origin follows redirects up to the last fetch scheme URL in a redirect chain that ends in a non-fetch scheme URL.

navigation timing type
a NavigationTimingType used for creating the navigation timing entry for the new Document

To attempt to create a non-fetch scheme document, given a non-fetch scheme navigation params navigationParams:

  1. Let url be navigationParams's URL.
  2. Let navigable be navigationParams's navigable.
  3. If url is to be handled using a mechanism that does not affect navigable, e.g., because url's scheme is handled externally, then:

    1. Hand-off to external software given url, navigable, navigationParams's target snapshot sandboxing flags, navigationParams's source snapshot has transient activation, and navigationParams's initiator origin.

    2. Return null.

  4. Handle url by displaying some sort of inline content, e.g., an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for the given scheme. Return the result of displaying the inline content given navigable, navigationParams's id, and navigationParams's navigation timing type.

    In the case of a registered handler being used, navigate will be invoked with a new URL.

To hand-off to external software given a URL or response resource, a navigable navigable, a sandboxing flag set sandboxFlags, a boolean hasTransientActivation, and an origin initiatorOrigin user agents should:

  1. If all of the following are true:

    then return without invoking the external software package.

    Navigation inside an iframe toward external software can be seen by users as a new popup or a new top-level navigation. That's why its is allowed in sandboxed iframe only when one of allow-popups, allow-top-navigation, allow-top-navigation-by-user-activation, or allow-top-navigation-to-custom-protocols is specified.

  2. Perform the appropriate handoff of resource while attempting to mitigate the risk that this is an attempt to exploit the target software. For example, user agents could prompt the user to confirm that initiatorOrigin is to be allowed to invoke the external software in question. In particular, if hasTransientActivation is false, then the user agent should not invoke the external software package without prior user confirmation.

    For example, there could be a vulnerability in the target software's URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link.

7.4.2.4 Preventing navigation

A couple of scenarios can intervene early in the navigation process and put the whole thing to a halt. This can be especially exciting when multiple navigables are navigating at the same time, due to a session history traversal.

A navigable source is allowed by sandboxing to navigate a second navigable target, given a source snapshot params sourceSnapshotParams, if the following steps return true:

  1. If source is target, then return true.

  2. If source is an ancestor of target, then return true.

  3. If target is an ancestor of source, then:

    1. If target is not a top-level traversable, then return true.

    2. If sourceSnapshotParams's has transient activation is true, and sourceSnapshotParams's sandboxing flags's sandboxed top-level navigation with user activation browsing context flag is set, then return false.

    3. If sourceSnapshotParams's has transient activation is false, and sourceSnapshotParams's sandboxing flags's sandboxed top-level navigation without user activation browsing context flag is set, then return false.

    4. Return true.

  4. If target is a top-level traversable:

    1. If source is the one permitted sandboxed navigator of target, then return true.

    2. If sourceSnapshotParams's sandboxing flags's sandboxed navigation browsing context flag is set, then return false.

    3. Return true.

  5. If sourceSnapshotParams's sandboxing flags's sandboxed navigation browsing context flag is set, then return false.

  6. Return true.

To check if unloading is canceled for a list of navigables navigablesThatNeedBeforeUnload, given an optional traversable navigable traversable, an optional integer targetStep, and an optional user navigation involvement-or-null userInvolvementForNavigateEvent, run these steps. They return "canceled-by-beforeunload", "canceled-by-navigate", or "continue".

  1. Let documentsToFireBeforeunload be the active document of each item in navigablesThatNeedBeforeUnload.

  2. Let unloadPromptShown be false.

  3. Let finalStatus be "continue".

  4. If traversable was given, then:

    1. Assert: targetStep and userInvolvementForNavigateEvent were given.

    2. Let targetEntry be the result of getting the target history entry given traversable and targetStep.

    3. If targetEntry is not traversable's current session history entry, and targetEntry's document state's origin is the same as traversable's current session history entry's document state's origin, then:

      In this case, we're going to fire the navigate event for traversable here. Because under some circumstances it might be canceled, we need to do this separately from other traversal navigate events, which happen later.

      Additionally, because we want beforeunload events to fire before navigate events, this means we need to fire beforeunload for traversable here (if applicable), instead of doing it as part of the below loop over documentsToFireBeforeunload.

      1. Assert: userInvolvementForNavigateEvent is not null.

      2. Let eventsFired be false.

      3. Let needsBeforeunload be true if navigablesThatNeedBeforeUnload contains traversable; otherwise false.

      4. If needsBeforeunload is true, then remove traversable's active document from documentsToFireBeforeunload.

      5. Queue a global task on the navigation and traversal task source given traversable's active window to perform the following steps:

        1. If needsBeforeunload is true, then:

          1. Let (unloadPromptShownForThisDocument, unloadPromptCanceledByThisDocument) be the result of running the steps to fire beforeunload given traversable's active document and false.

          2. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true.

          3. If unloadPromptCanceledByThisDocument is true, then set finalStatus to "canceled-by-beforeunload".

        2. If finalStatus is "canceled-by-beforeunload", then abort these steps.

        3. Let navigation be traversable's active window's navigation API.

        4. Let navigateEventResult be the result of firing a traverse navigate event at navigation given targetEntry and userInvolvementForNavigateEvent.

        5. If navigateEventResult is false, then set finalStatus to "canceled-by-navigate".

        6. Set eventsFired to true.

      6. Wait until eventsFired is true.

      7. If finalStatus is not "continue", then return finalStatus.

  5. Let totalTasks be the size of documentsThatNeedBeforeunload.

  6. Let completedTasks be 0.

  7. For each document of documents, queue a global task on the navigation and traversal task source given document's relevant global object to run the steps:

    1. Let (unloadPromptShownForThisDocument, unloadPromptCanceledByThisDocument) be the result of running the steps to fire beforeunload given document and unloadPromptShown.

    2. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true.

    3. If unloadPromptCanceledByThisDocument is true, then set finalStatus to "canceled-by-beforeunload".

    4. Increment completedTasks.

  8. Wait for completedTasks to be totalTasks.

  9. Return finalStatus.

The steps to fire beforeunload given a Document document and a boolean unloadPromptShown are:

  1. Let unloadPromptCanceled be false.

  2. Increase the document's unload counter by 1.

  3. Increase document's relevant agent's event loop's termination nesting level by 1.

  4. Let eventFiringResult be the result of firing an event named beforeunload at document's relevant global object, using BeforeUnloadEvent, with the cancelable attribute initialized to true.

  5. Decrease document's relevant agent's event loop's termination nesting level by 1.

  6. If all of the following are true:

    then:

    1. Set unloadPromptShown to true.

    2. Invoke WebDriver BiDi user prompt opened with document's relevant global object, "beforeunload", and "".

    3. Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response.

      The message shown to the user is not customizable, but instead determined by the user agent. In particular, the actual value of the returnValue attribute is ignored.

    4. If the user did not confirm the page navigation, set unloadPromptCanceled to true.

    5. Invoke WebDriver BiDi user prompt closed with document's relevant global object and true if unloadPromptCanceled is false or false otherwise.

  7. Decrease document's unload counter by 1.

  8. Return (unloadPromptShown, unloadPromptCanceled).

7.4.2.5 Aborting navigation

Each navigable has an ongoing navigation, which is a navigation ID, "traversal", or null, initially null. It is used to track navigation aborting and to prevent any navigations from taking place during traversal.

To set the ongoing navigation for a navigable navigable to newValue:

  1. If navigable's ongoing navigation is equal to newValue, then return.

  2. Inform the navigation API about aborting navigation given navigable.

  3. Set navigable's ongoing navigation to newValue.

7.4.3 Reloading and traversing

To reload a navigable navigable given an optional serialized state-or-null navigationAPIState (default null) and an optional user navigation involvement userInvolvement (default "none"):

  1. If userInvolvement is not "browser UI", then:

    1. Let navigation be navigable's active window's navigation API.

    2. Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.

    3. If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.

    4. Let continue be the result of firing a push/replace/reload navigate event at navigation with navigationType set to "reload", isSameDocument set to false, userInvolvement set to userInvolvement, destinationURL set to navigable's active session history entry's URL, and navigationAPIState set to destinationNavigationAPIState.

    5. If continue is false, then return.

  2. Set navigable's active session history entry's document state's reload pending to true.

  3. Let traversable be navigable's traversable navigable.

  4. Append the following session history traversal steps to traversable:

    1. Apply the reload history step to traversable.

To traverse the history by a delta given a traversable navigable traversable, an integer delta, and an optional Document sourceDocument:

  1. Let sourceSnapshotParams and initiatorToCheck be null.

  2. Let userInvolvement be "browser UI".

  3. If sourceDocument is given, then:

    1. Set sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument.

    2. Set initiatorToCheck to sourceDocument's node navigable.

    3. Set userInvolvement to "none".

  4. Append the following session history traversal steps to traversable:

    1. Let allSteps be the result of getting all used history steps for traversable.

    2. Let currentStepIndex be the index of traversable's current session history step within allSteps.

    3. Let targetStepIndex be currentStepIndex plus delta.

    4. If allSteps[targetStepIndex] does not exist, then abort these steps.

    5. Apply the traverse history step allSteps[targetStepIndex] to traversable, given sourceSnapshotParams, initiatorToCheck, and userInvolvement.

Apart from the navigate algorithm, session history entries can be pushed or replaced via one more mechanism, the URL and history update steps. The most well-known callers of these steps are the history.replaceState() and history.pushState() APIs, but various other parts of the standard also need to perform updates to the active history entry, and they use these steps to do so.

The URL and history update steps, given a Document document, a URL newURL, an optional serialized state-or-null serializedData (default null), and an optional history handling behavior historyHandling (default "replace"), are:

  1. Let navigable be document's node navigable.

  2. Let activeEntry be navigable's active session history entry.

  3. Let newEntry be a new session history entry, with

    URL
    newURL
    serialized state
    if serializedData is not null, serializedData; otherwise activeEntry's classic history API state
    document state
    activeEntry's document state
    scroll restoration mode
    activeEntry's scroll restoration mode
    persisted user state
    activeEntry's persisted user state
  4. If document's is initial about:blank is true, then set historyHandling to "replace".

    This means that pushState() on an initial about:blank Document behaves as a replaceState() call.

  5. Let entryToReplace be activeEntry if historyHandling is "replace", otherwise null.

  6. If historyHandling is "push", then:

    1. Increment document's history object's index.

    2. Set document's history object's length to its index + 1.

    These are temporary best-guess values for immediate synchronous access.

  7. If serializedData is not null, then restore the history object state given document and newEntry.

  8. Set document's URL to newURL.

    Since this is neither a navigation nor a history traversal, it does not cause a hashchange event to be fired.

  9. Set document's latest entry to newEntry.

  10. Set navigable's active session history entry to newEntry.

  11. Update the navigation API entries for a same-document navigation given document's relevant global object's navigation API, newEntry, and historyHandling.

  12. Let traversable be navigable's traversable navigable.

  13. Append the following session history synchronous navigation steps involving navigable to traversable:

    1. Finalize a same-document navigation given traversable, navigable, newEntry, entryToReplace, and historyHandling.

Although both fragment navigation and the URL and history update steps perform synchronous history updates, only fragment navigation contains a synchronous call to update document for history step application. The URL and history update steps instead perform a few select updates inside the above algorithm, omitting others. This is somewhat of an unfortunate historical accident, and generally leads to web-developer sadness about the inconsistency. For example, this means that popstate events fire for fragment navigations, but not for history.pushState() calls.

7.4.5 Populating a session history entry

As explained in the overview, both navigation and traversal involve creating a session history entry and then attempting to populate its document member, so that it can be presented inside the navigable.

This involves either: using an already-given response; using the srcdoc resource stored in the session history entry; or fetching. The process has several failure modes, which can either result in doing nothing (leaving the navigable on its currently-active Document) or can result in populating the session history entry with an error document.

To attempt to populate the history entry's document for a session history entry entry, given a navigable navigable, a NavigationTimingType navTimingType, a source snapshot params sourceSnapshotParams, a target snapshot params targetSnapshotParams, an optional navigation ID-or-null navigationId (default null), an optional navigation params-or-null navigationParams (default null), an optional string cspNavigationType (default "other"), an optional boolean allowPOST (default false), and optional algorithm steps completionSteps (default an empty algorithm):

  1. Assert: this is running in parallel.

  2. Assert: if navigationParams is non-null, then navigationParams's response is non-null.

  3. Let currentBrowsingContext be navigable's active browsing context.

  4. Let documentResource be entry's document state's resource.

  5. If navigationParams is null, then:

    1. If documentResource is a string, then set navigationParams to the result of creating navigation params from a srcdoc resource given entry, navigable, targetSnapshotParams, navigationId, and navTimingType.

    2. Otherwise, if all of the following are true:

      then set navigationParams to the result of creating navigation params by fetching given entry, navigable, sourceSnapshotParams, targetSnapshotParams, cspNavigationType, navigationId, and navTimingType.

    3. Otherwise, if entry's URL's scheme is not a fetch scheme, then set navigationParams to a new non-fetch scheme navigation params, with

      id
      navigationId
      navigable
      navigable
      URL
      entry's URL
      target snapshot sandboxing flags
      targetSnapshotParams's sandboxing flags
      source snapshot has transient activation
      sourceSnapshotParams's has transient activation
      initiator origin
      entry's document state's initiator origin
      navigation timing type
      navTimingType
  6. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:

    1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and abort these steps.

    2. Let saveExtraDocumentState be true.

      Usually, in the cases where we end up populating entry's document state's document, we then want to save some of the state from that Document into entry. This ensures that if there are future traversals to entry where its document has been destroyed, we can use that state when creating a new Document.

      However, in some specific cases, saving the state would be unhelpful. For those, we set saveExtraDocumentState to false later in this algorithm.

    3. If navigationParams is a non-fetch scheme navigation params, then:

      1. Set entry's document state's document to the result of running attempt to create a non-fetch scheme document given navigationParams.

        This can result in setting entry's document state's document to null, e.g., when handing-off to external software.

      2. Set saveExtraDocumentState to false.

    4. Otherwise, if any of the following are true:

      then:

      1. Set entry's document state's document to the result of creating a document for inline content that doesn't have a DOM, given navigable, null, and navTimingType. The inline content should indicate to the user the sort of error that occurred.

      2. Make document unsalvageable given entry's document state's document and "navigation-failure".

      3. Set saveExtraDocumentState to false.

      4. If navigationParams is not null, then:

        1. Run the environment discarding steps for navigationParams's reserved environment.

        2. Invoke WebDriver BiDi navigation failed with currentBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is navigationParams's response's URL.

    5. Otherwise, if navigationParams's response's status is not 204 and is not 205, then set entry's document state's document to the result of loading a document given navigationParams, sourceSnapshotParams, and entry's document state's initiator origin.

      This can result in setting entry's document state's document to null, e.g., when handing-off to external software.

    6. If entry's document state's document is not null, then:

      1. Set entry's document state's ever populated to true.

      2. If saveExtraDocumentState is true:

        1. Let document be entry's document state's document.

        2. Set entry's document state's origin to document's origin.

        3. If document's URL requires storing the policy container in history, then:

          1. Assert: navigationParams is a navigation params (i.e., neither null nor a non-fetch scheme navigation params).

          2. Set entry's document state's history policy container to navigationParams's policy container.

      3. If entry's document state's request referrer is "client", and navigationParams is a navigation params (i.e., neither null nor a non-fetch scheme navigation params), then:

        1. Assert: navigationParams's request is not null.

        2. Set entry's document state's request referrer to navigationParams's request's referrer.

    7. Run completionSteps.

To create navigation params from a srcdoc resource given a session history entry entry, a navigable navigable, a target snapshot params targetSnapshotParams, a navigation ID-or-null navigationId, and a NavigationTimingType navTimingType:

  1. Let documentResource be entry's document state's resource.

  2. Let response be a new response with

    URL
    about:srcdoc
    header list
    « (`Content-Type`, `text/html`) »
    body
    the UTF-8 encoding of documentResource, as a body
  3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, and entry's document state's origin.

  4. Let coop be a new cross-origin opener policy.

  5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with

    url
    response's URL
    origin
    responseOrigin
    cross-origin opener policy
    coop
  6. Let policyContainer be the result of determining navigation params policy container given response's URL, entry's document state's history policy container, null, navigable's container document's policy container, and null.

  7. Return a new navigation params, with

    id
    navigationId
    navigable
    navigable
    request
    null
    response
    response
    fetch controller
    null
    commit early hints
    null
    COOP enforcement result
    coopEnforcementResult
    reserved environment
    null
    origin
    responseOrigin
    policy container
    policyContainer
    final sandboxing flag set
    targetSnapshotParams's sandboxing flags
    cross-origin opener policy
    coop
    navigation timing type
    navTimingType
    about base URL
    entry's document state's about base URL

To create navigation params by fetching given a session history entry entry, a navigable navigable, a source snapshot params sourceSnapshotParams, a target snapshot params targetSnapshotParams, a string cspNavigationType, a navigation ID-or-null navigationId, and a NavigationTimingType navTimingType, perform the following steps. They return a navigation params, a non-fetch scheme navigation params, or null.

This algorithm mutates entry.

  1. Assert: this is running in parallel.

  2. Let documentResource be entry's document state's resource.

  3. Let request be a new request, with

    url
    entry's URL
    client
    sourceSnapshotParams's fetch client
    destination
    "document"
    credentials mode
    "include"
    use-URL-credentials flag
    set
    redirect mode
    "manual"
    replaces client id
    navigable's active document's relevant settings object's id
    mode
    "navigate"
    referrer
    entry's document state's request referrer
    referrer policy
    entry's document state's request referrer policy
  4. If documentResource is a POST resource, then:

    1. Set request's method to `POST`.

    2. Set request's body to documentResource's request body.

    3. Set `Content-Type` to documentResource's request content-type in request's header list.

  5. If entry's document state's reload pending is true, then set request's reload-navigation flag.

  6. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.

  7. If sourceSnapshotParams's has transient activation is true, then set request's user-activation to true.

  8. If navigable's container is non-null:

    1. If the navigable's container has a browsing context scope origin, then set request's origin to that browsing context scope origin.

    2. Set request's destination to navigable's container's local name.

    3. If sourceSnapshotParams's fetch client is navigable's container document's relevant settings object, then set request's initiator type to navigable's container's local name.

      This ensure that only container-initiated navigations are reported to resource timing.

  9. Let response be null.

  10. Let responseOrigin be null.

  11. Let fetchController be null.

  12. Let coopEnforcementResult be a new cross-origin opener policy enforcement result, with

    url
    navigable's active document's URL
    origin
    navigable's active document's origin
    cross-origin opener policy
    navigable's active document's cross-origin opener policy
    current context is navigation source
    true if navigable's active document's origin is same origin with entry's document state's initiator origin otherwise false
  13. Let finalSandboxFlags be an empty sandboxing flag set.

  14. Let responsePolicyContainer be null.

  15. Let responseCOOP be a new cross-origin opener policy.

  16. Let locationURL be null.

  17. Let currentURL be request's current URL.

  18. Let commitEarlyHints be null.

  19. While true:

    1. If request's reserved client is not null and currentURL's origin is not the same as request's reserved client's creation URL's origin, then:

      1. Run the environment discarding steps for request's reserved client.

      2. Set request's reserved client to null.

      3. Set commitEarlyHints to null.

        Preloaded links from early hint headers remain in the preload cache after a same origin redirect, but get discarded when the redirect is cross-origin.

    2. If request's reserved client is null, then:

      1. Let topLevelCreationURL be currentURL.

      2. Let topLevelOrigin be null.

      3. If navigable is not a top-level traversable, then:

        1. Let parentEnvironment be navigable's parent's active document's relevant settings object.

        2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.

        3. Set topLevelOrigin to parentEnvironment's top-level origin.

      4. Set request's reserved client to a new environment whose id is a unique opaque string, target browsing context is navigable's active browsing context, creation URL is currentURL, top-level creation URL is topLevelCreationURL, and top-level origin is topLevelOrigin.

        The created environment's active service worker is set in the Handle Fetch algorithm during the fetch if the request URL matches a service worker registration. [SW]

    3. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then set response to a network error and break. [CSP]

    4. Set response to null.

    5. If fetchController is null, then set fetchController to the result of fetching request, with processEarlyHintsResponse set to processEarlyHintsResponse as defined below, processResponse set to processResponse as defined below, and useParallelQueue set to true.

      Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:

      1. If commitEarlyHints is null, then set commitEarlyHints to the result of processing early hint headers given earlyResponse and request's reserved client.

      Let processResponse be the following algorithm given a response fetchedResponse:

      1. Set response to fetchedResponse.

    6. Otherwise, process the next manual redirect for fetchController.

      This will result in calling the processResponse we supplied above, during our first iteration through the loop, and thus setting response.

      Navigation handles redirects manually as navigation is the only place in the web platform that cares for redirects to mailto: URLs and such.

    7. Wait until either response is non-null, or navigable's ongoing navigation changes to no longer equal navigationId.

      If the latter condition occurs, then abort fetchController, and return.

      Otherwise, proceed onward.

    8. If request's body is null, then set entry's document state's resource to null.

      Fetch unsets the body for particular redirects.

    9. Set responsePolicyContainer to the result of creating a policy container from a fetch response given response and request's reserved client.

    10. Set finalSandboxFlags to the union of targetSnapshotParams's sandboxing flags and responsePolicyContainer's CSP list's CSP-derived sandboxing flags.

    11. Set responseOrigin to the result of determining the origin given response's URL, finalSandboxFlags, and entry's document state's initiator origin.

      If response is a redirect, then response's URL will be the URL that led to the redirect to response's location URL; it will not be the location URL itself.

    12. If navigable is a top-level traversable, then:

      1. Set responseCOOP to the result of obtaining a cross-origin opener policy given response and request's reserved client.

      2. Set coopEnforcementResult to the result of enforcing the response's cross-origin opener policy given navigable's active browsing context, response's URL, responseOrigin, responseCOOP, coopEnforcementResult and request's referrer.

      3. If finalSandboxFlags is not empty and responseCOOP's value is not "unsafe-none", then set response to an appropriate network error and break.

        This results in a network error as one cannot simultaneously provide a clean slate to a response using cross-origin opener policy and sandbox the result of navigating to that response.

    13. If response is not a network error, navigable is a child navigable, and the result of performing a cross-origin resource policy check with navigable's container document's origin, navigable's container document's relevant settings object, request's destination, response, and true is blocked, then set response to a network error and break.

      Here we're running the cross-origin resource policy check against the parent navigable rather than navigable itself. This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.

    14. Set locationURL to response's location URL given currentURL's fragment.

    15. If locationURL is failure or null, then break.

    16. Assert: locationURL is a URL.

    17. Set entry's classic history API state to StructuredSerializeForStorage(null).

    18. Let oldDocState be entry's document state.

    19. Set entry's document state to a new document state, with

      history policy container
      a clone of the oldDocState's history policy container if it is non-null; null otherwise
      request referrer
      oldDocState's request referrer
      request referrer policy
      oldDocState's request referrer policy
      initiator origin
      oldDocState's initiator origin
      origin
      oldDocState's origin
      about base URL
      oldDocState's about base URL
      resource
      oldDocState's resource
      ever populated
      oldDocState's ever populated
      navigable target name
      oldDocState's navigable target name

      For the navigation case, only entry referenced oldDocState, which was created early in the navigate algorithm. So for navigations, this is functionally just an update to entry's document state. For the traversal case, it's possible adjacent session history entries also reference oldDocState, in which case they will continue doing so even after we've updated entry's document state.

      oldDocState's history policy container is only ever non-null here in the traversal case, after we've populated it during a navigation to a URL that requires storing the policy container in history.

      The setup is given by the following Jake diagram:

      0 1 2 3
      top /a /a#foo /a#bar /b

      Also assume that the document state shared by the entries in steps 0, 1, and 2 has a null document, i.e., bfcache is not in play.

      Now consider the scenario where we traverse back to step 2, but this time when fetching /a, the server responds with a `Location` header pointing to /c. That is, locationURL points to /c and so we have reached this step instead of breaking out of the loop.

      In this case, we replace the document state of the session history entry occupying step 2, but we do not replace the document state of the entries occupying steps 0 and 1. The resulting Jake diagram looks like this:

      0 1 2 3
      top /a /a#foo /c#bar /b

      Note that we perform this replacement even if we end up in a redirect chain back to the original URL, for example if /c itself had a `Location` header pointing to /a. Such a case would end up like so:

      0 1 2 3
      top /a /a#foo /a#bar /b
    20. If locationURL's scheme is not an HTTP(S) scheme, then:

      1. Set entry's document state's resource to null.

      2. Break.

    21. Set currentURL to locationURL.

    22. Set entry's URL to currentURL.

    By the end of this loop we will be in one of these scenarios:

    • locationURL is failure, because of an unparseable `Location` header.

    • locationURL is null, either because response is a network error or because we successfully fetched a non-network error HTTP(S) response with no `Location` header.

    • locationURL is a URL with a non-HTTP(S) scheme.

  20. If locationURL is a URL whose scheme is not a fetch scheme, then return a new non-fetch scheme navigation params, with

    id
    navigationId
    navigable
    navigable
    URL
    locationURL
    target snapshot sandboxing flags
    targetSnapshotParams's sandboxing flags
    source snapshot has transient activation
    sourceSnapshotParams's has transient activation
    initiator origin
    responseOrigin
    navigation timing type
    navTimingType

    At this point, request's current URL is the last URL in the redirect chain with a fetch scheme before redirecting to a non-fetch scheme URL. It is this URL's origin that will be used as the initiator origin for navigations to non-fetch scheme URLs.

  21. If any of the following are true:

    then return null.

    We allow redirects to non-fetch scheme URLs, but redirects to fetch scheme URLs that aren't HTTP(S) are treated like network errors.

  22. Assert: locationURL is null and response is not a network error.

  23. Let resultPolicyContainer be the result of determining navigation params policy container given response's URL, entry's document state's history policy container, sourceSnapshotParams's source policy container, null, and responsePolicyContainer.

  24. If navigable's container is an iframe, and response's timing allow passed flag is set, then set container's pending resource-timing start time to null.

    If the iframe is allowed to report to resource timing, we don't need to run its fallback steps as the normal reporting would happen.

  25. Return a new navigation params, with

    id
    navigationId
    navigable
    navigable
    request
    request
    response
    response
    fetch controller
    fetchController
    commit early hints
    commitEarlyHints
    cross-origin opener policy
    responseCOOP
    reserved environment
    request's reserved client
    origin
    responseOrigin
    policy container
    resultPolicyContainer
    final sandboxing flag set
    finalSandboxFlags
    COOP enforcement result
    coopEnforcementResult
    navigation timing type
    navTimingType
    about base URL
    entry's document state's about base URL

An element has a browsing context scope origin if its Document's node navigable is a top-level traversable or if all of its Document's ancestor navigables all have active documents whose origins are the same origin as the element's node document's origin. If an element has a browsing context scope origin, then its value is the origin of the element's node document.

This definition is broken and needs investigation to see what it was intended to express: see issue #4703.

To load a document given navigation params navigationParams, source snapshot params sourceSnapshotParams, and origin initiatorOrigin, perform the following steps. They return a Document or null.

  1. Let type be the computed type of navigationParams's response.

  2. If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a navigable, then skip this step. Otherwise, if the type is one of the following types:

    an HTML MIME type
    Return the result of loading an HTML document, given navigationParams.
    an XML MIME type that is not an explicitly supported XML MIME type
    Return the result of loading an XML document given navigationParams and type.
    a JavaScript MIME type
    a JSON MIME type that is not an explicitly supported JSON MIME type
    "text/css"
    "text/plain"
    "text/vtt"
    Return the result of loading a text document given navigationParams and type.
    "multipart/x-mixed-replace"
    Return the result of loading a multipart/x-mixed-replace document, given navigationParams, sourceSnapshotParams, and initiatorOrigin.
    A supported image, video, or audio type
    Return the result of loading a media document given navigationParams and type.
    "application/pdf"
    "text/pdf"
    If the user agent's PDF viewer supported is true, return the result of creating a document for inline content that doesn't have a DOM given navigationParams's navigable.

    Otherwise, proceed onward.

    An explicitly supported XML MIME type is an XML MIME type for which the user agent is configured to use an external application to render the content, or for which the user agent has dedicated processing rules. For example, a web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type.

    An explicitly supported JSON MIME type is a JSON MIME type for which the user agent is configured to use an external application to render the content, or for which the user agent has dedicated processing rules.

    In both cases, the external application or user agent will either display the content inline directly in navigationParams's navigable, or hand it off to external software. Both happen in the steps below.

  3. Otherwise, the document's type is such that the resource will not affect navigationParams's navigable, e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download. Hand-off to external software given navigationParams's response, navigationParams's navigable, navigationParams's final sandboxing flag set, sourceSnapshotParams's has transient activation, and initiatorOrigin.

  4. Return null.

7.4.6 Applying the history step

For both navigation and traversal, once we have an idea of where we want to head to in the session history, much of the work comes about in applying that notion to the traversable navigable and the relevant Document. For navigations, this work generally occurs toward the end of the process; for traversals, it is the beginning.

7.4.6.1 Updating the traversable

Ensuring a traversable ends up at the right session history step is particularly complex, as it can involve coordinating across multiple navigable descendants of the traversable, populating them in parallel, and then synchronizing back up to ensure everyone has the same view of the result. This is further complicated by the existence of synchronous same-document navigations being mixed together with cross-document navigations, and how web pages have come to have certain relative timing expectations.

A changing navigable continuation state is used to store information during the apply the history step algorithm, allowing parts of the algorithm to continue only after other parts have finished. It is a struct with:

displayed document
A Document
target entry
A session history entry
navigable
A navigable
update only
A boolean

Although all updates to the traversable navigable end up in the same apply the history step algorithm, each possible entry point comes along with some minor customizations:

To update for navigable creation/destruction given a traversable navigable traversable:

  1. Let step be traversable's current session history step.

  2. Return the result of applying the history step step to traversable given false, null, null, null, and null.

To apply the push/replace history step given a non-negative integer step and a history handling behavior historyHandling to a traversable navigable traversable:

  1. Return the result of applying the history step step to traversable given false, null, null, null, and historyHandling.

Apply the push/replace history step never passes source snapshot params or an initiator navigable to apply the history step. This is because those checks are done earlier in the navigation algorithm.

To apply the reload history step to a traversable navigable traversable:

  1. Let step be traversable's current session history step.

  2. Return the result of applying the history step step to traversable given true, null, null, null, and "reload".

Apply the reload history step never passes source snapshot params or an initiator navigable to apply the history step. This is because reloading is always treated as if it were done by the navigable itself, even in cases like parent.location.reload().

To apply the traverse history step given a non-negative integer step to a traversable navigable traversable, with source snapshot params sourceSnapshotParams, navigable initiatorToCheck, and user navigation involvement userInvolvement:

  1. Return the result of applying the history step step to traversable given true, sourceSnapshotParams, initiatorToCheck, userInvolvement, and "traverse".


Now for the algorithm itself.

To apply the history step given a non-negative integer step to a traversable navigable traversable, with boolean checkForCancelation, source snapshot params-or-null sourceSnapshotParams, navigable-or-null initiatorToCheck, user navigation involvement-or-null userInvolvementForNavigateEvents, and NavigationType-or-null navigationType, perform the following steps. They return "initiator-disallowed", "canceled-by-beforeunload", "canceled-by-navigate", or "applied".

  1. Assert: This is running within traversable's session history traversal queue.

  2. Let targetStep be the result of getting the used step given traversable and step.

  3. If initiatorToCheck is not null, then:

    1. Assert: sourceSnapshotParams is not null.

    2. For each navigable of get all navigables whose current session history entry will change or reload: if initiatorToCheck is not allowed by sandboxing to navigate navigable given sourceSnapshotParams, then return "initiator-disallowed".

  4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.

  5. If checkForCancelation is true, and the result of checking if unloading is canceled given navigablesCrossingDocuments, traversable, targetStep, and userInvolvementForNavigateEvents is not "continue", then return that result.

  6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.

  7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.

  8. For each navigable of changingNavigables:

    1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.

    2. Set navigable's current session history entry to targetEntry.

    3. Set the ongoing navigation for navigable to "traversal".

  9. Let totalChangeJobs be the size of changingNavigables.

  10. Let completedChangeJobs be 0.

  11. Let changingNavigableContinuations be an empty queue of changing navigable continuation states.

    This queue is used to split the operations on changingNavigables into two parts. Specifically, changingNavigableContinuations holds data for the second part.

  12. For each navigable of changingNavigables, queue a global task on the navigation and traversal task source of navigable's active window to run the steps:

    This set of steps are split into two parts to allow synchronous navigations to be processed before documents unload. State is stored in changingNavigableContinuations for the second part.

    1. Let displayedEntry be navigable's active session history entry.

    2. Let targetEntry be navigable's current session history entry.

    3. Let changingNavigableContinuation be a changing navigable continuation state with:

      displayed document
      displayedEntry's document
      target entry
      targetEntry
      navigable
      navigable
      update-only
      false
    4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:

      1. Set changingNavigableContinuation's update-only to true.

      2. Enqueue changingNavigableContinuation on changingNavigableContinuations.

      3. Abort these steps.

      This case occurs due to a synchronous navigation which already updated the active session history entry.

    5. Switch on navigationType:

      "reload"

      Assert: targetEntry's document state's reload pending is true.

      "traverse"

      Assert: targetEntry's document state's ever populated is true.

      "replace"

      Assert: targetEntry's step is displayedEntry's step and targetEntry's document state's ever populated is false.

      "push"

      Assert: targetEntry's step is displayedEntry's step + 1 and targetEntry's document state's ever populated is false.

    6. Let oldOrigin be targetEntry's document state's origin.

    7. If all of the following are true:

      then:

      1. Assert: userInvolvementForNavigateEvents is not null.

      2. Let navigation be navigable's active window's navigation API.

      3. Fire a traverse navigate event at navigation given targetEntry and userInvolvementForNavigateEvents.

    8. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:

      1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".

      2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.

      3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.

      4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.

        In this case there is no clear source of the traversal/reload. We treat this situation as if navigable navigated itself, but note that some properties of targetEntry's original initiator are preserved in targetEntry's document state, such as the initiator origin and referrer, which will appropriately influence the navigation.

      5. Set targetEntry's document state's reload pending to false.

      6. Let allowPOST be targetEntry's document state's reload pending.

      7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams, targetSnapshotParams, with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given navigable's active window to run afterDocumentPopulated.

      Otherwise, run afterDocumentPopulated immediately.

      In both cases, let afterDocumentPopulated be the following steps:

      1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.

        This means we tried to populate the document, but were unable to do so, e.g. because of the server returning a 204.

        These kinds of failed navigations or traversals will not be signaled to the navigation API (e.g., through the promises of any navigation API method tracker, or the navigateerror event). Doing so would leak information about the timing of responses from other origins, in the cross-origin case, and providing different results in the cross-origin vs. same-origin cases was deemed too confusing.

        However, implementations could use this opportunity to clear any promise handlers for the navigation.transition.finished promise, as they are guaranteed at this point to never run. And, they might wish to report a warning to the console if any part of the navigation API initiated these navigations, to make it clear to the web developer why their promises will never settle and events will never fire.

      2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's classic history API state to StructuredSerializeForStorage(null).

        This clears history state when the origin changed vs a previous load of targetEntry without a redirect occuring. This can happen due to a change in CSP sandbox headers.

      3. If all of the following are true:

        then set targetEntry's document state's navigable target name to the empty string.

      4. Enqueue changingNavigableContinuation on changingNavigableContinuations.

        The rest of this job runs later in this algorithm.

  13. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set.

  14. While completedChangeJobs does not equal totalChangeJobs:

    1. If traversable's running nested apply history step is false, then:

      1. While traversable's session history traversal queue's algorithm set contains one or more synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation:

        1. Let steps be the first item in traversable's session history traversal queue's algorithm set that is synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation.

        2. Remove steps from traversable's session history traversal queue's algorithm set.

        3. Set traversable's running nested apply history step to true.

        4. Run steps.

        5. Set traversable's running nested apply history step to false.

        Synchronous navigations that are intended to take place before this traversal jump the queue at this point, so they can be added to the correct place in traversable's session history entries before this traversal potentially unloads their document. More details can be found here.

    2. Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations.

    3. If changingNavigableContinuation is nothing, then continue.

    4. Let displayedDocument be changingNavigableContinuation's displayed document.

    5. Let targetEntry be changingNavigableContinuation's target entry.

    6. Let navigable be changingNavigableContinuation's navigable.

    7. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.

      These values might have changed since they were last calculated.

    8. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.

      Once a navigable has reached this point in traversal, additionally queued synchronous navigation steps are likely to be intended to occur after this traversal rather than before it, so they no longer jump the queue. More details can be found here.

    9. Let entriesForNavigationAPI be the result of getting session history entries for the navigation API given navigable and targetStep.

    10. If changingNavigableContinuation's update-only is true, or targetEntry's document is displayedDocument, then:

      This is a same-document navigation: we proceed without unloading.

      1. Set the ongoing navigation for navigable to null.

        This allows new navigations of navigable to start, whereas during the traversal they were blocked.

      2. Queue a global task on the navigation and traversal task source given navigable's active window to perform afterPotentialUnloads.

    11. Otherwise:

      1. Assert: navigationType is not null.

      2. Deactivate displayedDocument, given userNavigationInvolvement, targetEntry, navigationType, and afterPotentialUnloads.

    12. In both cases, let afterPotentialUnloads be the following steps:

      1. If changingNavigableContinuation's update-only is false, then activate history entry targetEntry for navigable.

      2. Let updateDocument be an algorithm step which performs update document for history step application given targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength, scriptHistoryIndex, navigationType, entriesForNavigationAPI, and displayedEntry.

      3. If targetEntry's document is equal to displayedDocument, then perform updateDocument.

      4. Otherwise, queue a global task on the navigation and traversal task source given targetEntry's document's relevant global object to perform updateDocument.

      5. Increment completedChangeJobs.

  15. Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates.

    This step onwards deliberately waits for all the previous operations to complete, as they include processing synchronous navigations which will also post tasks to update history length and index.

  16. Let completedNonchangingJobs be 0.

  17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.

  18. For each navigable of nonchangingNavigablesThatStillNeedUpdates, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:

    1. Let document be navigable's active document.

    2. Set document's history object's index to scriptHistoryIndex.

    3. Set document's history object's length to scriptHistoryLength.

    4. Increment completedNonchangingJobs.

  19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.

  20. Set traversable's current session history step to targetStep.

  21. Return "applied".

To deactivate a document for a cross-document navigation given a Document displayedDocument, a user navigation involvement userNavigationInvolvement, a session history entry targetEntry, a NavigationType navigationType, and afterPotentialUnloads, which is an algorithm that receives no arguments:

  1. Let navigable be displayedDocument's node navigable.

  2. Let potentiallyTriggerViewTransition be false.

  3. Let isBrowserUINavigation be true if userNavigationInvolvement is "browser UI"; otherwise false.

  4. Set potentiallyTriggerViewTransition to the result of calling can navigation trigger a cross-document view-transition? given displayedDocument, targetEntry's document, navigationType, and isBrowserUINavigation.

  5. If potentiallyTriggerViewTransition is false, then:

    1. Let firePageSwapBeforeUnload be the following step:

      1. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and null.

    2. Set the ongoing navigation for navigable to null.

      This allows new navigations of navigable to start, whereas during the traversal they were blocked.

    3. Unload a document and its descendants given displayedDocument, targetEntry's document, afterPotentialUnloads, and firePageSwapBeforeUnload.

  6. Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:

    1. Let proceedWithNavigationAfterViewTransitionCapture be the following step:

      1. Append the following session history traversal steps to navigable's traversable navigable:

        1. Set the ongoing navigation for navigable to null.

          This allows new navigations of navigable to start, whereas during the traversal they were blocked.

        2. Unload a document and its descendants given displayedDocument, targetEntry's document, and afterPotentialUnloads.

    2. Let viewTransition be the result of setting up a cross-document view-transition given displayedDocument, targetEntry's document, navigationType, and proceedWithNavigationAfterViewTransitionCapture.

    3. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and viewTransition.

    4. If viewTransition is null, then run proceedWithNavigationAfterViewTransitionCapture.

      In the case where a view transition started, the view transitions algorithms are responsible for calling proceedWithNavigationAfterViewTransitionCapture.

To fire the pageswap event given a Document displayedDocument, a session history entry targetEntry, a NavigationType navigationType, and a ViewTransition-or-null viewTransition:

  1. Assert: this is running as part of a task queued on displayedDocument's relevant agent's event loop.

  2. Let navigation be displayedDocument's relevant global object's navigation API.

  3. Let activation be null.

  4. If all of the following are true:

    then:

    1. Let destinationEntry be determined by switching on navigationType:

      "reload"

      The current entry of navigation

      "traverse"

      The NavigationHistoryEntry in navigation's entry list whose session history entry is targetEntry

      "push"
      "replace"

      A new NavigationHistoryEntry in displayedDocument's relevant realm with its session history entry set to targetEntry.

    2. Set activation to a new NavigationActivation created in displayedDocument's relevant realm, with

      old entry
      the current entry of navigation
      new entry
      destinationEntry
      navigation type
      navigationType

    This means that a cross-origin redirect during a navigation would result in a null activation in the old document's PageSwapEvent, unless the new document is being restored from bfcache.

  5. Fire an event named pageswap at displayedDocument's relevant global object, using PageSwapEvent with its activation set to activation, and its viewTransition set to viewTransition.

To activate history entry session history entry entry for navigable navigable:

  1. Save persisted state to the navigable's active session history entry.

  2. Let newDocument be entry's document.

  3. Assert: newDocument's is initial about:blank is false, i.e., we never traverse back to the initial about:blank Document because it always gets replaced when we navigate away from it.

  4. Set navigable's active session history entry to entry.

  5. Make active newDocument.

To get the used step given a traversable navigable traversable, and a non-negative integer step, perform the following steps. They return a non-negative integer.

  1. Let steps be the result of getting all used history steps within traversable.

  2. Return the greatest item in steps that is less than or equal to step.

    This caters for situations where there's no session history entry with step step, due to the removal of a navigable.

To get the history object length and index given a traversable navigable traversable, and a non-negative integer step, perform the following steps. They return a tuple of two non-negative integers.

  1. Let steps be the result of getting all used history steps within traversable.

  2. Let scriptHistoryLength be the size of steps.

  3. Assert: steps contains step.

    It is assumed that step has been adjusted by getting the used step.

  4. Let scriptHistoryIndex be the index of step in steps.

  5. Return (scriptHistoryLength, scriptHistoryIndex).

To get all navigables whose current session history entry will change or reload given a traversable navigable traversable, and a non-negative integer targetStep, perform the following steps. They return a list of navigables.

  1. Let results be an empty list.

  2. Let navigablesToCheck be « traversable ».

    This list is extended in the loop below.

  3. For each navigable of navigablesToCheck:

    1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.

    2. If targetEntry is not navigable's current session history entry or targetEntry's document state's reload pending is true, then append navigable to results.

    3. If targetEntry's document is navigable's document, and targetEntry's document state's reload pending is false, then extend navigablesToCheck with the child navigables of navigable.

      Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. Child navigables are only checked if the navigable's active document will not change as part of this traversal.

  4. Return results.

To get all navigables that only need history object length/index update given a traversable navigable traversable, and a non-negative integer targetStep, perform the following steps. They return a list of navigables.

Other navigables might not be impacted by the traversal. For example, if the response is a 204, the currently active document will remain. Additionally, going 'back' after a 204 will change the current session history entry, but the active session history entry will already be correct.

  1. Let results be an empty list.

  2. Let navigablesToCheck be « traversable ».

    This list is extended in the loop below.

  3. For each navigable of navigablesToCheck:

    1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.

    2. If targetEntry is navigable's current session history entry and targetEntry's document state's reload pending is false, then:

      1. Append navigable to results.

      2. Extend navigablesToCheck with navigable's child navigables.

        Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. child navigables are only checked if the navigable's active document will not change as part of this traversal.

  4. Return results.

To get the target history entry given a navigable navigable, and a non-negative integer step, perform the following steps. They return a session history entry.

  1. Let entries be the result of getting session history entries for navigable.

  2. Return the item in entries that has the greatest step less than or equal to step.

To see why getting the target history entry returns the entry with the greatest step less than or equal to the input step, consider the following Jake diagram:

0 1 2 3
top /t /t#foo
frames[0] /i-0-a /i-0-b

For the input step 1, the target history entry for the top navigable is the /t entry, whose step is 0, while the target history entry for the frames[0] navigable is the /i-0-b entry, whose step is 1:

0 1 2 3
top /t /t#foo
frames[0] /i-0-a /i-0-b

Similarly, given the input step 3 we get the top entry whose step is 3, and the frames[0] entry whose step is 1:

0 1 2 3
top /t /t#foo
frames[0] /i-0-a /i-0-b

To get all navigables that might experience a cross-document traversal given a traversable navigable traversable, and a non-negative integer targetStep, perform the following steps. They return a list of navigables.

From traversable's session history traversal queue's perspective, these documents are candidates for going cross-document during the traversal described by targetStep. They will not experience a cross-document traversal if the status code for their target document is HTTP 204 No Content.

Note that if a given navigable might experience a cross-document traversal, this algorithm will return navigable but not its child navigables. Those would end up unloaded, not traversed.

  1. Let results be an empty list.

  2. Let navigablesToCheck be « traversable ».

    This list is extended in the loop below.

  3. For each navigable of navigablesToCheck:

    1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.

    2. If targetEntry's document is not navigable's document or targetEntry's document state's reload pending is true, then append navigable to results.

      Although navigable's active history entry can change synchronously, the new entry will always have the same Document, so accessing navigable's document is reliable.

    3. Otherwise, extend navigablesToCheck with navigable's child navigables.

      Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. Child navigables are only checked if the navigable's active document will not change as part of this traversal.

  4. Return results.

7.4.6.2 Updating the document

To update document for history step application given a Document document, a session history entry entry, a boolean doNotReactivate, integers scriptHistoryLength and scriptHistoryIndex, NavigationType-or-null navigationType, an optional list of session history entries entriesForNavigationAPI, and an optional session history entry previousEntryForActivation:

  1. Let documentIsNew be true if document's latest entry is null; otherwise false.

  2. Let documentsEntryChanged be true if document's latest entry is not entry; otherwise false.

  3. Set document's history object's index to scriptHistoryIndex.

  4. Set document's history object's length to scriptHistoryLength.

  5. Let navigation be history's relevant global object's navigation API.

  6. If documentsEntryChanged is true, then:

    1. Let oldURL be document's latest entry's URL.

    2. Set document's latest entry to entry.

    3. Restore the history object state given document and entry.

    4. If documentIsNew is false, then:

      1. Assert: navigationType is not null.

      2. Update the navigation API entries for a same-document navigation given navigation, entry, and navigationType.

      3. Fire an event named popstate at document's relevant global object, using PopStateEvent, with the state attribute initialized to document's history object's state and hasUAVisualTransition initialized to true if a visual transition, to display a cached rendered state of the latest entry, was done by the user agent.

      4. Restore persisted state given entry.

      5. If oldURL's fragment is not equal to entry's URL's fragment, then queue a global task on the DOM manipulation task source given document's relevant global object to fire an event named hashchange at document's relevant global object, using HashChangeEvent, with the oldURL attribute initialized to the serialization of oldURL and the newURL attribute initialized to the serialization of entry's URL.

    5. Otherwise:

      1. Assert: entriesForNavigationAPI is given.

      2. Restore persisted state given entry.

      3. Initialize the navigation API entries for a new document given navigation, entriesForNavigationAPI, and entry.

  7. If all the following are true:

    then:

    1. If navigation's activation is null, then set navigation's activation to a new NavigationActivation object in navigation's relevant realm.

    2. Let previousEntryIndex be the result of getting the navigation API entry index of previousEntryForActivation within navigation.

    3. If previousEntryIndex is non-negative, then set activation's old entry to navigation's entry list[previousEntryIndex].

    4. Otherwise, if all the following are true:

      then set activation's old entry to a new NavigationHistoryEntry in navigation's relevant realm, whose session history entry is previousEntryForActivation.

    5. Set activation's new entry to navigation's current entry.

    6. Set activation's navigation type to navigationType.

  8. If documentIsNew is true, then:

    1. Try to scroll to the fragment for document.

    2. At this point scripts may run for the newly-created document document.

  9. Otherwise, if documentsEntryChanged is false and doNotReactivate is false, then:

    1. Assert: entriesForNavigationAPI is given.

    2. Reactivate document given entry and entriesForNavigationAPI.

    documentsEntryChanged can be false for one of two reasons: either we are restoring from bfcache, or we are asynchronously finishing up a synchronous navigation which already synchronously set document's latest entry. The doNotReactivate argument distinguishes between these two cases.

To restore the history object state given Document document and session history entry entry:

  1. Let targetRealm be document's relevant realm.

  2. Let state be StructuredDeserialize(entry's classic history API state, targetRealm). If this throws an exception, catch it and let state be null.

  3. Set document's history object's state to state.

To make active a Document document:

  1. Let window be document's relevant global object.

  2. Set document's browsing context's WindowProxy's [[Window]] internal slot value to window.

  3. Set document's visibility state to document's node navigable's traversable navigable's system visibility state.

  4. Queue a new VisibilityStateEntry whose visibility state is document's visibility state and whose timestamp is zero.

  5. Set window's relevant settings object's execution ready flag.

To reactivate a Document document given a session history entry reactivatedEntry and a list of session history entries entriesForNavigationAPI:

This algorithm updates document after it has come out of bfcache, i.e., after it has been made fully active again. Other specifications that want to watch for this change to the fully active state are encouraged to add steps into this algorithm, so that the ordering of events that happen in effect of the change is clear.

  1. For each formControl of form controls in document with an autofill field name of "off", invoke the reset algorithm for formControl.

  2. If document's suspended timer handles is not empty:

    1. Assert: document's suspension time is not zero.

    2. Let suspendDuration be the current high resolution time minus document's suspension time.

    3. Let activeTimers be document's relevant global object's map of active timers.

    4. For each handle in document's suspended timer handles, if activeTimers[handle] exists, then increase activeTimers[handle] by suspendDuration.

  3. Update the navigation API entries for reactivation given document's relevant global object's navigation API, entriesForNavigationAPI, and reactivatedEntry.

  4. If document's current document readiness is "complete", and document's page showing flag is false, then:

    1. Set document's page showing flag to true.

    2. Set document's has been revealed to false.

    3. Update the visibility state of document to "visible".

    4. Fire a page transition event named pageshow at document's relevant global object with true.

To try to scroll to the fragment for a Document document, perform the following steps in parallel:

  1. Wait for an implementation-defined amount of time. (This is intended to allow the user agent to optimize the user experience in the face of performance concerns.)

  2. Queue a global task on the navigation and traversal task source given document's relevant global object to run these steps:

    1. If document has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment, then abort these steps.

    2. Scroll to the fragment given document.

    3. If document's indicated part is still null, then try to scroll to the fragment for document.

To make document unsalvageable, given a Document document and a string reason:

  1. Let details be a new not restored reason details whose reason is reason.

  2. Append details to document's bfcache blocking details.

  3. Set document's salvageable state to false.

To build not restored reasons for document state given Document document:

  1. Let notRestoredReasonsForDocument be a new not restored reasons.

  2. Set notRestoredReasonsForDocument's URL to document's URL.

  3. If document's node navigable's container is an iframe element, then:

    1. Set notRestoredReasonsForDocument's src to the value of document's node navigable's container's src attribute.

    2. Set notRestoredReasonsForDocument's id to the value of document's node navigable's container's id attribute.

    3. Set notRestoredReasonsForDocument's name to the value of document's node navigable's container's name attribute.

  4. Set notRestoredReasonsForDocument's reasons to a clone of document's bfcache blocking details.

  5. For each navigable of document's document-tree child navigables:

    1. Let childDocument be navigable's active document.

    2. Build not restored reasons for document state given childDocument.

    3. Append childDocument's not restored reasons to notRestoredReasonsForDocument's children.

  6. Set document's node navigable's active session history entry's document state's not restored reasons to notRestoredReasonsForDocument.

To build not restored reasons for a top-level traversable and its descendants given top-level traversable topLevelTraversable:

  1. Build not restored reasons for document state given topLevelTraversable's active document.

  2. Let crossOriginDescendants be an empty list.

  3. For each childNavigable of topLevelTraversable's active document's descendant navigables:

    1. If childNavigable's active document's origin is not same origin with topLevelTraversable's active document's origin, then append childNavigable to crossOriginDescendants.

  4. Let crossOriginDescendantsPreventsBfcache be false.

  5. For each crossOriginNavigable of crossOriginDescendants:

    1. Let reasonsForCrossOriginChild be crossOriginNavigable's active document's document state's not restored reasons.

    2. If reasonsForCrossOriginChild's reasons is not empty, set crossOriginDescendantsPreventsBfcache to true.

    3. Set reasonsForCrossOriginChild's URL to null.

    4. Set reasonsForCrossOriginChild's reasons to null.

    5. Set reasonsForCrossOriginChild's children to null.

  6. If crossOriginDescendantsPreventsBfcache is true, make document unsalvageable given topLevelTraversable's active document and "masked".

7.4.6.3 Revealing the document

A Document has a boolean has been revealed, initially false. It is used to ensure that the pagereveal event is fired once for each activation of the Document (once when it's rendered initially, and once for each reactivation).

To reveal a Document document:

  1. If document's has been revealed is true, then return.

  2. Set document's has been revealed to true.

  3. Let transition be the result of resolving inbound cross-document view-transition for document.

  4. Fire an event named pagereveal at document's relevant global object, using PageRevealEvent with its viewTransition set to transition.

  5. If transition is not null, then:

    1. Prepare to run script given document.

    2. Activate transition.

    3. Clean up after running script given document.

    Activating a view transition might resolve/reject promises, so by wrapping the activation with prepare/cleanup we ensure those promises are handled before the next rendering step.

Though pagereveal is guaranteed to be fired during the first update the rendering step that displays an up-to-date version of the page, user agents are free to display a cached frame of the page before firing it. This prevents the presence of a pagereveal handler from delaying the presentation of such cached frame.

7.4.6.4 Scrolling to a fragment

To scroll to the fragment given a Document document:

  1. If document's indicated part is null, then set document's target element to null.

  2. Otherwise, if document's indicated part is top of the document, then:

    1. Set document's target element to null.

    2. Scroll to the beginning of the document for document. [CSSOMVIEW]

    3. Return.

  3. Otherwise:

    1. Assert: document's indicated part is an element.

    2. Let target be document's indicated part.

    3. Set document's target element to target.

    4. Run the ancestor details revealing algorithm on target.

    5. Run the ancestor hidden-until-found revealing algorithm on target.

    6. Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW]

    7. Run the focusing steps for target, with the Document's viewport as the fallback target.

    8. Move the sequential focus navigation starting point to target.

A Document's indicated part is the one that its URL's fragment identifies, or null if the fragment does not identify anything. The semantics of the fragment in terms of mapping it to a node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragments for XML MIME types is the responsibility of RFC7303). [RFC7303]

There is also a target element for each Document, which is used in defining the :target pseudo-class and is updated by the above algorithm. It is initially null.

For an HTML document document, its indicated part is the result of selecting the indicated part given document and document's URL.

To select the indicated part given a Document document and a URL url:

  1. If document's URL does not equal url with exclude fragments set to true, then return null.

  2. Let fragment be url's fragment.

  3. If fragment is the empty string, then return the special value top of the document.

  4. Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment.

  5. If potentialIndicatedElement is not null, then return potentialIndicatedElement.

  6. Let fragmentBytes be the result of percent-decoding fragment.

  7. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.

  8. Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment.

  9. If potentialIndicatedElement is not null, then return potentialIndicatedElement.

  10. If decodedFragment is an ASCII case-insensitive match for the string top, then return the top of the document.

  11. Return null.

To find a potential indicated element given a Document document and a string fragment, run these steps:

  1. If there is an element in the document tree whose root is document and that has an ID equal to fragment, then return the first such element in tree order.

  2. If there is an a element in the document tree whose root is document that has a name attribute whose value is equal to fragment, then return the first such element in tree order.

  3. Return null.

7.4.6.5 Persisted history entry state

To save persisted state to a session history entry entry:

  1. Set the scroll position data of entry to contain the scroll positions for all of entry's document's restorable scrollable regions.

  2. Optionally, update entry's persisted user state to reflect any state that the user agent wishes to persist, such as the values of form fields.

To restore persisted state from a session history entry entry:

  1. If entry's scroll restoration mode is "auto", and entry's document's relevant global object's navigation API's suppress normal scroll restoration during ongoing navigation is false, then restore scroll position data given entry.

    The user agent not restoring scroll positions does not imply that scroll positions will be left at any particular value (e.g., (0,0)). The actual scroll position depends on the navigation type and the user agent's particular caching strategy. So web applications cannot assume any particular scroll position but rather are urged to set it to what they want it to be.

    If suppress normal scroll restoration during ongoing navigation is true, then restoring scroll position data might still happen at a later point, as part of finishing the relevant NavigateEvent, or via a navigateEvent.scroll() method call.

  2. Optionally, update other aspects of entry's document and its rendering, for instance values of form fields, that the user agent had previously recorded in entry's persisted user state.

    This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in the Text, Search, Telephone, URL, or Email state, if the persisted state includes the directionality of user input in such controls.

    Restoring the value of form controls as part of this process does not fire any input or change events, but can trigger the formStateRestoreCallback of form-associated custom elements.


Each Document has a boolean has been scrolled by the user, initially false. If the user scrolls the document, the user agent must set that document's has been scrolled by the user to true.

The restorable scrollable regions of a Document document are document's viewport, and all of document's scrollable regions excepting any navigable containers.

Child navigable scroll restoration is handled as part of state restoration for the session history entry for those navigables' Documents.

To restore scroll position data given a session history entry entry:

  1. Let document be entry's document.

  2. If document's has been scrolled by the user is true, then the user agent should return.

  3. The user agent should attempt to use entry's scroll position data to restore the scroll positions of entry's document's restorable scrollable regions. The user agent may continue to attempt to do so periodically, until document's has been scrolled by the user becomes true.

    This is formulated as an attempt, which is potentially repeated until success or until the user scrolls, due to the fact that relevant content indicated by the scroll position data might take some time to load from the network.

    Scroll restoration might be affected by scroll anchoring. [CSSSCROLLANCHORING]

7.5 Document lifecycle

7.5.1 Shared document creation infrastructure

When loading a document using one of the below algorithms, we use the following steps to create and initialize a Document object, given a type type, content type contentType, and navigation params navigationParams:

Document objects are also created when creating a new browsing context and document; such initial about:blank Document are never created by this algorithm. Also, browsing context-less Document objects can be created via various APIs, such as document.implementation.createHTMLDocument().

  1. Let browsingContext be navigationParams's navigable's active browsing context.

  2. Set browsingContext to the result of the obtaining a browsing context to use for a navigation response given browsingContext, navigationParams's final sandboxing flag set, navigationParams's cross-origin opener policy, and navigationParams's COOP enforcement result.

    This can result in a browsing context group switch, in which case browsingContext will be a newly-created browsing context instead of being navigationParams's navigable's active browsing context. In such a case, the created Window, Document, and agent will not end up being used; because the created Document's origin is opaque, we will end up creating a new agent and Window later in this algorithm to go along with the new Document.

  3. Let permissionsPolicy be the result of creating a permissions policy from a response given navigationParams's navigable's container, navigationParams's origin, and navigationParams's response. [PERMISSIONSPOLICY]

    The creating a permissions policy from a response algorithm makes use of the passed origin. If document.domain has been used for navigationParams's navigable's container document, then its origin cannot be same origin-domain with the passed origin, because these steps run before the document is created, so it cannot itself yet have used document.domain. Note that this means that Permissions Policy checks are less permissive compared to doing a same origin check instead.

    See below for some examples of this in action.

  4. Let creationURL be navigationParams's response's URL.

  5. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.

  6. Let window be null.

  7. If browsingContext's active document's is initial about:blank is true, and browsingContext's active document's origin is same origin-domain with navigationParams's origin, then set window to browsingContext's active window.

    This means that both the initial about:blank Document, and the new Document that is about to be created, will share the same Window object.

  8. Otherwise:

    1. Let oacHeader be the result of getting a structured field value given `Origin-Agent-Cluster` and "item" from navigationParams's response's header list.

    2. Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.

    3. If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.

    4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.

    5. Let realmExecutionContext be the result of creating a new realm given agent and the following customizations:

      • For the global object, create a new Window object.

      • For the global this binding, use browsingContext's WindowProxy object.

    6. Set window to the global object of realmExecutionContext's Realm component.

    7. Let topLevelCreationURL be creationURL.

    8. Let topLevelOrigin be navigationParams's origin.

    9. If navigable's container is not null, then:

      1. Let parentEnvironment be navigable's container's relevant settings object.

      2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.

      3. Set topLevelOrigin to parentEnvironment's top-level origin.

    10. Set up a window environment settings object with creationURL, realmExecutionContext, navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.

    This is the usual case, where the new Document we're about to create gets a new Window to go along with it.

  9. Let loadTimingInfo be a new document load timing info with its navigation start time set to navigationParams's response's timing info's start time.

  10. Let document be a new Document, with

    type
    type
    content type
    contentType
    origin
    navigationParams's origin
    browsing context
    browsingContext
    policy container
    navigationParams's policy container
    permissions policy
    permissionsPolicy
    active sandboxing flag set
    navigationParams's final sandboxing flag set
    cross-origin opener policy
    navigationParams's cross-origin opener policy
    load timing info
    loadTimingInfo
    was created via cross-origin redirects
    navigationParams's response's has cross-origin redirects
    during-loading navigation ID for WebDriver BiDi
    navigationParams's id
    URL
    creationURL
    current document readiness
    "loading"
    about base URL
    navigationParams's about base URL
    allow declarative shadow roots
    true
  11. Set window's associated Document to document.

  12. Run CSP initialization for a Document given document. [CSP]

  13. If navigationParams's request is non-null, then:

    1. Set document's referrer to the empty string.

    2. Let referrer be navigationParams's request's referrer.

    3. If referrer is a URL record, then set document's referrer to the serialization of referrer.

      Per Fetch, referrer will be either a URL record or "no-referrer" at this point.

  14. If navigationParams's fetch controller is not null, then:

    1. Let fullTimingInfo be the result of extracting the full timing info from navigationParams's fetch controller.

    2. Let redirectCount be 0 if navigationParams's response's has cross-origin redirects is true; otherwise navigationParams's request's redirect count.

    3. Create the navigation timing entry for document, given fullTimingInfo, redirectCount, navigationTimingType, navigationParams's response's service worker timing info, and navigationParams's response's body info.

  15. Create the navigation timing entry for document, with navigationParams's response's timing info, redirectCount, navigationParams's navigation timing type, and navigationParams's response's service worker timing info.

  16. If navigationParams's response has a `Refresh` header, then:

    1. Let value be the isomorphic decoding of the value of the header.

    2. Run the shared declarative refresh steps with document and value.

    We do not currently have a spec for how to handle multiple `Refresh` headers. This is tracked as issue #2900.

  17. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.

  18. Process link headers given document, navigationParams's response, and "pre-media".

  19. Return document.

In this example, the child document is not allowed to use PaymentRequest, despite being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, only the parent document has set document.domain, and the child document has not.

<!-- https://foo.example.com/a.html -->
<!doctype html>
<script>
document.domain = 'example.com';
</script>
<iframe src=b.html></iframe>
<!-- https://bar.example.com/b.html -->
<!doctype html>
<script>
document.domain = 'example.com'; // This happens after the document is initialized
new PaymentRequest(); // Not allowed to use
</script>

In this example, the child document is allowed to use PaymentRequest, despite not being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, none of the documents have set document.domain yet so same origin-domain falls back to a normal same origin check.

<!-- https://example.com/a.html -->
<!doctype html>
<iframe src=b.html></iframe>
<!-- The child document is now initialized, before the script below is run. -->
<script>
document.domain = 'example.com';
</script>
<!-- https://example.com/b.html -->
<!doctype html>
<script>
new PaymentRequest(); // Allowed to use
</script>

To populate with html/head/body given a Document document:

  1. Let html be the result of creating an element given document, html, and the HTML namespace.

  2. Let head be the result of creating an element given document, head, and the HTML namespace.

  3. Let body be the result of creating an element given document, body, and the HTML namespace.

  4. Append html to document.

  5. Append head to html.

  6. Append body to html.

7.5.2 Loading HTML documents

To load an HTML document, given navigation params navigationParams:

  1. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.

  2. If document's URL is about:blank, then populate with html/head/body given document.

    This special case, where even non-initial about:blank Documents are synchronously given their element nodes, is necessary for compatible with deployed content. In other words, it is not compatible to instead go down the "otherwise" branch and feed the empty byte sequence into an HTML parser to asynchronously populate document.

  3. Otherwise, create an HTML parser and associate it with the document. Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

    The first task that the networking task source places on the task queue while fetching runs must process link headers given document, navigationParams's response, and "media", after the task has been processed by the HTML parser.

    Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document.

    The input byte stream converts bytes into characters for use in the tokenizer. This process relies, in part, on character encoding information found in the real Content-Type metadata of the resource; the computed type is not used for this purpose.

    When no more bytes are available, the user agent must queue a global task on the networking task source given document's relevant global object to have the parser process the implied EOF character, which eventually causes a load event to be fired.

  4. Return document.

7.5.3 Loading XML documents

When faced with displaying an XML file inline, provided navigation params navigationParams and a string type, user agents must follow the requirements defined in XML and Namespaces in XML, XML Media Types, DOM, and other relevant specifications to create and initialize a Document object document, given "xml", type, and navigationParams, and return that Document. They must also create a corresponding XML parser. [XML] [XMLNS] [RFC7303] [DOM]

At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.

The first task that the networking task source places on the task queue while fetching runs must process link headers given document, navigationParams's response, and "media", after the task has been processed by the XML parser.

The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification, are the ones that must be used when determining the character encoding according to the rules given in the above specifications. Once the character encoding is established, the document's character encoding must be set to that character encoding.

Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for the newly-created Document.

Once parsing is complete, the user agent must set document's during-loading navigation ID for WebDriver BiDi to null.

For HTML documents this is reset when parsing is complete, after firing the load event.

Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating the Document.

7.5.4 Loading text documents

To load a text document, given a navigation params navigationParams and a string type:

  1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.

  2. Set document's parser cannot change the mode flag to true.

  3. Set document's mode to "no-quirks".

  4. Create an HTML parser and associate it with the document. Act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser's tokenizer to the PLAINTEXT state. Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

    document's encoding must be set to the character encoding used to decode the document during parsing.

    The first task that the networking task source places on the task queue while fetching runs must process link headers given document, navigationParams's response, and "media", after the task has been processed by the HTML parser.

    Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document.

    When no more bytes are available, the user agent must queue a global task on the networking task source given document's relevant global object to have the parser process the implied EOF character, which eventually causes a load event to be fired.

  5. User agents may add content to the head element of document, e.g., linking to a style sheet, providing script, or giving the document a title.

    In particular, if the user agent supports the Format=Flowed feature of RFC 3676 then the user agent would need to apply extra styling to cause the text to wrap correctly and to handle the quoting feature. This could be performed using, e.g., a CSS extension.

  6. Return document.

The rules for how to convert the bytes of the plain text document into actual characters, and the rules for actually rendering the text to the user, are defined by the specifications for the computed MIME type of the resource (i.e., type).

7.5.5 Loading multipart/x-mixed-replace documents

To load a multipart/x-mixed-replace document, given navigation params navigationParams, source snapshot params sourceSnapshotParams, and origin initiatorOrigin:

  1. Parse navigationParams's response's body using the rules for multipart types. [RFC2046]

  2. Let firstPartNavigationParams be a copy of navigationParams.

  3. Set firstPartNavigationParams's response to a new response representing the first part of navigationParams's response's body's multipart stream.

  4. Let document be the result of loading a document given firstPartNavigationParams, sourceSnapshotParams, and initiatorOrigin.

    For each additional body part obtained from navigationParams's response, the user agent must navigate document's node navigable to navigationParams's request's URL, using document, with response set to navigationParams's response and historyHandling set to "replace".

  5. Return document.

For the purposes of algorithms processing these body parts as if they were complete stand-alone resources, the user agent must act as if there were no more bytes for those resources whenever the boundary following the body part is reached.

Thus, load events (and for that matter unload events) do fire for each body part loaded.

7.5.6 Loading media documents

To load a media document, given navigationParams and a string type:

  1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.

  2. Set document's mode to "no-quirks".

  3. Populate with html/head/body given document.

  4. Append an element host element for the media, as described below, to the body element.

  5. Set the appropriate attribute of the element host element, as described below, to the address of the image, video, or audio resource.

  6. User agents may add content to the head element of document, or attributes to host element, e.g., to link to a style sheet, to provide a script, to give the document a title, or to make the media autoplay.

  7. Process link headers given document, navigationParams's response, and "media".

  8. Act as if the user agent had stopped parsing document.

  9. Return document.

The element host element to create for the media is the element given in the table below in the second cell of the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell in that same row.

Type of media Element for the media Appropriate attribute
Image img src
Video video src
Audio audio src

Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for the Document.

7.5.7 Loading a document for inline content that doesn't have a DOM

When the user agent is to create a document to display a user agent page or PDF viewer inline, provided a navigable navigable, a navigation ID navigationId, a NavigationTimingType navTimingType, the user agent should:

  1. Let origin be a new opaque origin.

  2. Let coop be a new cross-origin opener policy.

  3. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with

    url
    response's URL
    origin
    origin
    cross-origin opener policy
    coop
  4. Let navigationParams be a new navigation params with

    id
    navigationId
    navigable
    navigable
    request
    null
    response
    a new response
    origin
    origin
    fetch controller
    null
    commit early hints
    null
    COOP enforcement result
    coopEnforcementResult
    reserved environment
    null
    policy container
    a new policy container
    final sandboxing flag set
    an empty set
    cross-origin opener policy
    coop
    navigation timing type
    navTimingType
    about base URL
    null
  5. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.

  6. Either associate document with a custom rendering that is not rendered using the normal Document rendering rules, or mutate document until it represents the content the user agent wants to render.

  7. Return document.

Because we ensure the resulting Document's origin is opaque, and the resulting Document cannot run script with access to the DOM, the existence and properties of this Document are not observable to web developer code. This means that most of the above values, e.g., the text/html type, do not matter. Similarly, most of the items in navigationParams don't have any observable effect, besides preventing the Document-creation algorithm from getting confused, and so are set to default values.

Once the page has been set up, the user agent must act as if it had stopped parsing.

7.5.8 Finishing the loading process

A Document has a completely loaded time (a time or null), which is initially null.

A Document is considered completely loaded if its completely loaded time is non-null.

To completely finish loading a Document document:

  1. Assert: document's browsing context is non-null.

  2. Set document's completely loaded time to the current time.

  3. Let container be document's node navigable's container.

    This will be null in the case where document is the initial about:blank Document in a frame or iframe, since at the point of browsing context creation which calls this algorithm, the container relationship has not yet been established. (That happens in a subsequent step of create a new child navigable.)

    The consequence of this is that the following steps do nothing, i.e., we do not fire an asynchronous load event on the container element for such cases. Instead, a synchronous load event is fired in a special initial-insertion case when processing the iframe attributes.

  4. If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container.

  5. Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container.

7.5.9 Unloading documents

A Document has a salvageable state, which must initially be true, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g. that they never receive two pagehide events in a row without an intervening pageshow, or vice versa).

A Document has a DOMHighResTimeStamp suspension time, initially 0.

A Document has a list of suspended timer handles, initially empty.

Event loops have a termination nesting level counter, which must initially be 0.

Document objects have an unload counter, which is used to ignore certain operations while the below algorithms run. Initially, the counter must be set to zero.

To unload a Document oldDocument, given an optional Document newDocument:

  1. Assert: this is running as part of a task queued on oldDocument's relevant agent's event loop.

  2. Let unloadTimingInfo be a new document unload timing info.

  3. If newDocument is not given, then set unloadTimingInfo to null.

    In this case there is no new document that needs to know about how long it took oldDocument to unload.

  4. Otherwise, if newDocument's event loop is not oldDocument's event loop, then the user agent may be unloading oldDocument in parallel. In that case, the user agent should set unloadTimingInfo to null.

    In this case newDocument's loading is not impacted by how long it takes to unload oldDocument, so it would be meaningless to communicate that timing info.

  5. Let intendToKeepInBfcache be true if the user agent intends to keep oldDocument alive in a session history entry, such that it can later be used for history traversal.

    This must be false if oldDocument is not salvageable, or if there are any descendants of oldDocument which the user agent does not intend to keep alive in the same way (including due to their lack of salvageability).

  6. Let eventLoop be oldDocument's relevant agent's event loop.

  7. Increase eventLoop's termination nesting level by 1.

  8. Increase oldDocument's unload counter by 1.

  9. If intendToKeepInBfcache is false, then set oldDocument's salvageable state to false.

  10. If oldDocument's page showing is true:

    1. Set oldDocument's page showing to false.

    2. Fire a page transition event named pagehide at oldDocument's relevant global object with oldDocument's salvageable state.

    3. Update the visibility state of oldDocument to "hidden".

  11. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event start time to the current high resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings object's cross-origin isolated capability.

  12. If oldDocument's salvageable state is false, then fire an event named unload at oldDocument's relevant global object, with legacy target override flag set.

  13. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event end time to the current high resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings object's cross-origin isolated capability.

  14. Decrease eventLoop's termination nesting level by 1.

  15. Set oldDocument's suspension time to the current high resolution time given document's relevant global object.

  16. Set oldDocument's suspended timer handles to the result of getting the keys for the map of active timers.

  17. Set oldDocument's has been scrolled by the user to false.

  18. Run any unloading document cleanup steps for oldDocument that are defined by this specification and other applicable specifications.

  19. If oldDocument's node navigable is a top-level traversable, build not restored reasons for a top-level traversable and its descendants given oldDocument's node navigable.

  20. If oldDocument's salvageable state is false, then destroy oldDocument.

  21. Decrease oldDocument's unload counter by 1.

  22. If newDocument is given, newDocument's was created via cross-origin redirects is false, and newDocument's origin is the same as oldDocument's origin, then set newDocument's previous document unload timing to unloadTimingInfo.

To unload a document and its descendants, given a Document document, an optional Document-or-null newDocument (default null), an optional set of steps afterAllUnloads, and an optional set of steps firePageSwapSteps:

  1. Assert: this is running within document's node navigable's traversable navigable's session history traversal queue.

  2. Let childNavigables be document's child navigables.

  3. Let numberUnloaded be 0.

  4. For each childNavigable of childNavigable's in what order?, queue a global task on the navigation and traversal task source given childNavigable's active window to perform the following steps:

    1. Let incrementUnloaded be an algorithm step which increments numberUnloaded.

    2. Unload a document and its descendants given childNavigable's active document, null, and incrementUnloaded.

  5. Wait until numberUnloaded equals childNavigable's size.

  6. Queue a global task on the navigation and traversal task source given document's relevant global object to perform the following steps:

    1. If firePageSwapSteps is given, then run firePageSwapSteps.

    2. Unload document, passing along newDocument if it is not null.

    3. If afterAllUnloads was given, then run it.

This specification defines the following unloading document cleanup steps. Other specifications can define more. Given a Document document:

  1. Let window be document's relevant global object.

  2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.

    If this affected any WebSocket objects, then make document unsalvageable given document and "websocket".

  3. For each WebTransport object transport whose relevant global object is window, run the context cleanup steps given transport.

  4. If document's salvageable state is false, then:

    1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.

    2. Clear window's map of active timers.

It would be better if specification authors sent a pull request to add calls from here into their specifications directly, instead of using the unloading document cleanup steps hook, to ensure well-defined cross-specification call order. As of the time of this writing the following specifications are known to have unloading document cleanup steps, which will be run in an unspecified order: Fullscreen API, Web NFC, WebDriver BiDi, Compute Pressure, File API, Media Capture and Streams, Picture-in-Picture, Screen Orientation, Service Workers, WebLocks API, WebAudio API, WebRTC. [FULLSCREEN] [WEBNFC] [WEBDRIVERBIDI] [COMPUTEPRESSURE] [FILEAPI] [MEDIASTREAM] [PICTUREINPICTURE] [SCREENORIENTATION] [SW] [WEBLOCKS] [WEBAUDIO] [WEBRTC]

Issue #8906 tracks the work to make the order of these steps clear.

7.5.10 Destroying documents

To destroy a Document document:

  1. Assert: this is running as part of a task queued on document's relevant agent's event loop.

  2. Abort document.

  3. Set document's salvageable state to false.

  4. Let ports be the list of MessagePorts whose relevant global object's associated Document is document.

  5. For each port in ports, disentangle port.

  6. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.

  7. Remove any tasks whose document is document from any task queue (without running those tasks).

  8. Set document's browsing context to null.

  9. Set document's node navigable's active session history entry's document state's document to null.

  10. Remove document from the owner set of each WorkerGlobalScope object whose set contains document.

  11. For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.

Even after destruction, the Document object itself might still be accessible to script, in the case where we are destroying a child navigable.

To destroy a document and its descendants given a Document document and an optional set of steps afterAllDestruction, perform the following steps in parallel:

  1. If document is not fully active, then:

    1. Make document unsalvageable given document and "masked".

    2. If document's node navigable is a top-level traversable, build not restored reasons for a top-level traversable and its descendants given document's node navigable.

  2. Let childNavigables be document's child navigables.

  3. Let numberDestroyed be 0.

  4. For each childNavigable of childNavigable's in what order?, queue a global task on the navigation and traversal task source given childNavigable's active window to perform the following steps:

    1. Let incrementDestroyed be an algorithm step which increments numberDestroyed.

    2. Destroy a document and its descendants given childNavigable's active document and incrementDestroyed.

  5. Wait until numberDestroyed equals childNavigable's size.

  6. Queue a global task on the navigation and traversal task source given document's relevant global object to perform the following steps:

    1. Destroy document.

    2. If afterAllDestruction was given, then run it.

7.5.11 Aborting a document load

To abort a Document document:

  1. Assert: this is running as part of a task queued on document's relevant agent's event loop.

  2. Cancel any instances of the fetch algorithm in the context of document, discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then make document unsalvageable given document and "fetch".

  3. If document's during-loading navigation ID for WebDriver BiDi is non-null, then:

    1. Invoke WebDriver BiDi navigation aborted with document's browsing context, and a new WebDriver BiDi navigation status whose id is document's during-loading navigation ID for WebDriver BiDi, status is "canceled", and url is document's URL.

    2. Set document's during-loading navigation ID for WebDriver BiDi to null.

  4. If document has an active parser, then:

    1. Set document's active parser was aborted to true.

    2. Abort that parser.

    3. Set document's salvageable to false.

    4. Make document unsalvageable given document and "parser-aborted".

To abort a document and its descendants given a Document document:

  1. Assert: this is running as part of a task queued on document's relevant agent's event loop.

  2. Let descendantNavigables be document's descendant navigables.

  3. For each descendantNavigable of descendantNavigables in what order?, queue a global task on the navigation and traversal task source given descendantNavigable's active window to perform the following steps:

    1. Abort descendantNavigable's active document.

    2. If descendantNavigable's active document's salvageable is false, then set document's salvageable to false.

  4. Abort document.

To stop loading a navigable navigable:

  1. Let document be navigable's active document.

  2. If document's unload counter is 0, and navigable's ongoing navigation is a navigation ID, then set the ongoing navigation for navigable to null.

    This will have the effect of aborting any ongoing navigations of navigable, since at certain points during navigation, changes to the ongoing navigation will cause further work to be abandoned.

  3. Abort a document and its descendants given document.

Through their user interface, user agents also allow stopping traversals, i.e. cases where the ongoing navigation is "traversal". The above algorithm does not account for this. (On the other hand, user agents do not allow window.stop() to stop traversals, so the above algorithm is correct for that caller.) See issue #6905.

7.6 The `X-Frame-Options` header

Headers/X-Frame-Options

Support in all current engines.

Firefox4+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView Android?Samsung Internet?Opera Android?

The `X-Frame-Options` HTTP response header is a legacy way of controlling whether and how a Document may be loaded inside of a child navigable. It is obsoleted by the frame-ancestors CSP directive, which provides more granular control over the same situations. It was originally defined in HTTP Header Field X-Frame-Options, but the definition and processing model here supersedes that document. [CSP] [RFC7034]

In particular, HTTP Header Field X-Frame-Options specified an `ALLOW-FROM` variant of the header, but that is not to be implemented.

Per the below processing model, if both a CSP frame-ancestors directive and an `X-Frame-Options` header are used in the same response, then `X-Frame-Options` is ignored.

For web developers and conformance checkers, its value ABNF is:

X-Frame-Options = "DENY" / "SAMEORIGIN"

To check a navigation response's adherence to `X-Frame-Options`, given a response response, a navigable navigable, a CSP list cspList, and an origin destinationOrigin:

  1. If navigable is not a child navigable, then return true.

  2. For each policy of cspList:

    1. If policy's disposition is not "enforce", then continue.

    2. If policy's directive set contains a frame-ancestors directive, then return true.

  3. Let rawXFrameOptions be the result of getting, decoding, and splitting `X-Frame-Options` from response's header list.

  4. Let xFrameOptions be a new set.

  5. For each value of rawXFrameOptions, append value, converted to ASCII lowercase, to xFrameOptions.

  6. If xFrameOptions's size is greater than 1, and xFrameOptions contains any of "deny", "allowall", or "sameorigin", then return false.

    The intention here is to block any attempts at applying `X-Frame-Options` which were trying to do something valid, but appear confused.

    This is the only impact of the legacy `ALLOWALL` value on the processing model.

  7. If xFrameOptions's size is greater than 1, then return true.

    This means it contains multiple invalid values, which we treat the same way as if the header was omitted entirely.

  8. If xFrameOptions[0] is "deny", then return false.

  9. If xFrameOptions[0] is "sameorigin", then:

    1. Let containerDocument be navigable's container document.

    2. While containerDocument is not null:

      1. If containerDocument's origin is not same origin with destinationOrigin, then return false.

      2. Set containerDocument to containerDocument's container document.

  10. Return true.

    If we've reached this point then we have a lone invalid value (which could potentially be one the legacy `ALLOWALL` or `ALLOW-FROM` forms). These are treated as if the header were omitted entirely.


The following table illustrates the processing of various values for the header, including non-conformant ones:

`X-Frame-Options` Valid Result
`DENY` embedding disallowed
`SAMEORIGIN` same-origin embedding allowed
`INVALID` embedding allowed
`ALLOWALL` embedding allowed
`ALLOW-FROM=https://example.com/` embedding allowed (from anywhere)

The following table illustrates how various non-conformant cases involving multiple values are processed:

`X-Frame-Options` Result
`SAMEORIGIN, SAMEORIGIN` same-origin embedding allowed
`SAMEORIGIN, DENY` embedding disallowed
`SAMEORIGIN,` embedding disallowed
`SAMEORIGIN, ALLOWALL` embedding disallowed
`SAMEORIGIN, INVALID` embedding disallowed
`ALLOWALL, INVALID` embedding disallowed
`ALLOWALL,` embedding disallowed
`INVALID, INVALID` embedding allowed

The same results are obtained whether the values are delivered in a single header whose value is comma-delimited, or in multiple headers.

7.7 The `Refresh` header

The `Refresh` HTTP response header is the HTTP-equivalent to a meta element with an http-equiv attribute in the Refresh state. It takes the same value and works largely the same. Its processing model is detailed in create and initialize a Document object.

Browser user agents should provide the ability to navigate, reload, and stop loading any top-level traversable in their top-level traversable set.

For example, via a location bar and reload/stop button UI.

Browser user agents should provide the ability to traverse by a delta any top-level traversable in their top-level traversable set.

For example, via back and forward buttons, possibly including long-press abilities to change the delta.

It is suggested that such user agents allow traversal by deltas greater than one, to avoid letting a page "trap" the user by stuffing the session history with spurious entries. (For example, via repeated calls to history.pushState() or fragment navigations.)

Some user agents have heuristics for translating a single "back" or "forward" button press into a larger delta, specifically to overcome such abuses. We are contemplating specifying these heuristics in issue #7832.

Browser user agents should offer users the ability to create a fresh top-level traversable, given a user-provided or user agent-determined initial URL.

For example, via a "new tab" or "new window" button.

Browser user agents should offer users the ability to arbitrarily close any top-level traversable in their top-level traversable set.

For example, by clicking a "close tab" button.


Browser user agents may provide ways for the user to explicitly cause any navigable (not just a top-level traversable) to navigate, reload, or stop loading.

For example, via a context menu.

Browser user agents may provide the ability for users to destroy a top-level traversable.

For example, by force-closing a window containing one or more such top-level traversables.


When a user requests a reload of a navigable whose active session history entry's document state's resource is a POST resource, the user agent should prompt the user to confirm the operation first, since otherwise transactions (e.g., purchases or database modifications) could be repeated.

When a user requests a reload of a navigable, user agents may provide a mechanism for ignoring any caches when reloading.


All calls to navigate initiated by the mechanisms mentioned above must have the userInvolvement argument set to "browser UI".

All calls to reload initiated by the mechanisms mentioned above must have the userInvolvement argument set to "browser UI".

All calls to traverse the history by a delta initiated by the mechanisms mentioned above must not pass a value for the sourceDocument argument.


The above recommendations, and the data structures in this specification, are not meant to place restrictions on how user agents represent the session history to the user.

For example, although a top-level traversable's session history entries are stored and maintained as a list, and the user agent is recommended to give an interface for traversing that list by a delta, a novel user agent could instead or in addition present a tree-like view, with each page having multiple "forward" pages that the user can choose between.

Similarly, although session history for all descendant navigables is stored in their traversable navigable, user agents could present the user with a more nuanced per-navigable view of the session history.


Browser user agents may use a top-level browsing context's is popup boolean for the following purposes:

In both cases user agents might additionally incorporate user preferences, or present a choice as to whether to go down the popup route.

User agents that provides a minimal user interface for such popups are encouraged to not hide the browser's location bar.

8 Web application APIs

8.1 Scripting

8.1.1 Introduction

Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to:

8.1.2 Agents and agent clusters

8.1.2.1 Integration with the JavaScript agent formalism

JavaScript defines the concept of an agent. This section gives the mapping of that language-level concept on to the web platform.

Conceptually, the agent concept is an architecture-independent, idealized "thread" in which JavaScript code runs. Such code can involve multiple globals/realms that can synchronously access each other, and thus needs to run in a single execution thread.

Two Window objects having the same agent does not indicate they can directly access all objects created in each other's realms. They would have to be same origin-domain; see IsPlatformObjectSameOrigin.

The following types of agents exist on the web platform:

Similar-origin window agent

Contains various Window objects which can potentially reach each other, either directly or by using document.domain.

If the encompassing agent cluster's is origin-keyed is true, then all the Window objects will be same origin, can reach each other directly, and document.domain will no-op.

Two Window objects that are same origin can be in different similar-origin window agents, for instance if they are each in their own browsing context group.

Dedicated worker agent

Contains a single DedicatedWorkerGlobalScope.

Shared worker agent

Contains a single SharedWorkerGlobalScope.

Service worker agent

Contains a single ServiceWorkerGlobalScope.

Worklet agent

Contains a single WorkletGlobalScope object.

Although a given worklet can have multiple realms, each such realm needs its own agent, as each realm can be executing code independently and at the same time as the others.

Only shared and dedicated worker agents allow the use of JavaScript Atomics APIs to potentially block.

To create an agent, given a boolean canBlock:

  1. Let signifier be a new unique internal value.

  2. Let candidateExecution be a new candidate execution.

  3. Let agent be a new agent whose [[CanBlock]] is canBlock, [[Signifier]] is signifier, [[CandidateExecution]] is candidateExecution, and [[IsLockFree1]], [[IsLockFree2]], and [[LittleEndian]] are set at the implementation's discretion.

  4. Set agent's event loop to a new event loop.

  5. Return agent.

For a realm realm, the agent whose [[Signifier]] is realm.[[AgentSignifier]] is the realm's agent.

The relevant agent for a platform object platformObject is platformObject's relevant realm's agent.

The agent equivalent of the current realm is the surrounding agent.

8.1.2.2 Integration with the JavaScript agent cluster formalism

JavaScript also defines the concept of an agent cluster, which this standard maps to the web platform by placing agents appropriately when they are created using the obtain a similar-origin window agent or obtain a worker/worklet agent algorithms.

The agent cluster concept is crucial for defining the JavaScript memory model, and in particular among which agents the backing data of SharedArrayBuffer objects can be shared.

Conceptually, the agent cluster concept is an architecture-independent, idealized "process boundary" that groups together multiple "threads" (agents). The agent clusters defined by the specification are generally more restrictive than the actual process boundaries implemented in user agents. By enforcing these idealized divisions at the specification level, we ensure that web developers see interoperable behavior with regard to shared memory, even in the face of varying and changing user agent process models.

An agent cluster has an associated cross-origin isolation mode, which is a cross-origin isolation mode. It is initially "none".

An agent cluster has an associated is origin-keyed (a boolean), which is initially false.


The following defines the allocation of the agent clusters of similar-origin window agents.

An agent cluster key is a site or tuple origin. Without web developer action to achieve origin-keyed agent clusters, it will be a site.

An equivalent formulation is that an agent cluster key can be a scheme-and-host or an origin.

To obtain a similar-origin window agent, given an origin origin, a browsing context group group, and a boolean requestsOAC, run these steps:

  1. Let site be the result of obtaining a site with origin.

  2. Let key be site.

  3. If group's cross-origin isolation mode is not "none", then set key to origin.

  4. Otherwise, if group's historical agent cluster key map[origin] exists, then set key to group's historical agent cluster key map[origin].

  5. Otherwise:

    1. If requestsOAC is true, then set key to origin.

    2. Set group's historical agent cluster key map[origin] to key.

  6. If group's agent cluster map[key] does not exist, then:

    1. Let agentCluster be a new agent cluster.

    2. Set agentCluster's cross-origin isolation mode to group's cross-origin isolation mode.

    3. Set agentCluster's is origin-keyed to true if key equals origin; otherwise false.

    4. Add the result of creating an agent, given false, to agentCluster.

    5. Set group's agent cluster map[key] to agentCluster.

  7. Return the single similar-origin window agent contained in group's agent cluster map[key].

This means that there is only one similar-origin window agent per browsing context agent cluster. (However, dedicated worker and worklet agents might be in the same cluster.)


The following defines the allocation of the agent clusters of all other types of agents.

To obtain a worker/worklet agent, given an environment settings object or null outside settings, a boolean isTopLevel, and a boolean canBlock, run these steps:

  1. Let agentCluster be null.

  2. If isTopLevel is true, then:

    1. Set agentCluster to a new agent cluster.

    2. Set agentCluster's is origin-keyed to true.

      These workers can be considered to be origin-keyed. However, this is not exposed through any APIs (in the way that originAgentCluster exposes the origin-keyedness for windows).

  3. Otherwise:

    1. Assert: outside settings is not null.

    2. Let ownerAgent be outside settings's realm's agent.

    3. Set agentCluster to the agent cluster which contains ownerAgent.

  4. Let agent be the result of creating an agent given canBlock.

  5. Add agent to agentCluster.

  6. Return agent.

To obtain a dedicated/shared worker agent, given an environment settings object outside settings and a boolean isShared, return the result of obtaining a worker/worklet agent given outside settings, isShared, and true.

To obtain a worklet agent, given an environment settings object outside settings, return the result of obtaining a worker/worklet agent given outside settings, false, and false.

To obtain a service worker agent, return the result of obtaining a worker/worklet agent given null, true, and false.


The following pairs of global objects are each within the same agent cluster, and thus can use SharedArrayBuffer instances to share memory with each other:

The following pairs of global objects are not within the same agent cluster, and thus cannot share memory:

8.1.3 Realms and their counterparts

The JavaScript specification introduces the realm concept, representing a global environment in which script is run. Each realm comes with an implementation-defined global object; much of this specification is devoted to defining that global object and its properties.

For web specifications, it is often useful to associate values or algorithms with a realm/global object pair. When the values are specific to a particular type of realm, they are associated directly with the global object in question, e.g., in the definition of the Window or WorkerGlobalScope interfaces. When the values have utility across multiple realms, we use the environment settings object concept.

Finally, in some cases it is necessary to track associated values before a realm/global object/environment settings object even comes into existence (for example, during navigation). These values are tracked in the environment concept.

8.1.3.1 Environments

An environment is an object that identifies the settings of a current or potential execution environment (i.e., a navigation params's reserved environment or a request's reserved client). An environment has the following fields:

An id

An opaque string that uniquely identifies this environment.

A creation URL

A URL that represents the location of the resource with which this environment is associated.

In the case of a Window environment settings object, this URL might be distinct from its global object's associated Document's URL, due to mechanisms such as history.pushState() which modify the latter.

A top-level creation URL

Null or a URL that represents the creation URL of the "top-level" environment. It is null for workers and worklets.

A top-level origin

A for now implementation-defined value, null, or an origin. For a "top-level" potential execution environment it is null (i.e., when there is no response yet); otherwise it is the "top-level" environment's origin. For a dedicated worker or worklet it is the top-level origin of its creator. For a shared or service worker it is an implementation-defined value.

This is distinct from the top-level creation URL's origin when sandboxing, workers, and worklets are involved.

A target browsing context

Null or a target browsing context for a navigation request.

An active service worker

Null or a service worker that controls the environment.

An execution ready flag

A flag that indicates whether the environment setup is done. It is initially unset.

Specifications may define environment discarding steps for environments. The steps take an environment as input.

The environment discarding steps are run for only a select few environments: the ones that will never become execution ready because, for example, they failed to load.

8.1.3.2 Environment settings objects

An environment settings object is an environment that additionally specifies algorithms for:

A realm execution context

A JavaScript execution context shared by all scripts that use this settings object, i.e., all scripts in a given realm. When we run a classic script or run a module script, this execution context becomes the top of the JavaScript execution context stack, on top of which another execution context specific to the script in question is pushed. (This setup ensures Source Text Module Record's Evaluate knows which realm to use.)

A module map

A module map that is used when importing JavaScript modules.

An API base URL

A URL used by APIs called by scripts that use this environment settings object to parse URLs.

An origin

An origin used in security checks.

A policy container

A policy container containing policies used for security checks.

A cross-origin isolated capability

A boolean representing whether scripts that use this environment settings object are allowed to use APIs that require cross-origin isolation.

A time origin
A number used as the baseline for performance-related timestamps. [HRT]

An environment settings object's responsible event loop is its global object's relevant agent's event loop.

8.1.3.3 Realms, settings objects, and global objects

A global object is a JavaScript object that is the [[GlobalObject]] field of a realm.

In this specification, all realms are created with global objects that are either Window, WorkerGlobalScope, or WorkletGlobalScope objects.

A global object has an in error reporting mode boolean, which is initially false.

A global object has an outstanding rejected promises weak set, a set of Promise objects, initially empty. This set must not create strong references to any of its members, and implementations are free to limit its size in an implementation-defined manner, e.g., by removing old entries from it when new ones are added.

A global object has an about-to-be-notified rejected promises list, a list of Promise objects, initially empty.


There is always a 1-to-1-to-1 mapping between realms, global objects, and environment settings objects:

To create a new realm in an agent agent, optionally with instructions to create a global object or a global this binding (or both), the following steps are taken:

  1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.

  2. Let realm execution context be the running JavaScript execution context.

    This is the JavaScript execution context created in the previous step.

  3. Remove realm execution context from the JavaScript execution context stack.

  4. Let realm be realm execution context's Realm component.

  5. If agent's agent cluster's cross-origin isolation mode is "none", then:

    1. Let global be realm's global object.

    2. Let status be ! global.[[Delete]]("SharedArrayBuffer").

    3. Assert: status is true.

    This is done for compatibility with web content and there is some hope that this can be removed in the future. Web developers can still get at the constructor through new WebAssembly.Memory({ shared:true, initial:0, maximum:0 }).buffer.constructor.

  6. Return realm execution context.


When defining algorithm steps throughout this specification, it is often important to indicate what realm is to be used—or, equivalently, what global object or environment settings object is to be used. In general, there are at least four possibilities:

Entry
This corresponds to the script that initiated the currently running script action: i.e., the function or script that the user agent called into when it called into author code.
Incumbent
This corresponds to the most-recently-entered author function or script on the stack, or the author function or script that originally scheduled the currently-running callback.
Current
This corresponds to the currently-running function object, including built-in user-agent functions which might not be implemented as JavaScript. (It is derived from the current realm.)
Relevant
Every platform object has a relevant realm, which is roughly the realm in which it was created. When writing algorithms, the most prominent platform object whose relevant realm might be important is the this value of the currently-running function object. In some cases, there can be other important relevant realms, such as those of any arguments.

Note how the entry, incumbent, and current concepts are usable without qualification, whereas the relevant concept must be applied to a particular platform object.

The incumbent and entry concepts should not be used by new specifications, as they are excessively complicated and unintuitive to work with. We are working to remove almost all existing uses from the platform: see issue #1430 for incumbent, and issue #1431 for entry.

In general, web platform specifications should use the relevant concept, applied to the object being operated on (usually the this value of the current method). This mismatches the JavaScript specification, where current is generally used as the default (e.g., in determining the realm whose Array constructor should be used to construct the result in Array.prototype.map). But this inconsistency is so embedded in the platform that we have to accept it going forward.

Consider the following pages, with a.html being loaded in a browser window, b.html being loaded in an iframe as shown, and c.html and d.html omitted (they can simply be empty documents):

<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<title>Entry page</title>

<iframe src="b.html"></iframe>
<button onclick="frames[0].hello()">Hello</button>

<!--b.html -->
<!DOCTYPE html>
<html lang="en">
<title>Incumbent page</title>

<iframe src="c.html" id="c"></iframe>
<iframe src="d.html" id="d"></iframe>

<script>
  const c = document.querySelector("#c").contentWindow;
  const d = document.querySelector("#d").contentWindow;

  window.hello = () => {
    c.print.call(d);
  };
</script>

Each page has its own browsing context, and thus its own realm, global object, and environment settings object.

When the print() method is called in response to pressing the button in a.html, then:

One reason why the relevant concept is generally a better default choice than the current concept is that it is more suitable for creating an object that is to be persisted and returned multiple times. For example, the navigator.getBattery() method creates promises in the relevant realm for the Navigator object on which it is invoked. This has the following impact: [BATTERY]

<!-- outer.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant realm demo: outer page</title>
<script>
  function doTest() {
    const promise = navigator.getBattery.call(frames[0].navigator);

    console.log(promise instanceof Promise);           // logs false
    console.log(promise instanceof frames[0].Promise); // logs true

    frames[0].hello();
  }
</script>
<iframe src="inner.html" onload="doTest()"></iframe>

<!-- inner.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant realm demo: inner page</title>
<script>
  function hello() {
    const promise = navigator.getBattery();

    console.log(promise instanceof Promise);        // logs true
    console.log(promise instanceof parent.Promise); // logs false
  }
</script>

If the algorithm for the getBattery() method had instead used the current realm, all the results would be reversed. That is, after the first call to getBattery() in outer.html, the Navigator object in inner.html would be permanently storing a Promise object created in outer.html's realm, and calls like that inside the hello() function would thus return a promise from the "wrong" realm. Since this is undesirable, the algorithm instead uses the relevant realm, giving the sensible results indicated in the comments above.


The rest of this section deals with formally defining the entry, incumbent, current, and relevant concepts.

8.1.3.3.1 Entry

The process of calling scripts will push or pop realm execution contexts onto the JavaScript execution context stack, interspersed with other execution contexts.

With this in hand, we define the entry execution context to be the most recently pushed item in the JavaScript execution context stack that is a realm execution context. The entry realm is the entry execution context's Realm component.

Then, the entry settings object is the environment settings object of the entry realm.

Similarly, the entry global object is the global object of the entry realm.

8.1.3.3.2 Incumbent

All JavaScript execution contexts must contain, as part of their code evaluation state, a skip-when-determining-incumbent counter value, which is initially zero. In the process of preparing to run a callback and cleaning up after running a callback, this value will be incremented and decremented.

Every event loop has an associated backup incumbent settings object stack, initially empty. Roughly speaking, it is used to determine the incumbent settings object when no author code is on the stack, but author code is responsible for the current algorithm having been run in some way. The process of preparing to run a callback and cleaning up after running a callback manipulate this stack. [WEBIDL]

When Web IDL is used to invoke author code, or when HostEnqueuePromiseJob invokes a promise job, they use the following algorithms to track relevant data for determining the incumbent settings object:

To prepare to run a callback with an environment settings object settings:

  1. Push settings onto the backup incumbent settings object stack.

  2. Let context be the topmost script-having execution context.

  3. If context is not null, increment context's skip-when-determining-incumbent counter.

To clean up after running a callback with an environment settings object settings:

  1. Let context be the topmost script-having execution context.

    This will be the same as the topmost script-having execution context inside the corresponding invocation of prepare to run a callback.

  2. If context is not null, decrement context's skip-when-determining-incumbent counter.

  3. Assert: the topmost entry of the backup incumbent settings object stack is settings.

  4. Remove settings from the backup incumbent settings object stack.

Here, the topmost script-having execution context is the topmost entry of the JavaScript execution context stack that has a non-null ScriptOrModule component, or null if there is no such entry in the JavaScript execution context stack.

With all this in place, the incumbent settings object is determined as follows:

  1. Let context be the topmost script-having execution context.

  2. If context is null, or if context's skip-when-determining-incumbent counter is greater than zero, then:

    1. Assert: the backup incumbent settings object stack is not empty.

      This assert would fail if you try to obtain the incumbent settings object from inside an algorithm that was triggered neither by calling scripts nor by Web IDL invoking a callback. For example, it would trigger if you tried to obtain the incumbent settings object inside an algorithm that ran periodically as part of the event loop, with no involvement of author code. In such cases the incumbent concept cannot be used.

    2. Return the topmost entry of the backup incumbent settings object stack.

  3. Return context's Realm component's settings object.

Then, the incumbent realm is the realm of the incumbent settings object.

Similarly, the incumbent global object is the global object of the incumbent settings object.


The following series of examples is intended to make it clear how all of the different mechanisms contribute to the definition of the incumbent concept:

Consider the following starter example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  frames[0].postMessage("some data", "*");
</script>

There are two interesting environment settings objects here: that of window, and that of frames[0]. Our concern is: what is the incumbent settings object at the time that the algorithm for postMessage() executes?

It should be that of window, to capture the intuitive notion that the author script responsible for causing the algorithm to happen is executing in window, not frames[0]. This makes sense: the window post message steps use the incumbent settings object to determine the source property of the resulting MessageEvent, and in this case window is definitely the source of the message.

Let us now explain how the steps given above give us our intuitively-desired result of window's relevant settings object.

When the window post message steps look up the incumbent settings object, the topmost script-having execution context will be that corresponding to the script element: it was pushed onto the JavaScript execution context stack as part of ScriptEvaluation during the run a classic script algorithm. Since there are no Web IDL callback invocations involved, the context's skip-when-determining-incumbent counter is zero, so it is used to determine the incumbent settings object; the result is the environment settings object of window.

(Note how the environment settings object of frames[0] is the relevant settings object of this at the time the postMessage() method is called, and thus is involved in determining the target of the message. Whereas the incumbent is used to determine the source.)

Consider the following more complicated example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  const bound = frames[0].postMessage.bind(frames[0], "some data", "*");
  window.setTimeout(bound);
</script>

This example is very similar to the previous one, but with an extra indirection through Function.prototype.bind as well as setTimeout(). But, the answer should be the same: invoking algorithms asynchronously should not change the incumbent concept.

This time, the result involves more complicated mechanisms:

When bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to window (in the same manner as in our starter example above). Web IDL stores this as the resulting callback value's callback context.

When the task posted by setTimeout() executes, the algorithm for that task uses Web IDL to invoke the stored callback value. Web IDL in turn calls the above prepare to run a callback algorithm. This pushes the stored callback context onto the backup incumbent settings object stack. At this time (inside the timer task) there is no author code on the stack, so the topmost script-having execution context is null, and nothing gets its skip-when-determining-incumbent counter incremented.

Invoking the callback then calls bound, which in turn calls the postMessage() method of frames[0]. When the postMessage() algorithm looks up the incumbent settings object, there is still no author code on the stack, since the bound function just directly calls the built-in method. So the topmost script-having execution context will be null: the JavaScript execution context stack only contains an execution context corresponding to postMessage(), with no ScriptEvaluation context or similar below it.

This is where we fall back to the backup incumbent settings object stack. As noted above, it will contain as its topmost entry the relevant settings object of window. So that is what is used as the incumbent settings object while executing the postMessage() algorithm.

Consider this final, even more convoluted example:

<!-- a.html -->
<!DOCTYPE html>
<button>click me</button>
<iframe></iframe>
<script>
const bound = frames[0].location.assign.bind(frames[0].location, "https://example.com/");
document.querySelector("button").addEventListener("click", bound);
</script>
<!-- b.html -->
<!DOCTYPE html>
<iframe src="a.html"></iframe>
<script>
  const iframe = document.querySelector("iframe");
  iframe.onload = function onLoad() {
    iframe.contentWindow.document.querySelector("button").click();
  };
</script>

Again there are two interesting environment settings objects in play: that of a.html, and that of b.html. When the location.assign() method triggers the Location-object navigate algorithm, what will be the incumbent settings object? As before, it should intuitively be that of a.html: the click listener was originally scheduled by a.html, so even if something involving b.html causes the listener to fire, the incumbent responsible is that of a.html.

The callback setup is similar to the previous example: when bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to a.html, which is stored as the callback's callback context.

When the click() method is called inside b.html, it dispatches a click event on the button that is inside a.html. This time, when the prepare to run a callback algorithm executes as part of event dispatch, there is author code on the stack; the topmost script-having execution context is that of the onLoad function, whose skip-when-determining-incumbent counter gets incremented. Additionally, a.html's environment settings object (stored as the EventHandler's callback context) is pushed onto the backup incumbent settings object stack.

Now, when the Location-object navigate algorithm looks up the incumbent settings object, the topmost script-having execution context is still that of the onLoad function (due to the fact we are using a bound function as the callback). Its skip-when-determining-incumbent counter value is one, however, so we fall back to the backup incumbent settings object stack. This gives us the environment settings object of a.html, as expected.

Note that this means that even though it is the iframe inside a.html that navigates, it is a.html itself that is used as the source Document, which determines among other things the request client. This is perhaps the only justifiable use of the incumbent concept on the web platform; in all other cases the consequences of using it are simply confusing and we hope to one day switch them to use current or relevant as appropriate.

8.1.3.3.3 Current

The JavaScript specification defines the current realm, also known as the "current Realm Record". [JAVASCRIPT]

Then, the current settings object is the environment settings object of the current realm.

Similarly, the current global object is the global object of the current realm.

8.1.3.3.4 Relevant

The relevant realm for a platform object is the value of its [[Realm]] field.

Then, the relevant settings object for a platform object o is the environment settings object of the relevant realm for o.

Similarly, the relevant global object for a platform object o is the global object of the relevant realm for o.

8.1.3.4 Enabling and disabling scripting

Scripting is enabled for an environment settings object settings when all of the following conditions are true:

Scripting is disabled for an environment settings object when scripting is not enabled for it, i.e., when any of the above conditions are false.


Scripting is enabled for a node node if node's node document's browsing context is non-null, and scripting is enabled for node's relevant settings object.

Scripting is disabled for a node when scripting is not enabled, i.e., when its node document's browsing context is null or when scripting is disabled for its relevant settings object.

8.1.3.5 Secure contexts

An environment environment is a secure context if the following algorithm returns true:

  1. If environment is an environment settings object, then:

    1. Let global be environment's global object.

    2. If global is a WorkerGlobalScope, then:

      1. If global's owner set[0]'s relevant settings object is a secure context, then return true.

        We only need to check the 0th item since they will necessarily all be consistent.

      2. Return false.

    3. If global is a WorkletGlobalScope, then return true.

      Worklets can only be created in secure contexts.

  2. If the result of Is url potentially trustworthy? given environment's top-level creation URL is "Potentially Trustworthy", then return true.

  3. Return false.

An environment is a non-secure context if it is not a secure context.

8.1.4 Script processing model

8.1.4.1 Scripts

A script is one of two possible structs (namely, a classic script or a module script). All scripts have:

A settings object

An environment settings object, containing various settings that are shared with other scripts in the same context.

A record

One of the following:

A parse error

A JavaScript value, which has meaning only if the record is null, indicating that the corresponding script source text could not be parsed.

This value is used for internal tracking of immediate parse errors when creating scripts, and is not to be used directly. Instead, consult the error to rethrow when determining "what went wrong" for this script.

An error to rethrow

A JavaScript value representing an error that will prevent evaluation from succeeding. It will be re-thrown by any attempts to run the script.

This could be the script's parse error, but in the case of a module script it could instead be the parse error from one of its dependencies, or an error from resolve a module specifier.

Since this exception value is provided by the JavaScript specification, we know that it is never null, so we use null to signal that no error has occurred.

Fetch options
Null or a script fetch options, containing various options related to fetching this script or module scripts that it imports.
A base URL

Null or a base URL used for resolving module specifiers. When non-null, this will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts.

A classic script is a type of script that has the following additional item:

A muted errors boolean

A boolean which, if true, means that error information will not be provided for errors in this script. This is used to mute errors for cross-origin scripts, since that can leak private information.

A module script is another type of script. It has no additional items.

Module scripts can be classified into three types:

As CSS stylesheets and JSON documents do not import dependent modules, and do not throw exceptions on evaluation, the fetch options and base URL of CSS module scripts and JSON module scripts and are always null.

The active script is determined by the following algorithm:

  1. Let record be GetActiveScriptOrModule().

  2. If record is null, return null.

  3. Return record.[[HostDefined]].

The active script concept is so far only used by the import() feature, to determine the base URL to use for resolving relative module specifiers.

8.1.4.2 Fetching scripts

This section introduces a number of algorithms for fetching scripts, taking various necessary inputs and resulting in classic or module scripts.


Script fetch options is a struct with the following items:

cryptographic nonce

The cryptographic nonce metadata used for the initial fetch and for fetching any imported modules

integrity metadata

The integrity metadata used for the initial fetch

parser metadata

The parser metadata used for the initial fetch and for fetching any imported modules

credentials mode

The credentials mode used for the initial fetch (for module scripts) and for fetching any imported modules (for both module scripts and classic scripts)

referrer policy

The referrer policy used for the initial fetch and for fetching any imported modules

This policy can mutate after a module script's response is received, to be the referrer policy parsed from the response, and used when fetching any module dependencies.

render-blocking

The boolean value of render-blocking used for the initial fetch and for fetching any imported modules. Unless otherwise stated, its value is false.

fetch priority

The priority used for the initial fetch

Recall that via the import() feature, classic scripts can import module scripts.

The default classic script fetch options are a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is "same-origin", referrer policy is the empty string, and fetch priority is "auto".

Given a request request and a script fetch options options, we define:

set up the classic script request

Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.

set up the module script request

Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials mode, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.

To get the descendant script fetch options given a script fetch options originalOptions, a URL url, and an environment settings object settingsObject:

  1. Let newOptions be a copy of originalOptions.

  2. Let integrity be the empty string.

  3. If settingsObject's global object is a Window object, then set integrity to the result of resolving a module integrity metadata with url and settingsObject.

  4. Set newOptions's integrity metadata to integrity.

  5. Set newOptions's fetch priority to "auto".

  6. Return newOptions.

To resolve a module integrity metadata, given a URL url and an environment settings object settingsObject:

  1. Assert: settingsObject's global object is a Window object.

  2. Let map be settingsObject's global object's import map.

  3. If map's integrity[url] does not exist, then return the empty string.

  4. Return map's integrity[url].


Several of the below algorithms can be customized with a perform the fetch hook algorithm, which takes a request, a boolean isTopLevel, and a processCustomFetchResponse algorithm. It runs processCustomFetchResponse with a response and either null (on failure) or a byte sequence containing the response body. isTopLevel will be true for all classic script fetches, and for the initial fetch when fetching an external module script graph or fetching a module worker script graph, but false for the fetches resulting from import statements encountered throughout the graph or from import() expressions.

By default, not supplying a perform the fetch hook will cause the below algorithms to simply fetch the given request, with algorithm-specific customizations to the request and validations of the resulting response.

To layer your own customizations on top of these algorithm-specific ones, supply a perform the fetch hook that modifies the given request, fetches it, and then performs specific validations of the resulting response (completing with a network error if the validations fail).

The hook can also be used to perform more subtle customizations, such as keeping a cache of responses and avoiding performing a fetch at all.

Service Workers is an example of a specification that runs these algorithms with its own options for the hook. [SW]


Now for the algorithms themselves.

To fetch a classic script given a URL url, an environment settings object settingsObject, a script fetch options options, a CORS settings attribute state corsSetting, an encoding encoding, and an algorithm onComplete, run these steps. onComplete must be an algorithm accepting null (on failure) or a classic script (on success).

  1. Let request be the result of creating a potential-CORS request given url, "script", and corsSetting.

  2. Set request's client to settingsObject.

  3. Set request's initiator type to "script".

  4. Set up the classic script request given request and options.

  5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure, or a byte sequence bodyBytes:

    response can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.

    1. Set response to response's unsafe response.

    2. If any of the following are true:

      then run onComplete given null, and abort these steps.

      For historical reasons, this algorithm does not include MIME type checking, unlike the other script-fetching algorithms in this section.

    3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.

    4. Set encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding and encoding.

      This intentionally ignores the MIME type essence.

    5. Let sourceText be the result of decoding bodyBytes to Unicode, using encoding as the fallback encoding.

      The decode algorithm overrides encoding if the file contains a BOM.

    6. Let mutedErrors be true if response was CORS-cross-origin, and false otherwise.

    7. Let script be the result of creating a classic script given sourceText, settingsObject, response's URL, options, mutedErrors, and url.

    8. Run onComplete given script.

To fetch a classic worker script given a URL url, an environment settings object fetchClient, a destination destination, an environment settings object settingsObject, an algorithm onComplete, and an optional perform the fetch hook performFetch, run these steps. onComplete must be an algorithm accepting null (on failure) or a classic script (on success).

  1. Let request be a new request whose URL is url, client is fetchClient, destination is destination, initiator type is "other", mode is "same-origin", credentials mode is "same-origin", parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.

  2. If performFetch was given, run performFetch with request, true, and with processResponseConsumeBody as defined below.

    Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.

    In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:

    1. Set response to response's unsafe response.

    2. If any of the following are true:

      then run onComplete given null, and abort these steps.

    3. If all of the following are true:

      then run onComplete given null, and abort these steps.

      Other fetch schemes are exempted from MIME type checking for historical web-compatibility reasons. We might be able to tighten this in the future; see issue #3255.

    4. Let sourceText be the result of UTF-8 decoding bodyBytes.

    5. Let script be the result of creating a classic script using sourceText, settingsObject, response's URL, and the default classic script fetch options.

    6. Run onComplete given script.

To fetch a classic worker-imported script given a URL url, an environment settings object settingsObject, and an optional perform the fetch hook performFetch, run these steps. The algorithm will return a classic script on success, or throw an exception on failure.

  1. Let response be null.

  2. Let bodyBytes be null.

  3. Let request be a new request whose URL is url, client is settingsObject, destination is "script", initiator type is "other", parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.

  4. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.

    Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.

    In both cases, let processResponseConsumeBody given response res and null, failure, or a byte sequence bb be the following algorithm:

    1. Set bodyBytes to bb.

    2. Set response to res.

  5. Pause until response is not null.

    Unlike other algorithms in this section, the fetching process is synchronous here.

  6. Set response to response's unsafe response.

  7. If any of the following are true:

    then throw a "NetworkError" DOMException.

  8. Let sourceText be the result of UTF-8 decoding bodyBytes.

  9. Let mutedErrors be true if response was CORS-cross-origin, and false otherwise.

  10. Let script be the result of creating a classic script given sourceText, settingsObject, response's URL, the default classic script fetch options, and mutedErrors.

  11. Return script.

To fetch an external module script graph given a URL url, an environment settings object settingsObject, a script fetch options options, and an algorithm onComplete, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Disallow further import maps given settingsObject.

  2. Fetch a single module script given url, settingsObject, "script", options, settingsObject, "client", true, and with the following steps given result:

    1. If result is null, run onComplete given null, and abort these steps.

    2. Fetch the descendants of and link result given settingsObject, "script", and onComplete.

To fetch a modulepreload module script graph given a URL url, a destination destination, an environment settings object settingsObject, a script fetch options options, and an algorithm onComplete, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Disallow further import maps given settingsObject.

  2. Fetch a single module script given url, settingsObject, destination, options, settingsObject, "client", true, and with the following steps given result:

    1. Run onComplete given result.

    2. If result is not null, optionally fetch the descendants of and link result given settingsObject, destination, and an empty algorithm.

      Generally, performing this step will be beneficial for performance, as it allows pre-loading the modules that will invariably be requested later, via algorithms such as fetch an external module script graph that fetch the entire graph. However, user agents might wish to skip them in bandwidth-constrained situations, or situations where the relevant fetches are already in flight.

To fetch an inline module script graph given a string sourceText, a URL baseURL, an environment settings object settingsObject, a script fetch options options, and an algorithm onComplete, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Disallow further import maps given settingsObject.

  2. Let script be the result of creating a JavaScript module script using sourceText, settingsObject, baseURL, and options.

  3. Fetch the descendants of and link script, given settingsObject, "script", and onComplete.

To fetch a module worker script graph given a URL url, an environment settings object fetchClient, a destination destination, a credentials mode credentialsMode, an environment settings object settingsObject, and an algorithm onComplete, fetch a worklet/module worker script graph given url, fetchClient, destination, credentialsMode, settingsObject, and onComplete.

To fetch a worklet script graph given a URL url, an environment settings object fetchClient, a destination destination, a credentials mode credentialsMode, an environment settings object settingsObject, a module responses map moduleResponsesMap, and an algorithm onComplete, fetch a worklet/module worker script graph given url, fetchClient, destination, credentialsMode, settingsObject, onComplete, and the following perform the fetch hook given request and processCustomFetchResponse:

  1. Let requestURL be request's URL.

  2. If moduleResponsesMap[requestURL] is "fetching", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps.

  3. If moduleResponsesMap[requestURL] exists, then:

    1. Let cached be moduleResponsesMap[requestURL].

    2. Run processCustomFetchResponse with cached[0] and cached[1].

    3. Return.

  4. Set moduleResponsesMap[requestURL] to "fetching".

  5. Fetch request, with processResponseConsumeBody set to the following steps given response response and null, failure, or a byte sequence bodyBytes:

    1. Set moduleResponsesMap[requestURL] to (response, bodyBytes).

    2. Run processCustomFetchResponse with response and bodyBytes.


The following algorithms are meant for internal use by this specification only as part of fetching an external module script graph or other similar concepts above, and should not be used directly by other specifications.

This diagram illustrates how these algorithms relate to the ones above, as well as to each other:

fetch an external module script graph fetch a modulepreload module script graph fetch an inline module script graph fetch a module worker script graph fetch a worklet script graph fetch a worklet/module worker script graph fetch the descendants of and link a module script

To fetch a worklet/module worker script graph given a URL url, an environment settings object fetchClient, a destination destination, a credentials mode credentialsMode, an environment settings object settingsObject, an algorithm onComplete, and an optional perform the fetch hook performFetch, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Let options be a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is credentialsMode, referrer policy is the empty string, and fetch priority is "auto".

  2. Fetch a single module script given url, fetchClient, destination, options, settingsObject, "client", true, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.

    onSingleFetchComplete given result is the following algorithm:

    1. If result is null, run onComplete given null, and abort these steps.

    2. Fetch the descendants of and link result given fetchClient, destination, and onComplete. If performFetch was given, pass it along as well.

To fetch the descendants of and link a module script moduleScript, given an environment settings object fetchClient, a destination destination, an algorithm onComplete, and an optional perform the fetch hook performFetch, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Let record be moduleScript's record.

  2. If record is null, then:

    1. Set moduleScript's error to rethrow to moduleScript's parse error.

    2. Run onComplete given moduleScript.

    3. Return.

  3. Let state be Record { [[ParseError]]: null, [[Destination]]: destination, [[PerformFetch]]: null, [[FetchClient]]: fetchClient }.

  4. If performFetch was given, set state.[[PerformFetch]] to performFetch.

  5. Let loadingPromise be record.LoadRequestedModules(state).

    This step will recursively load all the module transitive dependencies.

  6. Upon fulfillment of loadingPromise, run the following steps:

    1. Perform record.Link().

      This step will recursively call Link on all of the module's unlinked dependencies.

      If this throws an exception, catch it, and set moduleScript's error to rethrow to that exception.

    2. Run onComplete given moduleScript.

  7. Upon rejection of loadingPromise, run the following steps:

    1. If state.[[ParseError]] is not null, set moduleScript's error to rethrow to state.[[ParseError]] and run onComplete given moduleScript.

    2. Otherwise, run onComplete given null.

      state.[[ParseError]] is null when loadingPromise is rejected due to a loading error.

To fetch a single module script, given a URL url, an environment settings object fetchClient, a destination destination, a script fetch options options, an environment settings object settingsObject, a referrer referrer, an optional ModuleRequest Record moduleRequest, a boolean isTopLevel, an algorithm onComplete, and an optional perform the fetch hook performFetch, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Let moduleType be "javascript".

  2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.

  3. Assert: the result of running the module type allowed steps given moduleType and settingsObject is true. Otherwise, we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Attributes]] in create a JavaScript module script or fetch a single imported module script.

  4. Let moduleMap be settingsObject's module map.

  5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps.

  6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.

  7. Set moduleMap[(url, moduleType)] to "fetching".

  8. Let request be a new request whose URL is url, mode is "cors", referrer is referrer, and client is fetchClient.

  9. Set request's destination to the result of running the fetch destination from module type steps given destination and moduleType.

  10. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin".

  11. Set request's initiator type to "script".

  12. Set up the module script request given request and options.

  13. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.

    Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.

    In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:

    response is always CORS-same-origin.

    1. If any of the following are true:

      then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.

    2. Let sourceText be the result of UTF-8 decoding bodyBytes.

    3. Let mimeType be the result of extracting a MIME type from response's header list.

    4. Let moduleScript be null.

    5. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]

    6. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.

    7. If mimeType is a JavaScript MIME type and moduleType is "javascript", then set moduleScript to the result of creating a JavaScript module script given sourceText, settingsObject, response's URL, and options.

    8. If the MIME type essence of mimeType is "text/css" and moduleType is "css", then set moduleScript to the result of creating a CSS module script given sourceText and settingsObject.

    9. If mimeType is a JSON MIME type and moduleType is "json", then set moduleScript to the result of creating a JSON module script given sourceText and settingsObject.

    10. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.

      It is intentional that the module map is keyed by the request URL, whereas the base URL for the module script is set to the response URL. The former is used to deduplicate fetches, while the latter is used for URL resolution.

To fetch a single imported module script, given a URL url, an environment settings object fetchClient, a destination destination, a script fetch options options, environment settings object settingsObject, a referrer referrer, a ModuleRequest Record moduleRequest, an algorithm onComplete, and an optional perform the fetch hook performFetch, run these steps. onComplete must be an algorithm accepting null (on failure) or a module script (on success).

  1. Assert: moduleRequest.[[Attributes]] does not contain any Record entry such that entry.[[Key]] is not "type", because we only asked for "type" attributes in HostGetSupportedImportAttributes.

  2. Let moduleType be the result of running the module type from module request steps given moduleRequest.

  3. If the result of running the module type allowed steps given moduleType and settingsObject is false, then run onComplete given null, and return.

  4. Fetch a single module script given url, fetchClient, destination, options, settingsObject, referrer, moduleRequest, false, and onComplete. If performFetch was given, pass it along as well.

8.1.4.3 Creating scripts

To create a classic script, given a string source, an environment settings object settings, a URL baseURL, a script fetch options options, an optional boolean mutedErrors (default false), and an optional URL-or-null sourceURLForWindowScripts (default null):

  1. If mutedErrors is true, then set baseURL to about:blank.

    When mutedErrors is true, baseURL is the script's CORS-cross-origin response's url, which shouldn't be exposed to JavaScript. Therefore, baseURL is sanitized here.

  2. If scripting is disabled for settings, then set source to the empty string.

  3. Let script be a new classic script that this algorithm will subsequently initialize.

  4. Set script's settings object to settings.

  5. Set script's base URL to baseURL.

  6. Set script's fetch options to options.

  7. Set script's muted errors to mutedErrors.

  8. Set script's parse error and error to rethrow to null.

  9. Record classic script creation time given script and sourceURLForWindowScripts.

  10. Let result be ParseScript(source, settings's realm, script).

    Passing script as the last parameter here ensures result.[[HostDefined]] will be script.

  11. If result is a list of errors, then:

    1. Set script's parse error and its error to rethrow to result[0].

    2. Return script.

  12. Set script's record to result.

  13. Return script.

To create a JavaScript module script, given a string source, an environment settings object settings, a URL baseURL, and a script fetch options options:

  1. If scripting is disabled for settings, then set source to the empty string.

  2. Let script be a new module script that this algorithm will subsequently initialize.

  3. Set script's settings object to settings.

  4. Set script's base URL to baseURL.

  5. Set script's fetch options to options.

  6. Set script's parse error and error to rethrow to null.

  7. Let result be ParseModule(source, settings's realm, script).

    Passing script as the last parameter here ensures result.[[HostDefined]] will be script.

  8. If result is a list of errors, then:

    1. Set script's parse error to result[0].

    2. Return script.

  9. For each ModuleRequest record requested of result.[[RequestedModules]]:

    1. If requested.[[Attributes]] contains a Record entry such that entry.[[Key]] is not "type", then:

      1. Let error be a new SyntaxError exception.

      2. Set script's parse error to error.

      3. Return script.

      The JavaScript specification re-performs this validation when loading script's dependencies. It is duplicated here to skip unnecessary work given that, in case of an invalid attribute key, loading the module graph would fail anyway. Additionally, this makes the errors reported for invalid static imports consistent with dynamic imports, for which invalid attributes are reported before calling into HTML and thus before validating the imported specifier.

    2. Resolve a module specifier given script and requested.[[Specifier]], catching any exceptions.

    3. If the previous step threw an exception, then:

      1. Set script's parse error to that exception.

      2. Return script.

    4. Let moduleType be the result of running the module type from module request steps given requested.

    5. If the result of running the module type allowed steps given moduleType and settings is false, then:

      1. Let error be a new TypeError exception.

      2. Set script's parse error to error.

      3. Return script.

    This step is essentially validating all of the requested module specifiers and type attributes. We treat a module with unresolvable module specifiers or unsupported type attributes the same as one that cannot be parsed; in both cases, a syntactic issue makes it impossible to ever contemplate linking the module later.

  10. Set script's record to result.

  11. Return script.

To create a CSS module script, given a string source and an environment settings object settings:

  1. Let script be a new module script that this algorithm will subsequently initialize.

  2. Set script's settings object to settings.

  3. Set script's base URL and fetch options to null.

  4. Set script's parse error and error to rethrow to null.

  5. Let sheet be the result of running the steps to create a constructed CSSStyleSheet with an empty dictionary as the argument.

  6. Run the steps to synchronously replace the rules of a CSSStyleSheet on sheet given source.

    If this throws an exception, catch it, and set script's parse error to that exception, and return script.

    The steps to synchronously replace the rules of a CSSStyleSheet will throw if source contains any @import rules. This is by-design for now because there is not yet an agreement on how to handle these for CSS module scripts; therefore they are blocked altogether until a consensus is reached.

  7. Set script's record to the result of CreateDefaultExportSyntheticModule(sheet).

  8. Return script.

To create a JSON module script, given a string source and an environment settings object settings:

  1. Let script be a new module script that this algorithm will subsequently initialize.

  2. Set script's settings object to settings.

  3. Set script's base URL and fetch options to null.

  4. Set script's parse error and error to rethrow to null.

  5. Let result be ParseJSONModule(source).

    If this throws an exception, catch it, and set script's parse error to that exception, and return script.

  6. Set script's record to result.

  7. Return script.

The module type from module request steps, given a ModuleRequest Record moduleRequest, are as follows:

  1. Let moduleType be "javascript".

  2. If moduleRequest.[[Attributes]] has a Record entry such that entry.[[Key]] is "type", then:

    1. If entry.[[Value]] is "javascript", then set moduleType to null.

      This specification uses the "javascript" module type internally for JavaScript module scripts, so this step is needed to prevent modules from being imported using a "javascript" type attribute (a null moduleType will cause the module type allowed check to fail).

    2. Otherwise, set moduleType to entry.[[Value]].

  3. Return moduleType.

The module type allowed steps, given a string moduleType and an environment settings object settings, are as follows:

  1. If moduleType is not "javascript", "css", or "json", then return false.

  2. If moduleType is "css" and the CSSStyleSheet interface is not exposed in settings's realm, then return false.

  3. Return true.

The fetch destination from module type steps, given a destination defaultDestination and a string moduleType, are as follows:

  1. If moduleType is "json", then return "json".
  2. If moduleType is "css", then return "style".
  3. Return defaultDestination.
8.1.4.4 Calling scripts

To run a classic script given a classic script script and an optional boolean rethrow errors (default false):

  1. Let settings be the settings object of script.

  2. Check if we can run script with settings. If this returns "do not run" then return NormalCompletion(empty).

  3. Record classic script execution start time given script.

  4. Prepare to run script given settings.

  5. Let evaluationStatus be null.

  6. If script's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.

  7. Otherwise, set evaluationStatus to ScriptEvaluation(script's record).

    If ScriptEvaluation does not complete because the user agent has aborted the running script, leave evaluationStatus as null.

  8. If evaluationStatus is an abrupt completion, then:

    1. If rethrow errors is true and script's muted errors is false, then:

      1. Clean up after running script with settings.

      2. Rethrow evaluationStatus.[[Value]].

    2. If rethrow errors is true and script's muted errors is true, then:

      1. Clean up after running script with settings.

      2. Throw a "NetworkError" DOMException.

    3. Otherwise, rethrow errors is false. Perform the following steps:

      1. Report an exception given by evaluationStatus.[[Value]] for script's settings object's global object.

      2. Clean up after running script with settings.

      3. Return evaluationStatus.

  9. Clean up after running script with settings.

  10. If evaluationStatus is a normal completion, then return evaluationStatus.

  11. If we've reached this point, evaluationStatus was left as null because the script was aborted prematurely during evaluation. Return Completion { [[Type]]: throw, [[Value]]: a new "QuotaExceededError" DOMException, [[Target]]: empty }.

To run a module script given a module script script and an optional boolean preventErrorReporting (default false):

  1. Let settings be the settings object of script.

  2. Check if we can run script with settings. If this returns "do not run", then return a promise resolved with undefined.

  3. Record module script execution start time given script.

  4. Prepare to run script given settings.

  5. Let evaluationPromise be null.

  6. If script's error to rethrow is not null, then set evaluationPromise to a promise rejected with script's error to rethrow.

  7. Otherwise:

    1. Let record be script's record.

    2. Set evaluationPromise to record.Evaluate().

      This step will recursively evaluate all of the module's dependencies.

      If Evaluate fails to complete as a result of the user agent aborting the running script, then set evaluationPromise to a promise rejected with a new "QuotaExceededError" DOMException.

  8. If preventErrorReporting is false, then upon rejection of evaluationPromise with reason, report an exception given by reason for script's settings object's global object.

  9. Clean up after running script with settings.

  10. Return evaluationPromise.

The steps to check if we can run script with an environment settings object settings are as follows. They return either "run" or "do not run".

  1. If the global object specified by settings is a Window object whose Document object is not fully active, then return "do not run".

  2. If scripting is disabled for settings, then return "do not run".

  3. Return "run".

The steps to prepare to run script with an environment settings object settings are as follows:

  1. Push settings's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

  2. Add settings to the surrounding agent's event loop's currently running task's script evaluation environment settings object set.

The steps to clean up after running script with an environment settings object settings are as follows:

  1. Assert: settings's realm execution context is the running JavaScript execution context.

  2. Remove settings's realm execution context from the JavaScript execution context stack.

  3. If the JavaScript execution context stack is now empty, perform a microtask checkpoint. (If this runs scripts, these algorithms will be invoked reentrantly.)

These algorithms are not invoked by one script directly calling another, but they can be invoked reentrantly in an indirect manner, e.g. if a script dispatches an event which has event listeners registered.

The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.

8.1.4.5 Killing scripts

Although the JavaScript specification does not account for this possibility, it's sometimes necessary to abort a running script. This causes any ScriptEvaluation or Source Text Module Record Evaluate invocations to cease immediately, emptying the JavaScript execution context stack without triggering any of the normal mechanisms like finally blocks. [JAVASCRIPT]

User agents may impose resource limitations on scripts, for example CPU quotas, memory limits, total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user agent may either throw a "QuotaExceededError" DOMException, abort the script without an exception, prompt the user, or throttle script execution.

For example, the following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue.

<script>
 while (true) { /* loop */ }
</script>

User agents are encouraged to allow users to disable scripting whenever the user is prompted either by a script (e.g. using the window.alert() API) or because of a script's actions (e.g. because it has exceeded a time limit).

If scripting is disabled while a script is executing, the script should be terminated immediately.

User agents may allow users to specifically disable scripts just for the purposes of closing a browsing context.

For example, the prompt mentioned in the example above could also offer the user with a mechanism to just close the page entirely, without running any unload event handlers.

8.1.4.6 Runtime script errors

reportError

Support in all current engines.

Firefox93+Safari15.4+Chrome95+
Opera?Edge95+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
self.reportError(e)

Dispatches an error event at the global object for the given value e, in the same fashion as an unhandled exception.

To extract error information from a JavaScript value exception:

  1. Let attributes be an empty map keyed by IDL attributes.

  2. Set attributes[error] to exception.

  3. Set attributes[message], attributes[filename], attributes[lineno], and attributes[colno] to implementation-defined values derived from exception.

    Browsers implement behavior not specified here or in the JavaScript specification to gather values which are helpful, including in unusual cases (e.g., eval). In the future, this might be specified in greater detail.

  4. Return attributes.

To report an exception exception which is a JavaScript value, for a particular global object global and optional boolean omitError (default false):

  1. Let notHandled be true.

  2. Let errorInfo be the result of extracting error information from exception.

  3. Let script be a script found in an implementation-defined way, or null. This should usually be the running script (most notably during run a classic script).

    Implementations have not yet settled on interoperable behavior for which script is used to determine whether errors are muted in less common cases.

  4. If script is a classic script and script's muted errors is true, then set errorInfo[error] to null, errorInfo[message] to "Script error.", errorInfo[filename] to the empty string, errorInfo[lineno] to 0, and errorInfo[colno] to 0.

  5. If omitError is true, then set errorInfo[error] to null.

  6. If global is not in error reporting mode, then:

    1. Set global's in error reporting mode to true.
    2. If global implements EventTarget, then set notHandled to the result of firing an event named error at global, using ErrorEvent, with the cancelable attribute initialized to true, and additional attributes initialized according to errorInfo.

      Returning true in an event handler cancels the event per the event handler processing algorithm.

    3. Set global's in error reporting mode to false.

  7. If notHandled is true, then:

    1. Set errorInfo[error] to null.

    2. If global implements DedicatedWorkerGlobalScope, queue a global task on the DOM manipulation task source with the global's associated Worker's relevant global object to run these steps:

      1. Let workerObject be the Worker object associated with global.

      2. Set notHandled be the result of firing an event named error at workerObject, using ErrorEvent, with the cancelable attribute initialized to true, and additional attributes initialized according to errorInfo.

      3. If notHandled is true, then report exception for workerObject's relevant global object with omitError set to true.

        The actual exception value will not be available in the owner realm, but the user agent still carries through enough information to set the message, filename, and other attributes, as well as potentially report to a developer console.

  8. Otherwise, the user agent may report exception to a developer console.

If the implicit port connecting a worker to its Worker object has been disentangled (i.e. if the parent worker has been terminated), then the user agent must act as if the Worker object had no error event handler and as if that worker's onerror attribute was null, but must otherwise act as described above.

Thus, error reports propagate up to the chain of dedicated workers up to the original Document, even if some of the workers along this chain have been terminated and garbage collected.

Previous revisions of this standard defined an algorithm to report the exception. As part of issue #958, this has been superseded by report an exception which behaves differently and takes different inputs. Issue #10516 tracks updating the specification ecosystem.


The reportError(e) method steps are to report an exception e for this.

It is unclear whether muting is applicable here. In Chrome and Safari it is muted, but in Firefox it is not. See also issue #958.


ErrorEvent

Support in all current engines.

Firefox27+Safari6+Chrome10+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

The ErrorEvent interface is defined as follows:

[Exposed=*]
interface ErrorEvent : Event {
  constructor(DOMString type, optional ErrorEventInit eventInitDict = {});

  readonly attribute DOMString message;
  readonly attribute USVString filename;
  readonly attribute unsigned long lineno;
  readonly attribute unsigned long colno;
  readonly attribute any error;
};

dictionary ErrorEventInit : EventInit {
  DOMString message = "";
  USVString filename = "";
  unsigned long lineno = 0;
  unsigned long colno = 0;
  any error;
};

The message attribute must return the value it was initialized to. It represents the error message.

The filename attribute must return the value it was initialized to. It represents the URL of the script in which the error originally occurred.

The lineno attribute must return the value it was initialized to. It represents the line number where the error occurred in the script.

The colno attribute must return the value it was initialized to. It represents the column number where the error occurred in the script.

The error attribute must return the value it was initialized to. It must initially be initialized to undefined. Where appropriate, it is set to the object representing the error (e.g., the exception object in the case of an uncaught exception).

8.1.4.7 Unhandled promise rejections

Window/rejectionhandled_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?

In addition to synchronous runtime script errors, scripts may experience asynchronous promise rejections, tracked via the unhandledrejection and rejectionhandled events. Tracking these rejections is done via the HostPromiseRejectionTracker abstract operation, but reporting them is defined here.

To notify about rejected promises given a global object global:

  1. Let list be a clone of global's about-to-be-notified rejected promises list.

  2. If list is empty, then return.

  3. Empty global's about-to-be-notified rejected promises list.

  4. Queue a global task on the DOM manipulation task source given global to run the following step:

    1. For each promise p of list:

      1. If p.[[PromiseIsHandled]] is true, then continue.

      2. Let notCanceled be the result of firing an event named unhandledrejection at global, using PromiseRejectionEvent, with the cancelable attribute initialized to true, the promise attribute initialized to p, and the reason attribute initialized to p.[[PromiseResult]].

      3. If notCanceled is true, then the user agent may report p.[[PromiseResult]] to a developer console.

      4. If p.[[PromiseIsHandled]] is false, then append p to global's outstanding rejected promises weak set.

PromiseRejectionEvent

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?

The PromiseRejectionEvent interface is defined as follows:

[Exposed=*]
interface PromiseRejectionEvent : Event {
  constructor(DOMString type, PromiseRejectionEventInit eventInitDict);

  readonly attribute object promise;
  readonly attribute any reason;
};

dictionary PromiseRejectionEventInit : EventInit {
  required object promise;
  any reason;
};

PromiseRejectionEvent/promise

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?

The promise attribute must return the value it was initialized to. It represents the promise which this notification is about.

Because of how Web IDL conversion rules for Promise<T> types always wrap the input into a new promise, the promise attribute is of type object instead, which is more appropriate for representing an opaque handle to the original promise object.

PromiseRejectionEvent/reason

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?

The reason attribute must return the value it was initialized to. It represents the rejection reason for the promise.

8.1.4.8 Import map parse results

An import map parse result is a struct that is similar to a script, and also can be stored in a script element's result, but is not counted as a script for other purposes. It has the following items:

An import map
An import map or null.
An error to rethrow
A JavaScript value representing an error that will prevent using this import map, when non-null.

To create an import map parse result given a string input and a URL baseURL:

  1. Let result be an import map parse result whose import map is null and whose error to rethrow is null.

  2. Parse an import map string given input and baseURL, catching any exceptions. If this threw an exception, then set result's error to rethrow to that exception. Otherwise, set result's import map to the return value.

  3. Return result.

To register an import map given a Window global and an import map parse result result:

  1. If result's error to rethrow is not null, then report an exception given by result's error to rethrow for global and return.

  2. Assert: global's import map is an empty import map.

  3. Set global's import map to result's import map.

8.1.5 Module specifier resolution

8.1.5.1 The resolution algorithm

The resolve a module specifier algorithm is the primary entry point for converting module specifier strings into URLs. When no import maps are involved, it is relatively straightforward, and reduces to resolving a URL-like module specifier.

When there is a non-empty import map present, the behavior is more complex. It checks candidate entries from all applicable module specifier maps, from most-specific to least-specific scopes (falling back to the top-level unscoped imports), and from most-specific to least-specific prefixes. For each candidate, the resolve an imports match algorithm will give on the following results:

In the end, if no successful resolution is found via any of the candidate module specifier maps, resolve a module specifier will throw an exception. Thus the result is always either a URL or a thrown exception.

To resolve a module specifier given a script-or-null referringScript and a string specifier:

  1. Let settingsObject and baseURL be null.

  2. If referringScript is not null, then:

    1. Set settingsObject to referringScript's settings object.

    2. Set baseURL to referringScript's base URL.

  3. Otherwise:

    1. Assert: there is a current settings object.

    2. Set settingsObject to the current settings object.

    3. Set baseURL to settingsObject's API base URL.

  4. Let importMap be an empty import map.

  5. If settingsObject's global object implements Window, then set importMap to settingsObject's global object's import map.

  6. Let baseURLString be baseURL, serialized.

  7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.

  8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier.

  9. For each scopePrefixscopeImports of importMap's scopes:

    1. If scopePrefix is baseURLString, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of baseURLString, then:

      1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports.

      2. If scopeImportsMatch is not null, then return scopeImportsMatch.

  10. Let topLevelImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports.

  11. If topLevelImportsMatch is not null, then return topLevelImportsMatch.

  12. At this point, specifier wasn't remapped to anything by importMap, but it might have been able to be turned into a URL.

    If asURL is not null, then return asURL.

  13. Throw a TypeError indicating that specifier was a bare specifier, but was not remapped to anything by importMap.

To resolve an imports match, given a string normalizedSpecifier, a URL-or-null asURL, and a module specifier map specifierMap:

  1. For each specifierKeyresolutionResult of specifierMap:

    1. If specifierKey is normalizedSpecifier, then:

      1. If resolutionResult is null, then throw a TypeError indicating that resolution of specifierKey was blocked by a null entry.

        This will terminate the entire resolve a module specifier algorithm, without any further fallbacks.

      2. Assert: resolutionResult is a URL.

      3. Return resolutionResult.

    2. If all of the following are true:

      • specifierKey ends with U+002F (/);

      • specifierKey is a code unit prefix of normalizedSpecifier; and

      • either asURL is null, or asURL is special,

      then:

      1. If resolutionResult is null, then throw a TypeError indicating that the resolution of specifierKey was blocked by a null entry.

        This will terminate the entire resolve a module specifier algorithm, without any further fallbacks.

      2. Assert: resolutionResult is a URL.

      3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix.

      4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing.

      5. Let url be the result of URL parsing afterPrefix with resolutionResult.

      6. If url is failure, then throw a TypeError indicating that resolution of normalizedSpecifier was blocked since the afterPrefix portion could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.

        This will terminate the entire resolve a module specifier algorithm, without any further fallbacks.

      7. Assert: url is a URL.

      8. If the serialization of resolutionResult is not a code unit prefix of the serialization of url, then throw a TypeError indicating that the resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.

        This will terminate the entire resolve a module specifier algorithm, without any further fallbacks.

      9. Return url.

  2. Return null.

    The resolve a module specifier algorithm will fall back to a less-specific scope, or to "imports", if possible.

To resolve a URL-like module specifier, given a string specifier and a URL baseURL:

  1. If specifier starts with "/", "./", or "../", then:

    1. Let url be the result of URL parsing specifier with baseURL.

    2. If url is failure, then return null.

      One way this could happen is if specifier is "../foo" and baseURL is a data: URL.

    3. Return url.

    This includes cases where specifier starts with "//", i.e., scheme-relative URLs. Thus, url might end up with a different host than baseURL.

  2. Let url be the result of URL parsing specifier (with no base URL).

  3. If url is failure, then return null.

  4. Return url.

8.1.5.2 Import maps

An import map allows control over module specifier resolution. Import maps are delivered via inline script elements with their type attribute set to "importmap", and with their child text content containing a JSON representation of the import map.

Only one import map is processed per Document. After the first import map is seen, others will be ignored, with their corresponding script elements generating error events. Similarly, once any modules have been imported, e.g., via import() expressions or script elements with their type attribute set to "module", further import maps will be ignored.

These restrictions, as well as the lack of support for external import maps, are in place to keep the initial version of the feature simple. They might be lifted over time as implementer bandwidth allows.

The simplest use of import maps is to globally remap a bare module specifier:

{
  "imports": {
    "moment": "/node_modules/moment/src/moment.js"
  }
}

This enables statements like import moment from "moment"; to work, fetching and evaluating the JavaScript module at the /node_modules/moment/src/moment.js URL.

An import map can remap a class of module specifiers into a class of URLs by using trailing slashes, like so:

{
  "imports": {
    "moment/": "/node_modules/moment/src/"
  }
}

This enables statements like import localeData from "moment/locale/zh-cn.js"; to work, fetching and evaluating the JavaScript module at the /node_modules/moment/src/locale/zh-cn.js URL. Such trailing-slash mappings are often combined with bare-specifier mappings, e.g.

{
  "imports": {
    "moment": "/node_modules/moment/src/moment.js",
    "moment/": "/node_modules/moment/src/"
  }
}

so that both the "main module" specified by "moment" and the "submodules" specified by paths such as "moment/locale/zh-cn.js" are available.

Bare specifiers are not the only type of module specifiers which import maps can remap. "URL-like" specifiers, i.e., those that are either parseable as absolute URLs or start with "/", "./", or "../", can be remapped as well:

{
  "imports": {
    "https://cdn.example.com/vue/dist/vue.runtime.esm.js": "/node_modules/vue/dist/vue.runtime.esm.js",
    "/js/app.mjs": "/js/app-8e0d62a03.mjs",
    "../helpers/": "https://cdn.example/helpers/"
  }
}

Note how the URL to be remapped, as well as the URL being mapped to, can be specified either as absolute URLs, or as relative URLs starting with "/", "./", or "../". (They cannot be specified as relative URLs without those starting sigils, as those help distinguish from bare module specifiers.) Also note how the trailing slash mapping works in this context as well.

Such remappings operate on the post-canonicalization URL, and do not require a match between the literal strings supplied in the import map key and the imported module specifier. So for example, if this import map was included on https://example.com/app.html, then not only would import "/js/app.mjs" be remapped, but so would import "./js/app.mjs" and import "./foo/../js/app.mjs".

All previous examples have globally remapped module specifiers, by using the top-level "imports" key in the import map. The top-level "scopes" key can be used to provide localized remappings, which only apply when the referring module matches a specific URL prefix. For example:

{
  "scopes": {
    "/a/" : {
      "moment": "/node_modules/moment/src/moment.js"
    },
    "/b/" : {
      "moment": "https://cdn.example.com/moment/src/moment.js"
    }
  }
}

With this import map, the statement import "moment" will have different meanings depending on which referrer script contains the statement:

A typical usage of scopes is to allow multiple versions of the "same" module to exist in a web application, with some parts of the module graph importing one version, and other parts importing another version.

Scopes can overlap each other, and overlap the global "imports" specifier map. At resolution time, scopes are consulted in order of most- to least-specific, where specificity is measured by sorting the scopes using the code unit less than operation. So, for example, "/scope2/scope3/" is treated as more specific than "/scope2/", which is treated as more specific than the top-level (unscoped) mappings.

The following import map illustrates this:

{
  "imports": {
    "a": "/a-1.mjs",
    "b": "/b-1.mjs",
    "c": "/c-1.mjs"
  },
  "scopes": {
    "/scope2/": {
      "a": "/a-2.mjs"
    },
    "/scope2/scope3/": {
      "b": "/b-3.mjs"
    }
  }
}

This results in the following resolutions (using relative URLs for brevity):

Specifier
"a" "b" "c"
Referrer /scope1/r.mjs /a-1.mjs /b-1.mjs /c-1.mjs
/scope2/r.mjs /a-2.mjs /b-1.mjs /c-1.mjs
/scope2/scope3/r.mjs /a-2.mjs /b-3.mjs /c-1.mjs

Import maps can also be used to provide modules with integrity metadata to be used in Subresource Integrity checks. [SRI]

The following import map illustrates this:

{
  "imports": {
    "a": "/a-1.mjs",
    "b": "/b-1.mjs",
    "c": "/c-1.mjs"
  },
  "integrity": {
    "/a-1.mjs": "sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7",
    "/d-1.mjs": "sha384-MBO5IDfYaE6c6Aao94oZrIOiC6CGiSN2n4QUbHNPhzk5Xhm0djZLQqTpL0HzTUxk"
  }
}

The above example provides integrity metadata to be enforced on the modules /a-1.mjs and /d-1.mjs, even if the latter is not defined as an import in the map.


The child text content of a script element representing an import map must match the following import map authoring requirements:

A valid module specifier map is a JSON object that meets the following requirements:

8.1.5.3 Import map processing model

Formally, an import map is a struct with three items:

A module specifier map is an ordered map whose keys are strings and whose values are either URLs or nulls.

A module integrity map is an ordered map whose keys are URLs and whose values are strings that will be used as integrity metadata.

An empty import map is an import map with its imports and scopes both being empty maps.


Each Window has an import map, initially an empty import map.

Each Window has an import maps allowed boolean, initially true.

To disallow further import maps given an environment settings object settingsObject:

  1. Let global be settingsObject's global object.

  2. If global does not implement Window, then return.

  3. Set global's import maps allowed to false.

Import maps are currently disallowed once any module loading has started, or once a single import map is loaded. These restrictions might be lifted in future specification revisions.


To parse an import map string, given a string input and a URL baseURL:

  1. Let parsed be the result of parsing a JSON string to an Infra value given input.

  2. If parsed is not an ordered map, then throw a TypeError indicating that the top-level value needs to be a JSON object.

  3. Let sortedAndNormalizedImports be an empty ordered map.

  4. If parsed["imports"] exists, then:

    1. If parsed["imports"] is not an ordered map, then throw a TypeError indicating that the value for the "imports" top-level key needs to be a JSON object.

    2. Set sortedAndNormalizedImports to the result of sorting and normalizing a module specifier map given parsed["imports"] and baseURL.

  5. Let sortedAndNormalizedScopes be an empty ordered map.

  6. If parsed["scopes"] exists, then:

    1. If parsed["scopes"] is not an ordered map, then throw a TypeError indicating that the value for the "scopes" top-level key needs to be a JSON object.

    2. Set sortedAndNormalizedScopes to the result of sorting and normalizing scopes given parsed["scopes"] and baseURL.

  7. Let normalizedIntegrity be an empty ordered map.

  8. If parsed["integrity"] exists, then:

    1. If parsed["integrity"] is not an ordered map, then throw a TypeError indicating that the value for the "integrity" top-level key needs to be a JSON object.

    2. Set normalizedIntegrity to the result of normalizing a module integrity map given parsed["integrity"] and baseURL.

  9. If parsed's keys contains any items besides "imports", "scopes", or "integrity", then the user agent should report a warning to the console indicating that an invalid top-level key was present in the import map.

    This can help detect typos. It is not an error, because that would prevent any future extensions from being added backward-compatibly.

  10. Return an import map whose imports are sortedAndNormalizedImports, whose scopes are sortedAndNormalizedScopes, and whose integrity are normalizedIntegrity.

The import map that results from this parsing algorithm is highly normalized. For example, given a base URL of https://example.com/base/page.html, the input

{
  "imports": {
    "/app/helper": "node_modules/helper/index.mjs",
    "lodash": "/node_modules/lodash-es/lodash.js"
  }
}

will generate an import map with imports of

«[
  "https://example.com/app/helper" → https://example.com/base/node_modules/helper/index.mjs
  "lodash" → https://example.com/node_modules/lodash-es/lodash.js
]»

and (despite nothing being present in the input string) an empty ordered map for its scopes.

To sort and normalize a module specifier map, given an ordered map originalMap and a URL baseURL:

  1. Let normalized be an empty ordered map.

  2. For each specifierKeyvalue of originalMap:

    1. Let normalizedSpecifierKey be the result of normalizing a specifier key given specifierKey and baseURL.

    2. If normalizedSpecifierKey is null, then continue.

    3. If value is not a string, then:

      1. The user agent may report a warning to the console indicating that addresses need to be strings.

      2. Set normalized[normalizedSpecifierKey] to null.

      3. Continue.

    4. Let addressURL be the result of resolving a URL-like module specifier given value and baseURL.

    5. If addressURL is null, then:

      1. The user agent may report a warning to the console indicating that the address was invalid.

      2. Set normalized[normalizedSpecifierKey] to null.

      3. Continue.

    6. If specifierKey ends with U+002F (/), and the serialization of addressURL does not end with U+002F (/), then:

      1. The user agent may report a warning to the console indicating that an invalid address was given for the specifier key specifierKey; since specifierKey ends with a slash, the address needs to as well.

      2. Set normalized[normalizedSpecifierKey] to null.

      3. Continue.

    7. Set normalized[normalizedSpecifierKey] to addressURL.

  3. Return the result of sorting in descending order normalized, with an entry a being less than an entry b if a's key is code unit less than b's key.

To sort and normalize scopes, given an ordered map originalMap and a URL baseURL:

  1. Let normalized be an empty ordered map.

  2. For each scopePrefixpotentialSpecifierMap of originalMap:

    1. If potentialSpecifierMap is not an ordered map, then throw a TypeError indicating that the value of the scope with prefix scopePrefix needs to be a JSON object.

    2. Let scopePrefixURL be the result of URL parsing scopePrefix with baseURL.

    3. If scopePrefixURL is failure, then:

      1. The user agent may report a warning to the console that the scope prefix URL was not parseable.

      2. Continue.

    4. Let normalizedScopePrefix be the serialization of scopePrefixURL.

    5. Set normalized[normalizedScopePrefix] to the result of sorting and normalizing a module specifier map given potentialSpecifierMap and baseURL.

  3. Return the result of sorting in descending order normalized, with an entry a being less than an entry b if a's key is code unit less than b's key.

In the above two algorithms, sorting keys and scopes in descending order has the effect of putting "foo/bar/" before "foo/". This in turn gives "foo/bar/" a higher priority than "foo/" during module specifier resolution.

To normalize a module integrity map, given an ordered map originalMap:

  1. Let normalized be an empty ordered map.

  2. For each keyvalue of originalMap:

    1. Let resolvedURL be the result of resolving a URL-like module specifier given key and baseURL.

      Unlike "imports", keys of the integrity map are treated as URLs, not module specifiers. However, we use the resolve a URL-like module specifier algorithm to prohibit "bare" relative URLs like foo, which could be mistaken for module specifiers.

    2. If resolvedURL is null, then:

      1. The user agent may report a warning to the console indicating that the key failed to resolve.

      2. Continue.

    3. If value is not a string, then:

      1. The user agent may report a warning to the console indicating that integrity metadata values need to be strings.

      2. Continue.

    4. Set normalized[resolvedURL] to value.

  3. Return normalized.

To normalize a specifier key, given a string specifierKey and a URL baseURL:

  1. If specifierKey is the empty string, then:

    1. The user agent may report a warning to the console indicating that specifier keys may not be the empty string.

    2. Return null.

  2. Let url be the result of resolving a URL-like module specifier, given specifierKey and baseURL.

  3. If url is not null, then return the serialization of url.

  4. Return specifierKey.

8.1.6 JavaScript specification host hooks

The JavaScript specification contains a number of implementation-defined abstract operations, that vary depending on the host environment. This section defines them for user agent hosts.

8.1.6.1 HostEnsureCanAddPrivateElement(O)

JavaScript contains an implementation-defined HostEnsureCanAddPrivateElement(O) abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }.

  2. Return NormalCompletion(unused).

JavaScript private fields can be applied to arbitrary objects. Since this can dramatically complicate implementation for particularly-exotic host objects, the JavaScript language specification provides this hook to allow hosts to reject private fields on objects meeting a host-defined criteria. In the case of HTML, WindowProxy and Location have complicated semantics — particularly around navigation and security — that make implementation of private field semantics challenging, so our implementation simply rejects those objects.

8.1.6.2 HostEnsureCanCompileStrings(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg)

JavaScript contains an implementation-defined HostEnsureCanCompileStrings abstract operation, redefined by the Dynamic Code Brand Checks proposal. User agents must use the following implementation: [JAVASCRIPT] [JSDYNAMICCODEBRANDCHECKS]

  1. Perform ? EnsureCSPDoesNotBlockStringCompilation(realm, parameterStrings, bodyString, codeString, compilationType, parameterArgs, bodyArg). [CSP]

8.1.6.3 HostGetCodeForEval(argument)

The Dynamic Code Brand Checks proposal contains an implementation-defined HostGetCodeForEval(argument) abstract operation. User agents must use the following implementation: [JSDYNAMICCODEBRANDCHECKS]

  1. If argument is a TrustedScript object, then return argument's data.

  2. Otherwise, return no-code.

8.1.6.4 HostPromiseRejectionTracker(promise, operation)

JavaScript contains an implementation-defined HostPromiseRejectionTracker(promise, operation) abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let script be the running script.

  2. If script is a classic script and script's muted errors is true, then return.

  3. Let settingsObject be the current settings object.

  4. If script is not null, then set settingsObject to script's settings object.

  5. Let global be settingsObject's global object.

  6. If operation is "reject", then:

    1. Append promise to global's about-to-be-notified rejected promises list.

  7. If operation is "handle", then:

    1. If global's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.

    2. If global's outstanding rejected promises weak set does not contain promise, then return.

    3. Remove promise from global's outstanding rejected promises weak set.

    4. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent, with the promise attribute initialized to promise, and the reason attribute initialized to promise.[[PromiseResult]].

8.1.6.5 HostSystemUTCEpochNanoseconds(global)

The Temporal proposal contains an implementation-defined HostSystemUTCEpochNanoseconds abstract operation. User agents must use the following implementation: [JSTEMPORAL]

  1. Let settingsObject be global's relevant settings object.

  2. Let time be settingsObject's current wall time.

  3. Let ns be the number of nanoseconds from the Unix epoch to time, rounded to the nearest integer.

  4. Return the result of clamping ns between nsMinInstant and nsMaxInstant.

8.1.6.6 Job-related host hooks

Reference/Global_Objects/Promise#Incumbent_settings_object_tracking

Support in one engine only.

Firefox50+SafariNoChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The JavaScript specification defines Jobs to be scheduled and run later by the host, as well as JobCallback Records which encapsulate JavaScript functions that are called as part of jobs. The JavaScript specification contains a number of implementation-defined abstract operations that lets the host define how jobs are scheduled and how JobCallbacks are handled. HTML uses these abstract operations to track the incumbent settings object in promises and FinalizationRegistry callbacks by saving and restoring the incumbent settings object and a JavaScript execution context for the active script in JobCallbacks. This section defines them for user agent hosts.

8.1.6.6.1 HostCallJobCallback(callback, V, argumentsList)

JavaScript contains an implementation-defined HostCallJobCallback(callback, V, argumentsList) abstract operation to let hosts restore state when invoking JavaScript callbacks from inside tasks. User agents must use the following implementation: [JAVASCRIPT]

  1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]].

  2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]].

  3. Prepare to run a callback with incumbent settings.

    This affects the incumbent concept while the callback runs.

  4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.

    This affects the active script while the callback runs.

  5. Let result be Call(callback.[[Callback]], V, argumentsList).

  6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.

  7. Clean up after running a callback with incumbent settings.

  8. Return result.

8.1.6.6.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)

JavaScript has the ability to register objects with FinalizationRegistry objects, in order to schedule a cleanup action if they are found to be garbage collected. The JavaScript specification contains an implementation-defined HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry) abstract operation to schedule the cleanup action.

The timing and occurrence of cleanup work is implementation-defined in the JavaScript specification. User agents might differ in when and whether an object is garbage collected, affecting both whether the return value of the WeakRef.prototype.deref() method is undefined, and whether FinalizationRegistry cleanup callbacks occur. There are well-known cases in popular web browsers where objects are not accessible to JavaScript, but they remain retained by the garbage collector indefinitely. HTML clears kept-alive WeakRef objects in the perform a microtask checkpoint algorithm. Authors would be best off not depending on the timing details of garbage collection implementations.

Cleanup actions do not take place interspersed with synchronous JavaScript execution, but rather happen in queued tasks. User agents must use the following implementation: [JAVASCRIPT]

  1. Let global be finalizationRegistry.[[Realm]]'s global object.

  2. Queue a global task on the JavaScript engine task source given global to perform the following steps:

    1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]]'s environment settings object.

    2. Check if we can run script with entry. If this returns "do not run", then return.

    3. Prepare to run script with entry.

      This affects the entry concept while the cleanup callback runs.

    4. Let result be the result of performing CleanupFinalizationRegistry(finalizationRegistry).

    5. Clean up after running script with entry.

    6. If result is an abrupt completion, then report an exception given by result.[[Value]] for global.

8.1.6.6.3 HostEnqueueGenericJob(job, realm)

JavaScript contains an implementation-defined HostEnqueueGenericJob(job, realm) abstract operation to perform generic jobs in a particular realm (e.g., resolve promises resulting from Atomics.waitAsync). User agents must use the following implementation: [JAVASCRIPT]

  1. Let global be realm's global object.

  2. Queue a global task on the JavaScript engine task source given global to perform job().

8.1.6.6.4 HostEnqueuePromiseJob(job, realm)

JavaScript contains an implementation-defined HostEnqueuePromiseJob(job, realm) abstract operation to schedule Promise-related operations. HTML schedules these operations in the microtask queue. User agents must use the following implementation: [JAVASCRIPT]

  1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.

    If realm is not null, it is the realm of the author code that will run. When job is returned by NewPromiseReactionJob, it is the realm of the promise's handler function. When job is returned by NewPromiseResolveThenableJob, it is the realm of the then function.

    If realm is null, either no author code will run or author code is guaranteed to throw. For the former, the author may not have passed in code to run, such as in promise.then(null, null). For the latter, it is because a revoked Proxy was passed. In both cases, all the steps below that would otherwise use job settings get skipped.

    NewPromiseResolveThenableJob and NewPromiseReactionJob both seem to provide non-null realms (the current Realm Record) in the case of a revoked proxy. The previous text could be updated to reflect that.

  2. Queue a microtask to perform the following steps:

    1. If job settings is not null, then check if we can run script with job settings. If this returns "do not run" then return.

    2. If job settings is not null, then prepare to run script with job settings.

      This affects the entry concept while the job runs.

    3. Let result be job().

      job is an abstract closure returned by NewPromiseReactionJob or NewPromiseResolveThenableJob. The promise's handler function when job is returned by NewPromiseReactionJob, and the then function when job is returned by NewPromiseResolveThenableJob, are wrapped in JobCallback Records. HTML saves the incumbent settings object and a JavaScript execution context for to the active script in HostMakeJobCallback and restores them in HostCallJobCallback.

    4. If job settings is not null, then clean up after running script with job settings.

    5. If result is an abrupt completion, then report an exception given by result.[[Value]] for realm's global object.

      There is a very gnarly case where HostEnqueuePromiseJob is called with a null realm (e.g., because Promise.prototype.then was called with null handlers) but also the job returns abruptly (because the promise capability's resolve or reject handler threw, possibly because this is a subclass of Promise that takes the supplied functions and wraps them in throwing functions before passing them on to the function passed to the Promise superclass constructor. Which global is to be used then, considering that the current realm could be different at each of those steps, by using a Promise constructor or Promise.prototype.then from another realm? See issue #10526.

8.1.6.6.5 HostEnqueueTimeoutJob(job, realm, milliseconds)

JavaScript contains an implementation-defined HostEnqueueTimeoutJob(job, milliseconds) abstract operation to schedule an operation to be performed after a timeout. HTML schedules these operations using run steps after a timeout. User agents must use the following implementation: [JAVASCRIPT]

  1. Let global be realm's global object.

  2. Let timeoutStep be an algorithm step which queues a global task on the JavaScript engine task source given global to perform job().

  3. Run steps after a timeout given global, "JavaScript", milliseconds, and timeoutStep.

8.1.6.6.6 HostMakeJobCallback(callable)

JavaScript contains an implementation-defined HostMakeJobCallback(callable) abstract operation to let hosts attach state to JavaScript callbacks that are called from inside tasks. User agents must use the following implementation: [JAVASCRIPT]

  1. Let incumbent settings be the incumbent settings object.

  2. Let active script be the active script.

  3. Let script execution context be null.

  4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null, its Realm field set to active script's settings object's realm, and its ScriptOrModule set to active script's record.

    As seen below, this is used in order to propagate the current active script forward to the time when the job callback is invoked.

    A case where active script is non-null, and saving it in this way is useful, is the following:

    Promise.resolve('import(`./example.mjs`)').then(eval);

    Without this step (and the steps that use it in HostCallJobCallback), there would be no active script when the import() expression is evaluated, since eval() is a built-in function that does not originate from any particular script.

    With this step in place, the active script is propagated from the above code into the job, allowing import() to use the original script's base URL appropriately.

    active script can be null if the user clicks on the following button:

    <button onclick="Promise.resolve('import(`./example.mjs`)').then(eval)">Click me</button>

    In this case, the JavaScript function for the event handler will be created by the get the current value of the event handler algorithm, which creates a function with null [[ScriptOrModule]] value. Thus, when the promise machinery calls HostMakeJobCallback, there will be no active script to pass along.

    As a consequence, this means that when the import() expression is evaluated, there will still be no active script. Fortunately that is handled by our implementation of HostLoadImportedModule by falling back to using the current settings object's API base URL.

  5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.

8.1.6.7 Module-related host hooks

The JavaScript specification defines a syntax for modules, as well as some host-agnostic parts of their processing model. This specification defines the rest of their processing model: how the module system is bootstrapped, via the script element with type attribute set to "module", and how modules are fetched, resolved, and executed. [JAVASCRIPT]

Although the JavaScript specification speaks in terms of "scripts" versus "modules", in general this specification speaks in terms of classic scripts versus module scripts, since both of them use the script element.

modulePromise = import(specifier)

Returns a promise for the module namespace object for the module script identified by specifier. This allows dynamic importing of module scripts at runtime, instead of statically using the import statement form. The specifier will be resolved relative to the active script.

The returned promise will be rejected if an invalid specifier is given, or if a failure is encountered while fetching or evaluating the resulting module graph.

This syntax can be used inside both classic and module scripts. It thus provides a bridge into the module-script world, from the classic-script world.

url = import.meta.url

Returns the active module script's base URL.

This syntax can only be used inside module scripts.

url = import.meta.resolve(specifier)

Returns specifier, resolved relative to the active script. That is, this returns the URL that would be imported by using import(specifier).

Throws a TypeError exception if an invalid specifier is given.

This syntax can only be used inside module scripts.

A module map is a map keyed by tuples consisting of a URL record and a string. The URL record is the request URL at which the module was fetched, and the string indicates the type of the module (e.g. "javascript"). The module map's values are either a module script, null (used to represent failed fetches), or a placeholder value "fetching". Module maps are used to ensure that imported module scripts are only fetched, parsed, and evaluated once per Document or worker.

Since module maps are keyed by (URL, module type), the following code will create three separate entries in the module map, since it results in three different (URL, module type) tuples (all with "javascript" type):

import "https://example.com/module.mjs";
import "https://example.com/module.mjs#map-buster";
import "https://example.com/module.mjs?debug=true";

That is, URL queries and fragments can be varied to create distinct entries in the module map; they are not ignored. Thus, three separate fetches and three separate module evaluations will be performed.

In contrast, the following code would only create a single entry in the module map, since after applying the URL parser to these inputs, the resulting URL records are equal:

import "https://example.com/module2.mjs";
import "https:example.com/module2.mjs";
import "https://///example.com\\module2.mjs";
import "https://example.com/foo/../module2.mjs";

So in this second example, only one fetch and one module evaluation will occur.

Note that this behavior is the same as how shared workers are keyed by their parsed constructor url.

Since module type is also part of the module map key, the following code will create two separate entries in the module map (the type is "javascript" for the first, and "css" for the second):

<script type=module>
  import "https://example.com/module";
</script>
<script type=module>
  import "https://example.com/module" with { type: "css" };
</script>

This can result in two separate fetches and two separate module evaluations being performed.

In practice, due to the as-yet-unspecified memory cache (see issue #6110) the resource may only be fetched once in WebKit and Blink-based browsers. Additionally, as long as all module types are mutually exclusive, the module type check in fetch a single module script will fail for at least one of the imports, so at most one module evaluation will occur.

The purpose of including the type in the module map key is so that an import with the wrong type attribute does not prevent a different import of the same specifier but with the correct type from succeeding.

JavaScript module scripts are the default import type when importing from another JavaScript module; that is, when an import statement lacks a type import attribute the imported module script's type will be JavaScript. Attempting to import a JavaScript resource using an import statement with a type import attribute will fail:

<script type="module">
    // All of the following will fail, assuming that the imported .mjs files are served with a
    // JavaScript MIME type. JavaScript module scripts are the default and cannot be imported with
    // any import type attribute.
    import foo from "./foo.mjs" with { type: "javascript" };
    import foo2 from "./foo2.mjs" with { type: "js" };
    import foo3 from "./foo3.mjs" with { type: "" };
    await import("./foo4.mjs", { with: { type: null } });
    await import("./foo5.mjs", { with: { type: undefined } });
</script>
8.1.6.7.1 HostGetImportMetaProperties(moduleRecord)

Reference/Operators/import.meta/resolve

Support in all current engines.

Firefox106+Safari16.4+Chrome105+
Opera?Edge105+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Reference/Operators/import.meta

Support in all current engines.

Firefox62+Safari11.1+Chrome64+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS12+Chrome Android?WebView Android?Samsung Internet?Opera Android?

JavaScript contains an implementation-defined HostGetImportMetaProperties abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let moduleScript be moduleRecord.[[HostDefined]].

  2. Assert: moduleScript's base URL is not null, as moduleScript is a JavaScript module script.

  3. Let urlString be moduleScript's base URL, serialized.

  4. Let steps be the following steps, given the argument specifier:

    1. Set specifier to ? ToString(specifier).

    2. Let url be the result of resolving a module specifier given moduleScript and specifier.

    3. Return the serialization of url.

  5. Let resolveFunction be ! CreateBuiltinFunction(steps, 1, "resolve", « »).

  6. Return « Record { [[Key]]: "url", [[Value]]: urlString }, Record { [[Key]]: "resolve", [[Value]]: resolveFunction } ».

8.1.6.7.2 HostGetSupportedImportAttributes()

The Import Attributes proposal contains an implementation-defined HostGetSupportedImportAttributes abstract operation. User agents must use the following implementation: [JSIMPORTATTRIBUTES]

  1. Return « "type" ».

8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload)

JavaScript contains an implementation-defined HostLoadImportedModule abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let settingsObject be the current settings object.

  2. If settingsObject's global object implements WorkletGlobalScope or ServiceWorkerGlobalScope and loadState is undefined, then:

    loadState is undefined when the current fetching process has been initiated by a dynamic import() call, either directly or when loading the transitive dependencies of the dynamically imported module.

    1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.

    2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).

    3. Return.

  3. Let referencingScript be null.

  4. Let originalFetchOptions be the default classic script fetch options.

  5. Let fetchReferrer be "client".

  6. If referrer is a Script Record or a Module Record, then:

    1. Set referencingScript to referrer.[[HostDefined]].

    2. Set settingsObject to referencingScript's settings object.

    3. Set fetchReferrer to referencingScript's base URL.

    4. Set originalFetchOptions to referencingScript's fetch options.

    referrer is usually a Script Record or a Module Record, but it will not be so for event handlers per the get the current value of the event handler algorithm. For example, given:

    <button onclick="import('./foo.mjs')">Click me</button>

    If a click event occurs, then at the time the import() expression runs, GetActiveScriptOrModule will return null, and this operation will receive the current realm as a fallback referrer.

  7. Disallow further import maps given settingsObject.

  8. Let url be the result of resolving a module specifier given referencingScript and moduleRequest.[[Specifier]], catching any exceptions. If they throw an exception, let resolutionError be the thrown exception.

  9. If the previous step threw an exception, then:

    1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: resolutionError, [[Target]]: empty }.

    2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).

    3. Return.

  10. Let fetchOptions be the result of getting the descendant script fetch options given originalFetchOptions, url, and settingsObject.

  11. Let destination be "script".

  12. Let fetchClient be settingsObject.

  13. If loadState is not undefined, then:

    1. Set destination to loadState.[[Destination]].

    2. Set fetchClient to loadState.[[FetchClient]].

  14. Fetch a single imported module script given url, fetchClient, destination, fetchOptions, settingsObject, fetchReferrer, moduleRequest, and onSingleFetchComplete as defined below. If loadState is not undefined and loadState.[[PerformFetch]] is not null, pass loadState.[[PerformFetch]] along as well.

    onSingleFetchComplete given moduleScript is the following algorithm:

    1. Let completion be null.

    2. If moduleScript is null, then set completion to Completion Record { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.

    3. Otherwise, if moduleScript's parse error is not null, then:

      1. Let parseError be moduleScript's parse error.

      2. Set completion to Completion Record { [[Type]]: throw, [[Value]]: parseError, [[Target]]: empty }.

      3. If loadState is not undefined and loadState.[[ParseError]] is null, set loadState.[[ParseError]] to parseError.

    4. Otherwise, set completion to Completion Record { [[Type]]: normal, [[Value]]: moduleScript's record, [[Target]]: empty }.

    5. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).

8.1.7 Event loops

8.1.7.1 Definitions

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. Each agent has an associated event loop, which is unique to that agent.

The event loop of a similar-origin window agent is known as a window event loop. The event loop of a dedicated worker agent, shared worker agent, or service worker agent is known as a worker event loop. And the event loop of a worklet agent is known as a worklet event loop.

Event loops do not necessarily correspond to implementation threads. For example, multiple window event loops could be cooperatively scheduled in a single thread.

However, for the various worker agents that are allocated with [[CanBlock]] set to true, the JavaScript specification does place requirements on them regarding forward progress, which effectively amount to requiring dedicated per-agent threads in those cases.


An event loop has one or more task queues. A task queue is a set of tasks.

Task queues are sets, not queues, because the event loop processing model grabs the first runnable task from the chosen queue, instead of dequeuing the first task.

The microtask queue is not a task queue.

Tasks encapsulate algorithms that are responsible for such work as:

Events

Dispatching an Event object at a particular EventTarget object is often done by a dedicated task.

Not all events are dispatched using the task queue; many are dispatched during other tasks.

Parsing

The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task.

Callbacks

Calling a callback is often done by a dedicated task.

Using a resource

When an algorithm fetches a resource, if the fetching occurs in a non-blocking fashion then the processing of the resource once some or all of the resource is available is performed by a task.

Reacting to DOM manipulation

Some elements have tasks that trigger in response to DOM manipulation, e.g. when that element is inserted into the document.

Formally, a task is a struct which has:

Steps
A series of steps specifying the work to be done by the task.
A source
One of the task sources, used to group and serialize related tasks.
A document
A Document associated with the task, or null for tasks that are not in a window event loop.
A script evaluation environment settings object set
A set of environment settings objects used for tracking script evaluation during the task.

A task is runnable if its document is either null or fully active.

Per its source field, each task is defined as coming from a specific task source. For each event loop, every task source must be associated with a specific task queue.

Essentially, task sources are used within standards to separate logically-different types of tasks, which a user agent might wish to distinguish between. Task queues are used by user agents to coalesce task sources within a given event loop.

For example, a user agent could have one task queue for mouse and key events (to which the user interaction task source is associated), and another to which all other task sources are associated. Then, using the freedom granted in the initial step of the event loop processing model, it could give keyboard and mouse events preference over other tasks three-quarters of the time, keeping the interface responsive but not starving other task queues. Note that in this setup, the processing model still enforces that the user agent would never process events from any one task source out of order.


Each event loop has a currently running task, which is either a task or null. Initially, this is null. It is used to handle reentrancy.

Each event loop has a microtask queue, which is a queue of microtasks, initially empty. A microtask is a colloquial way of referring to a task that was created via the queue a microtask algorithm.

Each event loop has a performing a microtask checkpoint boolean, which is initially false. It is used to prevent reentrant invocation of the perform a microtask checkpoint algorithm.

Each window event loop has a DOMHighResTimeStamp last render opportunity time, initially set to zero.

Each window event loop has a DOMHighResTimeStamp last idle period start time, initially set to zero.

To get the same-loop windows for a window event loop loop, return all Window objects whose relevant agent's event loop is loop.

8.1.7.2 Queuing tasks

To queue a task on a task source source, which performs a series of steps steps, optionally given an event loop event loop and a document document:

  1. If event loop was not given, set event loop to the implied event loop.

  2. If document was not given, set document to the implied document.

  3. Let task be a new task.

  4. Set task's steps to steps.

  5. Set task's source to source.

  6. Set task's document to the document.

  7. Set task's script evaluation environment settings object set to an empty set.

  8. Let queue be the task queue to which source is associated on event loop.

  9. Append task to queue.

Failing to pass an event loop and document to queue a task means relying on the ambiguous and poorly-specified implied event loop and implied document concepts. Specification authors should either always pass these values, or use the wrapper algorithms queue a global task or queue an element task instead. Using the wrapper algorithms is recommended.

To queue a global task on a task source source, with a global object global and a series of steps steps:

  1. Let event loop be global's relevant agent's event loop.

  2. Let document be global's associated Document, if global is a Window object; otherwise null.

  3. Queue a task given source, event loop, document, and steps.

To queue an element task on a task source source, with an element element and a series of steps steps:

  1. Let global be element's relevant global object.

  2. Queue a global task given source, global, and steps.

To queue a microtask which performs a series of steps steps, optionally given a document document:

  1. Assert: there is a surrounding agent. I.e., this algorithm is not called while in parallel.

  2. Let eventLoop be the surrounding agent's event loop.

  3. If document was not given, set document to the implied document.

  4. Let microtask be a new task.

  5. Set microtask's steps to steps.

  6. Set microtask's source to the microtask task source.

  7. Set microtask's document to document.

  8. Set microtask's script evaluation environment settings object set to an empty set.

  9. Enqueue microtask on eventLoop's microtask queue.

It is possible for a microtask to be moved to a regular task queue, if, during its initial execution, it spins the event loop. This is the only case in which the source, document, and script evaluation environment settings object set of the microtask are consulted; they are ignored by the perform a microtask checkpoint algorithm.

The implied event loop when queuing a task is the one that can deduced from the context of the calling algorithm. This is generally unambiguous, as most specification algorithms only ever involve a single agent (and thus a single event loop). The exception is algorithms involving or specifying cross-agent communication (e.g., between a window and a worker); for those cases, the implied event loop concept must not be relied upon and specifications must explicitly provide an event loop when queuing a task.

The implied document when queuing a task on an event loop event loop is determined as follows:

  1. If event loop is not a window event loop, then return null.

  2. If the task is being queued in the context of an element, then return the element's node document.

  3. If the task is being queued in the context of a browsing context, then return the browsing context's active document.

  4. If the task is being queued by or for a script, then return the script's settings object's global object's associated Document.

  5. Assert: this step is never reached, because one of the previous conditions is true. Really?

Both implied event loop and implied document are vaguely-defined and have a lot of action-at-a-distance. The hope is to remove these, especially implied document. See issue #4980.

8.1.7.3 Processing model

An event loop must continually run through the following steps for as long as it exists:

  1. Let oldestTask and taskStartTime be null.

  2. If the event loop has a task queue with at least one runnable task, then:

    1. Let taskQueue be one such task queue, chosen in an implementation-defined manner.

      Remember that the microtask queue is not a task queue, so it will not be chosen in this step. However, a task queue to which the microtask task source is associated might be chosen in this step. In that case, the task chosen in the next step was originally a microtask, but it got moved as part of spinning the event loop.

    2. Set taskStartTime to the unsafe shared current time.

    3. Set oldestTask to the first runnable task in taskQueue, and remove it from taskQueue.

    4. If oldestTask's document is not null, then record task start time given taskStartTime and oldestTask's document.

    5. Set the event loop's currently running task to oldestTask.

    6. Perform oldestTask's steps.

    7. Set the event loop's currently running task back to null.

    8. Perform a microtask checkpoint.

  3. Let taskEndTime be the unsafe shared current time. [HRT]

  4. If oldestTask is not null, then:

    1. Let top-level browsing contexts be an empty set.

    2. For each environment settings object settings of oldestTask's script evaluation environment settings object set:

      1. Let global be settings's global object.

      2. If global is not a Window object, then continue.

      3. If global's browsing context is null, then continue.

      4. Let tlbc be global's browsing context's top-level browsing context.

      5. If tlbc is not null, then append it to top-level browsing contexts.

    3. Report long tasks, passing in taskStartTime, taskEndTime, top-level browsing contexts, and oldestTask.

    4. If oldestTask's document is not null, then record task end time given taskEndTime and oldestTask's document.

  5. If this is a window event loop that has no runnable task in this event loop's task queues, then:

    1. Set this event loop's last idle period start time to the unsafe shared current time.

    2. Let computeDeadline be the following steps:

      1. Let deadline be this event loop's last idle period start time plus 50.

        The cap of 50ms in the future is to ensure responsiveness to new user input within the threshold of human perception.

      2. Let hasPendingRenders be false.

      3. For each windowInSameLoop of the same-loop windows for this event loop:

        1. If windowInSameLoop's map of animation frame callbacks is not empty, or if the user agent believes that the windowInSameLoop might have pending rendering updates, set hasPendingRenders to true.

        2. Let timerCallbackEstimates be the result of getting the values of windowInSameLoop's map of active timers.

        3. For each timeoutDeadline of timerCallbackEstimates, if timeoutDeadline is less than deadline, set deadline to timeoutDeadline.

      4. If hasPendingRenders is true, then:

        1. Let nextRenderDeadline be this event loop's last render opportunity time plus (1000 divided by the current refresh rate).

          The refresh rate can be hardware- or implementation-specific. For a refresh rate of 60Hz, the nextRenderDeadline would be about 16.67ms after the last render opportunity time.

        2. If nextRenderDeadline is less than deadline, then return nextRenderDeadline.

      5. Return deadline.

    3. For each win of the same-loop windows for this event loop, perform the start an idle period algorithm for win with the following step: return the result of calling computeDeadline, coarsened given win's relevant settings object's cross-origin isolated capability. [REQUESTIDLECALLBACK]

  6. If this is a worker event loop, then:

    1. If this event loop's agent's single realm's global object is a supported DedicatedWorkerGlobalScope and the user agent believes that it would benefit from having its rendering updated at this time, then:

      1. Let now be the current high resolution time given the DedicatedWorkerGlobalScope. [HRT]

      2. Run the animation frame callbacks for that DedicatedWorkerGlobalScope, passing in now as the timestamp.

      3. Update the rendering of that dedicated worker to reflect the current state.

      Similar to the notes for updating the rendering in a window event loop, a user agent can determine the rate of rendering in the dedicated worker.

    2. If there are no tasks in the event loop's task queues and the WorkerGlobalScope object's closing flag is true, then destroy the event loop, aborting these steps, resuming the run a worker steps described in the Web workers section below.

A window event loop eventLoop must also run the following in parallel, as long as it exists:

  1. Wait until at least one navigable whose active document's relevant agent's event loop is eventLoop might have a rendering opportunity.

  2. Set eventLoop's last render opportunity time to the unsafe shared current time.

  3. For each navigable that has a rendering opportunity, queue a global task on the rendering task source given navigable's active window to update the rendering:

    This might cause redundant calls to update the rendering. However, these calls would have no observable effect because there will be no rendering necessary, as per the Unnecessary rendering step. Implementations can introduce further optimizations such as only queuing this task when it is not already queued. However, note that the document associated with the task might become inactive before the task is processed.

    1. Let frameTimestamp be eventLoop's last render opportunity time.

    2. Let docs be all fully active Document objects whose relevant agent's event loop is eventLoop, sorted arbitrarily except that the following conditions must be met:

      In the steps below that iterate over docs, each Document must be processed in the order it is found in the list.

    3. Filter non-renderable documents: Remove from docs any Document object doc for which any of the following are true:

      We have to check for rendering opportunities here, in addition to checking that in the in parallel steps, as some documents that share the same event loop might not have a rendering opportunity at the same time.

    4. Unnecessary rendering: Remove from docs any Document object doc for which all of the following are true:

    5. Remove from docs all Document objects for which the user agent believes that it's preferable to skip updating the rendering for other reasons.

      The step labeled Filter non-renderable documents prevents the user agent from updating the rendering when it is unable to present new content to the user.

      The step labeled Unnecessary rendering prevents the user agent from updating the rendering when there's no new content to draw.

      This step enables the user agent to prevent the steps below from running for other reasons, for example, to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved). Concretely, a user agent might wish to coalesce timer callbacks together, with no intermediate rendering updates.

    6. For each doc of docs, reveal doc.

    7. For each doc of docs, flush autofocus candidates for doc if its node navigable is a top-level traversable.

    8. For each doc of docs, run the resize steps for doc. [CSSOMVIEW]

    9. For each doc of docs, run the scroll steps for doc. [CSSOMVIEW]

    10. For each doc of docs, evaluate media queries and report changes for doc. [CSSOMVIEW]

    11. For each doc of docs, update animations and send events for doc, passing in relative high resolution time given frameTimestamp and doc's relevant global object as the timestamp [WEBANIMATIONS]

    12. For each doc of docs, run the fullscreen steps for doc. [FULLSCREEN]

    13. For each doc of docs, if the user agent detects that the backing storage associated with a CanvasRenderingContext2D or an OffscreenCanvasRenderingContext2D, context, has been lost, then it must run the context lost steps for each such context:

      1. Let canvas be the value of context's canvas attribute, if context is a CanvasRenderingContext2D, or the associated OffscreenCanvas object for context otherwise.

      2. Set context's context lost to true.

      3. Reset the rendering context to its default state given context.

      4. Let shouldRestore be the result of firing an event named contextlost at canvas, with the cancelable attribute initialized to true.

      5. If shouldRestore is false, then abort these steps.

      6. Attempt to restore context by creating a backing storage using context's attributes and associating them with context. If this fails, then abort these steps.

      7. Set context's context lost to false.

      8. Fire an event named contextrestored at canvas.

    14. For each doc of docs, run the animation frame callbacks for doc, passing in the relative high resolution time given frameTimestamp and doc's relevant global object as the timestamp.

    15. Let unsafeStyleAndLayoutStartTime be the unsafe shared current time.

    16. For each doc of docs:

      1. Let resizeObserverDepth be 0.

      2. While true:

        1. Recalculate styles and update layout for doc.

        2. Let hadInitialVisibleContentVisibilityDetermination be false.

        3. For each element element with 'auto' used value of 'content-visibility':

          1. Let checkForInitialDetermination be true if element's proximity to the viewport is not determined and it is not relevant to the user. Otherwise, let checkForInitialDetermination be false.

          2. Determine proximity to the viewport for element.

          3. If checkForInitialDetermination is true and element is now relevant to the user, then set hadInitialVisibleContentVisibilityDetermination to true.

        4. If hadInitialVisibleContentVisibilityDetermination is true, then continue.

          The intent of this step is for the initial viewport proximity determination, which takes effect immediately, to be reflected in the style and layout calculation which is carried out in a previous step of this loop. Proximity determinations other than the initial one take effect at the next rendering opportunity. [CSSCONTAIN]

        5. Gather active resize observations at depth resizeObserverDepth for doc.

        6. If doc has active resize observations:

          1. Set resizeObserverDepth to the result of broadcasting active resize observations given doc.

          2. Continue.
        7. Otherwise, break.
      3. If doc has skipped resize observations, then deliver resize loop error given doc.

    17. For each doc of docs, if the focused area of doc is not a focusable area, then run the focusing steps for doc's viewport, and set doc's relevant global object's navigation API's focus changed during ongoing navigation to false.

      For example, this might happen because an element has the hidden attribute added, causing it to stop being rendered. It might also happen to an input element when the element gets disabled.

      This will usually fire blur events, and possibly change events.

      In addition to this asynchronous fixup, if the focused area of the document is removed, there is a synchronous fixup. That one will not fire blur or change events.

    18. For each doc of docs, perform pending transition operations for doc. [CSSVIEWTRANSITIONS]

    19. For each doc of docs, run the update intersection observations steps for doc, passing in the relative high resolution time given now and doc's relevant global object as the timestamp. [INTERSECTIONOBSERVER]

    20. For each doc of docs, record rendering time for doc given unsafeStyleAndLayoutStartTime.

    21. For each doc of docs, mark paint timing for doc.

    22. For each doc of docs, update the rendering or user interface of doc and its node navigable to reflect the current state.

    23. For each doc of docs, process top layer removals given doc.

A navigable has a rendering opportunity if the user agent is currently able to present the contents of the navigable to the user, accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.

A navigable's rendering opportunities are determined based on hardware constraints such as display refresh rates and other factors such as page performance or whether its active document's visibility state is "visible". Rendering opportunities typically occur at regular intervals.

This specification does not mandate any particular model for selecting rendering opportunities. But for example, if the browser is attempting to achieve a 60Hz refresh rate, then rendering opportunities occur at a maximum of every 60th of a second (about 16.7ms). If the browser finds that a navigable is not able to sustain this rate, it might drop to a more sustainable 30 rendering opportunities per second for that navigable, rather than occasionally dropping frames. Similarly, if a navigable is not visible, the user agent might decide to drop that page to a much slower 4 rendering opportunities per second, or even less.


When a user agent is to perform a microtask checkpoint:

  1. If the event loop's performing a microtask checkpoint is true, then return.

  2. Set the event loop's performing a microtask checkpoint to true.

  3. While the event loop's microtask queue is not empty:

    1. Let oldestMicrotask be the result of dequeuing from the event loop's microtask queue.

    2. Set the event loop's currently running task to oldestMicrotask.

    3. Run oldestMicrotask.

      This might involve invoking scripted callbacks, which eventually calls the clean up after running script steps, which call this perform a microtask checkpoint algorithm again, which is why we use the performing a microtask checkpoint flag to avoid reentrancy.

    4. Set the event loop's currently running task back to null.

  4. For each environment settings object settingsObject whose responsible event loop is this event loop, notify about rejected promises given settingsObject's global object.

  5. Cleanup Indexed Database transactions.

  6. Perform ClearKeptObjects().

    When WeakRef.prototype.deref() returns an object, that object is kept alive until the next invocation of ClearKeptObjects(), after which it is again subject to garbage collection.

  7. Set the event loop's performing a microtask checkpoint to false.

  8. Record timing info for microtask checkpoint.


When an algorithm running in parallel is to await a stable state, the user agent must queue a microtask that runs the following steps, and must then stop executing (execution of the algorithm resumes when the microtask is run, as described in the following steps):

  1. Run the algorithm's synchronous section.

  2. Resumes execution of the algorithm in parallel, if appropriate, as described in the algorithm's steps.

Steps in synchronous sections are marked with ⌛.


Algorithm steps that say to spin the event loop until a condition goal is met are equivalent to substituting in the following algorithm steps:

  1. Let task be the event loop's currently running task.

    task could be a microtask.

  2. Let task source be task's source.

  3. Let old stack be a copy of the JavaScript execution context stack.

  4. Empty the JavaScript execution context stack.

  5. Perform a microtask checkpoint.

    If task is a microtask this step will be a no-op due to performing a microtask checkpoint being true.

  6. In parallel:

    1. Wait until the condition goal is met.

    2. Queue a task on task source to:

      1. Replace the JavaScript execution context stack with old stack.

      2. Perform any steps that appear after this spin the event loop instance in the original algorithm.

        This resumes task.

  7. Stop task, allowing whatever algorithm that invoked it to resume.

    This causes the event loop's main set of steps or the perform a microtask checkpoint algorithm to continue.

Unlike other algorithms in this and other specifications, which behave similar to programming-language function calls, spin the event loop is more like a macro, which saves typing and indentation at the usage site by expanding into a series of steps and operations.

An algorithm whose steps are:

  1. Do something.

  2. Spin the event loop until awesomeness happens.

  3. Do something else.

is a shorthand which, after "macro expansion", becomes

  1. Do something.

  2. Let old stack be a copy of the JavaScript execution context stack.

  3. Empty the JavaScript execution context stack.

  4. Perform a microtask checkpoint.

  5. In parallel:

    1. Wait until awesomeness happens.

    2. Queue a task on the task source in which "do something" was done to:

      1. Replace the JavaScript execution context stack with old stack.

      2. Do something else.

Here is a more full example of the substitution, where the event loop is spun from inside a task that is queued from work in parallel. The version using spin the event loop:

  1. In parallel:

    1. Do parallel thing 1.

    2. Queue a task on the DOM manipulation task source to:

      1. Do task thing 1.

      2. Spin the event loop until awesomeness happens.

      3. Do task thing 2.

    3. Do parallel thing 2.

The fully expanded version:

  1. In parallel:

    1. Do parallel thing 1.

    2. Let old stack be null.

    3. Queue a task on the DOM manipulation task source to:

      1. Do task thing 1.

      2. Set old stack to a copy of the JavaScript execution context stack.

      3. Empty the JavaScript execution context stack.

      4. Perform a microtask checkpoint.

    4. Wait until awesomeness happens.

    5. Queue a task on the DOM manipulation task source to:

      1. Replace the JavaScript execution context stack with old stack.

      2. Do task thing 2.

    6. Do parallel thing 2.


Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps:

  1. Let global be the current global object.

  2. Let timeBeforePause be the current high resolution time given global.

  3. If necessary, update the rendering or user interface of any Document or navigable to reflect the current state.

  4. Wait until the condition goal is met. While a user agent has a paused task, the corresponding event loop must not run further tasks, and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the event loop will not be doing anything.

  5. Record pause duration given the duration from timeBeforePause to the current high resolution time given global.

Pausing is highly detrimental to the user experience, especially in scenarios where a single event loop is shared among multiple documents. User agents are encouraged to experiment with alternatives to pausing, such as spinning the event loop or even simply proceeding without any kind of suspended execution at all, insofar as it is possible to do so while preserving compatibility with existing content. This specification will happily change if a less-drastic alternative is discovered to be web-compatible.

In the interim, implementers should be aware that the variety of alternatives that user agents might experiment with can change subtle aspects of event loop behavior, including task and microtask timing. Implementations should continue experimenting even if doing so causes them to violate the exact semantics implied by the pause operation.

8.1.7.4 Generic task sources

The following task sources are used by a number of mostly unrelated features in this and other specifications.

The DOM manipulation task source

This task source is used for features that react to DOM manipulations, such as things that happen in a non-blocking fashion when an element is inserted into the document.

The user interaction task source

This task source is used for features that react to user interaction, for example keyboard or mouse input.

Events sent in response to user input (e.g. click events) must be fired using tasks queued with the user interaction task source. [UIEVENTS]

The networking task source

This task source is used for features that trigger in response to network activity.

The navigation and traversal task source

This task source is used to queue tasks involved in navigation and history traversal.

The rendering task source

This task source is used solely to update the rendering.

8.1.7.5 Dealing with the event loop from other specifications

Writing specifications that correctly interact with the event loop can be tricky. This is compounded by how this specification uses concurrency-model-independent terminology, so we say things like "event loop" and "in parallel" instead of using more familiar model-specific terms like "main thread" or "on a background thread".

By default, specification text generally runs on the event loop. This falls out from the formal event loop processing model, in that you can eventually trace most algorithms back to a task queued there.

The algorithm steps for any JavaScript method will be invoked by author code calling that method. And author code can only be run via queued tasks, usually originating somewhere in the script processing model.

From this starting point, the overriding guideline is that any work a specification needs to perform that would otherwise block the event loop must instead be performed in parallel with it. This includes (but is not limited to):

The next complication is that, in algorithm sections that are in parallel, you must not create or manipulate objects associated to a specific realm, global, or environment settings object. (Stated in more familiar terms, you must not directly access main-thread artifacts from a background thread.) Doing so would create data races observable to JavaScript code, since after all, your algorithm steps are running in parallel to the JavaScript code.

You can, however, manipulate specification-level data structures and values from Infra, as those are realm-agnostic. They are never directly exposed to JavaScript without a specific conversion taking place (often via Web IDL). [INFRA] [WEBIDL]

To affect the world of observable JavaScript objects, then, you must queue a global task to perform any such manipulations. This ensures your steps are properly interleaved with respect to other things happening on the event loop. Furthermore, you must choose a task source when queuing a global task; this governs the relative order of your steps versus others. If you are unsure which task source to use, pick one of the generic task sources that sounds most applicable. Finally, you must indicate which global object your queued task is associated with; this ensures that if that global object is inactive, the task does not run.

The base primitive, on which queue a global task builds, is the queue a task algorithm. In general, queue a global task is better because it automatically picks the right event loop and, where appropriate, document. Older specifications often use queue a task combined with the implied event loop and implied document concepts, but this is discouraged.

Putting this all together, we can provide a template for a typical algorithm that needs to do work asynchronously:

  1. Do any synchronous setup work, while still on the event loop. This may include converting realm-specific JavaScript values into realm-agnostic specification-level values.

  2. Perform a set of potentially-expensive steps in parallel, operating entirely on realm-agnostic values, and producing a realm-agnostic result.

  3. Queue a global task, on a specified task source and given an appropriate global object, to convert the realm-agnostic result back into observable effects on the observable world of JavaScript objects on the event loop.

The following is an algorithm that "encrypts" a passed-in list of scalar value strings input, after parsing them as URLs:

  1. Let urls be an empty list.

  2. For each string of input:

    1. Let parsed be the result of encoding-parsing a URL given string, relative to the current settings object.

    2. If parsed is failure, then return a promise rejected with a "SyntaxError" DOMException.

    3. Let serialized be the result of applying the URL serializer to parsed.

    4. Append serialized to urls.

  3. Let realm be the current realm.

  4. Let p be a new promise.

  5. Run the following steps in parallel:

    1. Let encryptedURLs be an empty list.

    2. For each url of urls:

      1. Wait 100 milliseconds, so that people think we're doing heavy-duty encryption.

      2. Let encrypted be a new string derived from url, whose nth code unit is equal to url's nth code unit plus 13.

      3. Append encrypted to encryptedURLs.

    3. Queue a global task on the networking task source, given realm's global object, to perform the following steps:

      1. Let array be the result of converting encryptedURLs to a JavaScript array, in realm.

      2. Resolve p with array.

  6. Return p.

Here are several things to notice about this algorithm:

(On these last two points, see also whatwg/webidl issue #135 and whatwg/webidl issue #371, where we are still mulling over the subtleties of the above promise-resolution pattern.)

Another thing to note is that, in the event this algorithm was called from a Web IDL-specified operation taking a sequence<USVString>, there was an automatic conversion from realm-specific JavaScript objects provided by the author as input, into the realm-agnostic sequence<USVString> Web IDL type, which we then treat as a list of scalar value strings. So depending on how your specification is structured, there may be other implicit steps happening on the main event loop that play a part in this whole process of getting you ready to go in parallel.

8.1.8 Events

8.1.8.1 Event handlers

Events/Event_handlers

Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified. [DOM]

An event handler is a struct with two items:

Event handlers are exposed in two ways.

The first way, common to all event handlers, is as an event handler IDL attribute.

The second way is as an event handler content attribute. Event handlers on HTML elements and some of the event handlers on Window objects are exposed in this way.

For both of these two ways, the event handler is exposed through a name, which is a string that always starts with "on" and is followed by the name of the event for which the handler is intended.


Most of the time, the object that exposes an event handler is the same as the object on which the corresponding event listener is added. However, the body and frameset elements expose several event handlers that act upon the element's Window object, if one exists. In either case, we call the object an event handler acts upon the target of that event handler.

To determine the target of an event handler, given an EventTarget object eventTarget on which the event handler is exposed, and an event handler name name, the following steps are taken:

  1. If eventTarget is not a body element or a frameset element, then return eventTarget.

  2. If name is not the name of an attribute member of the WindowEventHandlers interface mixin and the Window-reflecting body element event handler set does not contain name, then return eventTarget.

  3. If eventTarget's node document is not an active document, then return null.

    This could happen if this object is a body element without a corresponding Window object, for example.

    This check does not necessarily prevent body and frameset elements that are not the body element of their node document from reaching the next step. In particular, a body element created in an active document (perhaps with document.createElement()) but not connected will also have its corresponding Window object as the target of several event handlers exposed through it.

  4. Return eventTarget's node document's relevant global object.


Each EventTarget object that has one or more event handlers specified has an associated event handler map, which is a map of strings representing names of event handlers to event handlers.

When an EventTarget object that has one or more event handlers specified is created, its event handler map must be initialized such that it contains an entry for each event handler that has that object as target, with items in those event handlers set to their initial values.

The order of the entries of event handler map could be arbitrary. It is not observable through any algorithms that operate on the map.

Entries are not created in the event handler map of an object for event handlers that are merely exposed on that object, but have some other object as their targets.


An event handler IDL attribute is an IDL attribute for a specific event handler. The name of the IDL attribute is the same as the name of the event handler.

The getter of an event handler IDL attribute with name name, when called, must run these steps:

  1. Let eventTarget be the result of determining the target of an event handler given this object and name.

  2. If eventTarget is null, then return null.

  3. Return the result of getting the current value of the event handler given eventTarget and name.

The setter of an event handler IDL attribute with name name, when called, must run these steps:

  1. Let eventTarget be the result of determining the target of an event handler given this object and name.

  2. If eventTarget is null, then return.

  3. If the given value is null, then deactivate an event handler given eventTarget and name.

  4. Otherwise:

    1. Let handlerMap be eventTarget's event handler map.

    2. Let eventHandler be handlerMap[name].

    3. Set eventHandler's value to the given value.

    4. Activate an event handler given eventTarget and name.

Certain event handler IDL attributes have additional requirements, in particular the onmessage attribute of MessagePort objects.


An event handler content attribute is a content attribute for a specific event handler. The name of the content attribute is the same as the name of the event handler.

Event handler content attributes, when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion.

The following attribute change steps are used to synchronize between event handler content attributes and event handlers: [DOM]

  1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.

  2. Let eventTarget be the result of determining the target of an event handler given element and localName.

  3. If eventTarget is null, then return.

  4. If value is null, then deactivate an event handler given eventTarget and localName.

  5. Otherwise:

    1. If the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon element, "script attribute", and value, then return. [CSP]

    2. Let handlerMap be eventTarget's event handler map.

    3. Let eventHandler be handlerMap[localName].

    4. Let location be the script location that triggered the execution of these steps.

    5. Set eventHandler's value to the internal raw uncompiled handler value/location.

    6. Activate an event handler given eventTarget and localName.

Per the DOM Standard, these steps are run even if oldValue and value are identical (setting an attribute to its current value), but not if oldValue and value are both null (removing an attribute that doesn't currently exist). [DOM]


To deactivate an event handler given an EventTarget object eventTarget and a string name that is the name of an event handler, run these steps:

  1. Let handlerMap be eventTarget's event handler map.

  2. Let eventHandler be handlerMap[name].

  3. Set eventHandler's value to null.

  4. Let listener be eventHandler's listener.

  5. If listener is not null, then remove an event listener with eventTarget and listener.

  6. Set eventHandler's listener to null.

To erase all event listeners and handlers given an EventTarget object eventTarget, run these steps:

  1. If eventTarget has an associated event handler map, then for each nameeventHandler of eventTarget's associated event handler map, deactivate an event handler given eventTarget and name.

  2. Remove all event listeners given eventTarget.

This algorithm is used to define document.open().

To activate an event handler given an EventTarget object eventTarget and a string name that is the name of an event handler, run these steps:

  1. Let handlerMap be eventTarget's event handler map.

  2. Let eventHandler be handlerMap[name].

  3. If eventHandler's listener is not null, then return.

  4. Let callback be the result of creating a Web IDL EventListener instance representing a reference to a function of one argument that executes the steps of the event handler processing algorithm, given eventTarget, name, and its argument.

    The EventListener's callback context can be arbitrary; it does not impact the steps of the event handler processing algorithm. [DOM]

    The callback is emphatically not the event handler itself. Every event handler ends up registering the same callback, the algorithm defined below, which takes care of invoking the right code, and processing the code's return value.

  5. Let listener be a new event listener whose type is the event handler event type corresponding to eventHandler and callback is callback.

    To be clear, an event listener is different from an EventListener.

  6. Add an event listener with eventTarget and listener.

  7. Set eventHandler's listener to listener.

The event listener registration happens only if the event handler's value is being set to non-null, and the event handler is not already activated. Since listeners are called in the order they were registered, assuming no deactivation occurred, the order of event listeners for a particular event type will always be:

  1. the event listeners registered with addEventListener() before the first time the event handler's value was set to non-null

  2. then the callback to which it is currently set, if any

  3. and finally the event listeners registered with addEventListener() after the first time the event handler's value was set to non-null.

This example demonstrates the order in which event listeners are invoked. If the button in this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively.

<button id="test">Start Demo</button>
<script>
 var button = document.getElementById('test');
 button.addEventListener('click', function () { alert('ONE') }, false);
 button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here
 button.addEventListener('click', function () { alert('THREE') }, false);
 button.onclick = function () { alert('TWO'); };
 button.addEventListener('click', function () { alert('FOUR') }, false);
</script>

However, in the following example, the event handler is deactivated after its initial activation (and its event listener is removed), before being reactivated at a later time. The page will show five alerts with "ONE", "TWO", "THREE", "FOUR", and "FIVE" respectively, in order.

<button id="test">Start Demo</button>
<script>
 var button = document.getElementById('test');
 button.addEventListener('click', function () { alert('ONE') }, false);
 button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler is activated here
 button.addEventListener('click', function () { alert('TWO') }, false);
 button.onclick = null;                                 // but deactivated here
 button.addEventListener('click', function () { alert('THREE') }, false);
 button.onclick = function () { alert('FOUR'); };       // and re-activated here
 button.addEventListener('click', function () { alert('FIVE') }, false);
</script>

The interfaces implemented by the event object do not influence whether an event handler is triggered or not.

The event handler processing algorithm for an EventTarget object eventTarget, a string name representing the name of an event handler, and an Event object event is as follows:

  1. Let callback be the result of getting the current value of the event handler given eventTarget and name.

  2. If callback is null, then return.

  3. Let special error event handling be true if event is an ErrorEvent object, event's type is "error", and event's currentTarget implements the WindowOrWorkerGlobalScope mixin. Otherwise, let special error event handling be false.

  4. Process the Event object event as follows:

    If special error event handling is true

    Let return value be the result of invoking callback with « event's message, event's filename, event's lineno, event's colno, event's error », "rethrow", and with callback this value set to event's currentTarget.

    Otherwise

    Let return value be the result of invoking callback with « event », "rethrow", and with callback this value set to event's currentTarget.

    If an exception gets thrown by the callback, it will be rethrown, ending these steps. The exception will propagate to the DOM event dispatch logic, which will then report it.

  5. Process return value as follows:

    If event is a BeforeUnloadEvent object and event's type is "beforeunload"

    In this case, the event handler IDL attribute's type will be OnBeforeUnloadEventHandler, so return value will have been coerced into either null or a DOMString.

    If return value is not null, then:

    1. Set event's canceled flag.

    2. If event's returnValue attribute's value is the empty string, then set event's returnValue attribute's value to return value.

    If special error event handling is true

    If return value is true, then set event's canceled flag.

    Otherwise

    If return value is false, then set event's canceled flag.

    If we've gotten to this "Otherwise" clause because event's type is "beforeunload" but event is not a BeforeUnloadEvent object, then return value will never be false, since in such cases return value will have been coerced into either null or a DOMString.


The EventHandler callback function type represents a callback used for event handlers. It is represented in Web IDL as follows:

[LegacyTreatNonObjectAsNull]
callback EventHandlerNonNull = any (Event event);
typedef EventHandlerNonNull? EventHandler;

In JavaScript, any Function object implements this interface.

For example, the following document fragment:

<body onload="alert(this)" onclick="alert(this)">

...leads to an alert saying "[object Window]" when the document is loaded, and an alert saying "[object HTMLBodyElement]" whenever the user clicks something in the page.

The return value of the function affects whether the event is canceled or not: as described above, if the return value is false, the event is canceled.

There are two exceptions in the platform, for historical reasons:

For historical reasons, the onerror handler has different arguments:

[LegacyTreatNonObjectAsNull]
callback OnErrorEventHandlerNonNull = any ((Event or DOMString) event, optional DOMString source, optional unsigned long lineno, optional unsigned long colno, optional any error);
typedef OnErrorEventHandlerNonNull? OnErrorEventHandler;
window.onerror = (message, source, lineno, colno, error) => {};

Similarly, the onbeforeunload handler has a different return value:

[LegacyTreatNonObjectAsNull]
callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event);
typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;

An internal raw uncompiled handler is a tuple with the following information:

When the user agent is to get the current value of the event handler given an EventTarget object eventTarget and a string name that is the name of an event handler, it must run these steps:

  1. Let handlerMap be eventTarget's event handler map.

  2. Let eventHandler be handlerMap[name].

  3. If eventHandler's value is an internal raw uncompiled handler, then:

    1. If eventTarget is an element, then let element be eventTarget, and document be element's node document. Otherwise, eventTarget is a Window object, let element be null, and document be eventTarget's associated Document.

    2. If scripting is disabled for document, then return null.

    3. Let body be the uncompiled script body in eventHandler's value.

    4. Let location be the location where the script body originated, as given by eventHandler's value.

    5. If element is not null and element has a form owner, let form owner be that form owner. Otherwise, let form owner be null.

    6. Let settings object be the relevant settings object of document.

    7. If body is not parsable as FunctionBody or if parsing detects an early error, then follow these substeps:

      1. Set eventHandler's value to null.

        This does not deactivate the event handler, which additionally removes the event handler's listener (if present).

      2. Let syntaxError be a new SyntaxError exception associated with settings object's realm which describes the error while parsing. It should be based on location, where the script body originated.

      3. Report an exception with syntaxError for settings object's global object.

      4. Return null.

    8. Push settings object's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

      This is necessary so the subsequent invocation of OrdinaryFunctionCreate takes place in the correct realm.

    9. Let function be the result of calling OrdinaryFunctionCreate, with arguments:

      functionPrototype
      %Function.prototype%
      sourceText
      If name is onerror and eventTarget is a Window object
      The string formed by concatenating "function ", name, "(event, source, lineno, colno, error) {", U+000A LF, body, U+000A LF, and "}".
      Otherwise
      The string formed by concatenating "function ", name, "(event) {", U+000A LF, body, U+000A LF, and "}".
      ParameterList
      If name is onerror and eventTarget is a Window object
      Let the function have five arguments, named event, source, lineno, colno, and error.
      Otherwise
      Let the function have a single argument called event.
      body
      The result of parsing body above.
      thisMode
      non-lexical-this
      scope
      1. Let realm be settings object's realm.

      2. Let scope be realm.[[GlobalEnv]].

      3. If eventHandler is an element's event handler, then set scope to NewObjectEnvironment(document, true, scope).

        (Otherwise, eventHandler is a Window object's event handler.)

      4. If form owner is not null, then set scope to NewObjectEnvironment(form owner, true, scope).

      5. If element is not null, then set scope to NewObjectEnvironment(element, true, scope).

      6. Return scope.

    10. Remove settings object's realm execution context from the JavaScript execution context stack.

    11. Set function.[[ScriptOrModule]] to null.

      This is done because the default behavior, of associating the created function with the nearest script on the stack, can lead to path-dependent results. For example, an event handler which is first invoked by user interaction would end up with null [[ScriptOrModule]] (since then this algorithm would be first invoked when the active script is null), whereas one that is first invoked by dispatching an event from script would have its [[ScriptOrModule]] set to that script.

      Instead, we just always set [[ScriptOrModule]] to null. This is more intuitive anyway; the idea that the first script which dispatches an event is somehow responsible for the event handler code is dubious.

      In practice, this only affects the resolution of relative URLs via import(), which consult the base URL of the associated script. Nulling out [[ScriptOrModule]] means that HostLoadImportedModule will fall back to the current settings object's API base URL.

    12. Set eventHandler's value to the result of creating a Web IDL EventHandler callback function object whose object reference is function and whose callback context is settings object.

  4. Return eventHandler's value.

8.1.8.2 Event handlers on elements, Document objects, and Window objects

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and that must be supported by all Document and Window objects, as event handler IDL attributes:

Event handler Event handler event type
onabort

HTMLMediaElement/abort_event

Support in all current engines.

Firefox9+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
abort
onauxclick

Element/auxclick_event

Firefox53+SafariNoChrome55+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android53+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
auxclick
onbeforeinput beforeinput
onbeforematch beforematch
onbeforetoggle beforetoggle
oncancel

HTMLDialogElement/cancel_event

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome AndroidNoWebView Android?Samsung Internet?Opera Android?
cancel
oncanplay

HTMLMediaElement/canplay_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
canplay
oncanplaythrough

HTMLMediaElement/canplaythrough_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
canplaythrough
onchange

HTMLElement/change_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
change
onclick

Element/click_event

Support in all current engines.

Firefox6+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
click
onclose close
oncontextlost contextlost
oncontextmenu contextmenu
oncontextrestored contextrestored
oncopy

Element/copy_event

Support in all current engines.

Firefox22+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
copy
oncuechange

HTMLTrackElement/cuechange_event

Support in all current engines.

Firefox68+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android4.4.3+Samsung Internet?Opera Android19+
cuechange
oncut

Element/cut_event

Support in all current engines.

Firefox22+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
cut
ondblclick

Element/dblclick_event

Support in all current engines.

Firefox6+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS1+Chrome AndroidNoWebView Android?Samsung Internet?Opera Android12.1+
dblclick
ondrag drag
ondragend dragend
ondragenter dragenter
ondragleave dragleave
ondragover dragover
ondragstart dragstart
ondrop drop
ondurationchange

HTMLMediaElement/durationchange_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
durationchange
onemptied

HTMLMediaElement/emptied_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
emptied
onended

HTMLMediaElement/ended_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
ended
onformdata formdata
oninput

HTMLElement/input_event

Support in all current engines.

Firefox6+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)NoInternet Explorer🔰 9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
input
oninvalid invalid
onkeydown

Element/keydown_event

Support in all current engines.

Firefox6+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
keydown
onkeypress keypress
onkeyup

Element/keyup_event

Support in all current engines.

Firefox6+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
keyup
onloadeddata

HTMLMediaElement/loadeddata_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
loadeddata
onloadedmetadata

HTMLMediaElement/loadedmetadata_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
loadedmetadata
onloadstart

HTMLMediaElement/loadstart_event

Support in all current engines.

Firefox6+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
loadstart
onmousedown

Element/mousedown_event

Support in all current engines.

Firefox6+Safari4+Chrome2+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
mousedown
onmouseenter

Element/mouseenter_event

Support in all current engines.

Firefox10+Safari7+Chrome30+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
mouseenter
onmouseleave

Element/mouseleave_event

Support in all current engines.

Firefox10+Safari7+Chrome30+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
mouseleave
onmousemove

Element/mousemove_event

Support in all current engines.

Firefox6+Safari4+Chrome2+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
mousemove
onmouseout

Element/mouseout_event

Support in all current engines.

Firefox6+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
mouseout
onmouseover

Element/mouseover_event

Support in all current engines.

Firefox6+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
mouseover
onmouseup

Element/mouseup_event

Support in all current engines.

Firefox6+Safari4+Chrome2+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
mouseup
onpaste

Element/paste_event

Support in all current engines.

Firefox22+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
paste
onpause

HTMLMediaElement/pause_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
pause
onplay

HTMLMediaElement/play_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
play
onplaying

HTMLMediaElement/playing_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
playing
onprogress

HTMLMediaElement/progress_event

Support in all current engines.

Firefox6+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
progress
onratechange

HTMLMediaElement/ratechange_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
ratechange
onreset reset
onscrollend

Document/scrollend_event

Firefox109+SafariNoChrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Element/scrollend_event

Firefox109+SafariNoChrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
scrollend
onsecuritypolicyviolation

Element/securitypolicyviolation_event

Support in all current engines.

Firefox63+Safari10+Chrome41+
Opera?Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
securitypolicyviolation
onseeked

HTMLMediaElement/seeked_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
seeked
onseeking

HTMLMediaElement/seeking_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
seeking
onselect

HTMLInputElement/select_event

Support in all current engines.

Firefox6+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTextAreaElement/select_event

Support in all current engines.

Firefox6+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
select
onslotchange

HTMLSlotElement/slotchange_event

Support in all current engines.

Firefox63+Safari10.1+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
slotchange
onstalled

HTMLMediaElement/stalled_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
stalled
onsubmit

HTMLFormElement/submit_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
submit
onsuspend

HTMLMediaElement/suspend_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
suspend
ontimeupdate

HTMLMediaElement/timeupdate_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
timeupdate
ontoggle toggle
onvolumechange

HTMLMediaElement/volumechange_event

Support in all current engines.

Firefox6+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
volumechange
onwaiting

HTMLMediaElement/waiting_event

Support in all current engines.

Firefox6+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
waiting
onwebkitanimationend webkitAnimationEnd
onwebkitanimationiteration webkitAnimationIteration
onwebkitanimationstart webkitAnimationStart
onwebkittransitionend webkitTransitionEnd
onwheel

Element/wheel_event

Support in all current engines.

Firefox17+Safari7+Chrome31+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOSNoChrome Android?WebView Android?Samsung Internet?Opera Android?
wheel

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes; that must be supported by all Document objects, as event handler IDL attributes; and that must be supported by all Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document:

Event handler Event handler event type
onblur

Element/blur_event

Support in all current engines.

Firefox24+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Window/blur_event

Support in all current engines.

Firefox6+Safari5.1+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
blur
onerror

Window/error_event

Support in all current engines.

Firefox6+Safari5.1+Chrome10+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
error
onfocus

Element/focus_event

Support in all current engines.

Firefox24+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Window/focus_event

Support in all current engines.

Firefox6+Safari5.1+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
focus
onload load
onresize resize
onscroll

Document/scroll_event

Support in all current engines.

Firefox6+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Element/scroll_event

Support in all current engines.

Firefox6+Safari1.3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
scroll

We call the set of the names of the event handlers listed in the first column of this table the Window-reflecting body element event handler set.


The following are the event handlers (and their corresponding event handler event types) that must be supported by Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document:

Event handler Event handler event type
onafterprint

Window/afterprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
afterprint
onbeforeprint

Window/beforeprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
beforeprint
onbeforeunload

Window/beforeunload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
beforeunload
onhashchange

Window/hashchange_event

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
hashchange
onlanguagechange

Window/languagechange_event

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet4.0+Opera Android?
languagechange
onmessage

Window/message_event

Support in all current engines.

Firefox9+Safari4+Chrome60+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS4+Chrome Android?WebView Android?Samsung Internet?Opera Android47+
message
onmessageerror

HTMLMediaElement/error_event

Support in all current engines.

Firefox6+Safari3.1+Chrome3+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Window/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+
messageerror
onoffline

Window/offline_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
offline
ononline

Window/online_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
online
onpageswap pageswap
onpagehide pagehide
onpagereveal pagereveal
onpageshow pageshow
onpopstate

Window/popstate_event

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+
popstate
onrejectionhandled

Window/rejectionhandled_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?
rejectionhandled
onstorage

Window/storage_event

Support in all current engines.

Firefox45+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)15+Internet Explorer9+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
storage
onunhandledrejection

Window/unhandledrejection_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?
unhandledrejection
onunload

Window/unload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
unload

This list of event handlers is reified as event handler IDL attributes through the WindowEventHandlers interface mixin.


The following are the event handlers (and their corresponding event handler event types) that must be supported on Document objects as event handler IDL attributes:

Event handler Event handler event type
onreadystatechange readystatechange
onvisibilitychange

Document/visibilitychange_event

Support in all current engines.

Firefox56+Safari14.1+Chrome62+
Opera49+Edge79+
Edge (Legacy)18Internet Explorer🔰 10+
Firefox Android?Safari iOS?Chrome Android?WebView Android62+Samsung Internet?Opera Android46+
visibilitychange
8.1.8.2.1 IDL definitions
interface mixin GlobalEventHandlers {
  attribute EventHandler onabort;
  attribute EventHandler onauxclick;
  attribute EventHandler onbeforeinput;
  attribute EventHandler onbeforematch;
  attribute EventHandler onbeforetoggle;
  attribute EventHandler onblur;
  attribute EventHandler oncancel;
  attribute EventHandler oncanplay;
  attribute EventHandler oncanplaythrough;
  attribute EventHandler onchange;
  attribute EventHandler onclick;
  attribute EventHandler onclose;
  attribute EventHandler oncontextlost;
  attribute EventHandler oncontextmenu;
  attribute EventHandler oncontextrestored;
  attribute EventHandler oncopy;
  attribute EventHandler oncuechange;
  attribute EventHandler oncut;
  attribute EventHandler ondblclick;
  attribute EventHandler ondrag;
  attribute EventHandler ondragend;
  attribute EventHandler ondragenter;
  attribute EventHandler ondragleave;
  attribute EventHandler ondragover;
  attribute EventHandler ondragstart;
  attribute EventHandler ondrop;
  attribute EventHandler ondurationchange;
  attribute EventHandler onemptied;
  attribute EventHandler onended;
  attribute OnErrorEventHandler onerror;
  attribute EventHandler onfocus;
  attribute EventHandler onformdata;
  attribute EventHandler oninput;
  attribute EventHandler oninvalid;
  attribute EventHandler onkeydown;
  attribute EventHandler onkeypress;
  attribute EventHandler onkeyup;
  attribute EventHandler onload;
  attribute EventHandler onloadeddata;
  attribute EventHandler onloadedmetadata;
  attribute EventHandler onloadstart;
  attribute EventHandler onmousedown;
  [LegacyLenientThis] attribute EventHandler onmouseenter;
  [LegacyLenientThis] attribute EventHandler onmouseleave;
  attribute EventHandler onmousemove;
  attribute EventHandler onmouseout;
  attribute EventHandler onmouseover;
  attribute EventHandler onmouseup;
  attribute EventHandler onpaste;
  attribute EventHandler onpause;
  attribute EventHandler onplay;
  attribute EventHandler onplaying;
  attribute EventHandler onprogress;
  attribute EventHandler onratechange;
  attribute EventHandler onreset;
  attribute EventHandler onresize;
  attribute EventHandler onscroll;
  attribute EventHandler onscrollend;
  attribute EventHandler onsecuritypolicyviolation;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onslotchange;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler ontimeupdate;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
  attribute EventHandler onwebkitanimationend;
  attribute EventHandler onwebkitanimationiteration;
  attribute EventHandler onwebkitanimationstart;
  attribute EventHandler onwebkittransitionend;
  attribute EventHandler onwheel;
};

interface mixin WindowEventHandlers {
  attribute EventHandler onafterprint;
  attribute EventHandler onbeforeprint;
  attribute OnBeforeUnloadEventHandler onbeforeunload;
  attribute EventHandler onhashchange;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onpagehide;
  attribute EventHandler onpagereveal;
  attribute EventHandler onpageshow;
  attribute EventHandler onpageswap;
  attribute EventHandler onpopstate;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onstorage;
  attribute EventHandler onunhandledrejection;
  attribute EventHandler onunload;
};
8.1.8.3 Event firing

Certain operations and methods are defined as firing events on elements. For example, the click() method on the HTMLElement interface is defined as firing a click event on the element. [UIEVENTS]

Firing a synthetic pointer event named e at target, with an optional not trusted flag, means running these steps:

  1. Let event be the result of creating an event using PointerEvent.

  2. Initialize event's type attribute to e.

  3. Initialize event's bubbles and cancelable attributes to true.

  4. Set event's composed flag.

  5. If the not trusted flag is set, initialize event's isTrusted attribute to false.

  6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state of the key input device, if any (false for any keys that are not available).

  7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.

  8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.

  9. Return the result of dispatching event at target.

Firing a click event at target means firing a synthetic pointer event named click at target.

8.2 The WindowOrWorkerGlobalScope mixin

The WindowOrWorkerGlobalScope mixin is for use of APIs that are to be exposed on Window and WorkerGlobalScope objects.

Other standards are encouraged to further extend it using partial interface mixin WindowOrWorkerGlobalScope { … }; along with an appropriate reference.

typedef (DOMString or Function or TrustedScript) TimerHandler;

interface mixin WindowOrWorkerGlobalScope {
  [Replaceable] readonly attribute USVString origin;
  readonly attribute boolean isSecureContext;
  readonly attribute boolean crossOriginIsolated;

  undefined reportError(any e);

  // base64 utility methods
  DOMString btoa(DOMString data);
  ByteString atob(DOMString data);

  // timers
  long setTimeout(TimerHandler handler, optional long timeout = 0, any... arguments);
  undefined clearTimeout(optional long id = 0);
  long setInterval(TimerHandler handler, optional long timeout = 0, any... arguments);
  undefined clearInterval(optional long id = 0);

  // microtask queuing
  undefined queueMicrotask(VoidFunction callback);

  // ImageBitmap
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, optional ImageBitmapOptions options = {});
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh, optional ImageBitmapOptions options = {});

  // structured cloning
  any structuredClone(any value, optional StructuredSerializeOptions options = {});
};
Window includes WindowOrWorkerGlobalScope;
WorkerGlobalScope includes WindowOrWorkerGlobalScope;
self.isSecureContext

isSecureContext

Support in all current engines.

Firefox49+Safari11.1+Chrome47+
Opera?Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns whether or not this global object represents a secure context. [SECURE-CONTEXTS]

self.origin

origin

Support in all current engines.

Firefox54+Safari11+Chrome59+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the global object's origin, serialized as string.

self.crossOriginIsolated

crossOriginIsolated

Support in all current engines.

Firefox72+Safari15.2+Chrome87+
Opera?Edge87+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns whether scripts running in this global are allowed to use APIs that require cross-origin isolation. This depends on the `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` HTTP response headers and the "cross-origin-isolated" feature.

Developers are strongly encouraged to use self.origin over location.origin. The former returns the origin of the environment, the latter of the URL of the environment. Imagine the following script executing in a document on https://stargate.example/:

var frame = document.createElement("iframe")
frame.onload = function() {
  var frameWin = frame.contentWindow
  console.log(frameWin.location.origin) // "null"
  console.log(frameWin.origin) // "https://stargate.example"
}
document.body.appendChild(frame)

self.origin is a more reliable security indicator.

The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.

The origin getter steps are to return this's relevant settings object's origin, serialized.

The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.

8.3 Base64 utility methods

The atob() and btoa() methods allow developers to transform content to and from the base64 encoding.

In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.

result = self.btoa(data)

btoa

Support in all current engines.

Firefox1+Safari3+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.

Throws an "InvalidCharacterError" DOMException exception if the input string contains any out-of-range characters.

result = self.atob(data)

atob

Support in all current engines.

Firefox1+Safari3+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.

Throws an "InvalidCharacterError" DOMException if the input string is not valid base64 data.

The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data, and then must apply forgiving-base64 encode to that byte sequence and return the result.

The atob(data) method steps are:

  1. Let decodedData be the result of running forgiving-base64 decode on data.

  2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.

  3. Return decodedData.

8.4 Dynamic markup insertion

APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XML documents (and the XML parser).

Document objects have a throw-on-dynamic-markup-insertion counter, which is used in conjunction with the create an element for the token algorithm to prevent custom element constructors from being able to use document.open(), document.close(), and document.write() when they are invoked by the parser. Initially, the counter must be set to zero.

8.4.1 Opening the input stream

document = document.open()

Document/open

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

Causes the Document to be replaced in-place, as if it was a new Document object, but reusing the previous object, which is then returned.

The resulting Document has an HTML parser associated with it, which can be given data to parse using document.write().

The method has no effect if the Document is still being parsed.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

window = document.open(url, name, features)

Works like the window.open() method.

Document objects have an active parser was aborted boolean, which is used to prevent scripts from invoking the document.open() and document.write() methods (directly or indirectly) after the document's active parser has been aborted. It is initially false.

The document open steps, given a document, are as follows:

  1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.

  2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.

  3. Let entryDocument be the entry global object's associated Document.

  4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.

  5. If document has an active parser whose script nesting level is greater than 0, then return document.

    This basically causes document.open() to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.

  6. Similarly, if document's unload counter is greater than 0, then return document.

    This basically causes document.open() to be ignored when it's called from a beforeunload, pagehide, or unload event handler while the Document is being unloaded.

  7. If document's active parser was aborted is true, then return document.

    This notably causes document.open() to be ignored if it is called after a navigation has started, but only during the initial parse. See issue #4723 for more background.

  8. If document's node navigable is non-null and document's node navigable's ongoing navigation is a navigation ID, then stop loading document's node navigable.

  9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.

  10. If document is the associated Document of document's relevant global object, then erase all event listeners and handlers given document's relevant global object.

  11. Let oldFlag be the value of document's fire mutation events flag.
  12. Set document's fire mutation events flag to false.
  13. Replace all with null within document.

  14. Set document's fire mutation events flag to oldFlag.
  15. If document is fully active, then:

    1. Let newURL be a copy of entryDocument's URL.

    2. If entryDocument is not document, then set newURL's fragment to null.

    3. Run the URL and history update steps with document and newURL.

  16. Set document's is initial about:blank to false.

  17. If document's iframe load in progress flag is set, then set document's mute iframe load flag.

  18. Set document to no-quirks mode.

  19. Create a new HTML parser and associate it with document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.

  20. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).

  21. Update the current document readiness of document to "loading".

    This causes a readystatechange event to fire, but the event is actually unobservable to author code, because of the previous step which erased all event listeners and handlers that could observe it.

  22. Return document.

The document open steps do not affect whether a Document is ready for post-load tasks or completely loaded.

The open(unused1, unused2) method must return the result of running the document open steps with this.

The unused1 and unused2 arguments are ignored, but kept in the IDL to allow code that calls the function with one or two arguments to continue working. They are necessary due to Web IDL overload resolution algorithm rules, which would throw a TypeError exception for such calls had the arguments not been there. whatwg/webidl issue #581 investigates changing the algorithm to allow for their removal. [WEBIDL]

The open(url, name, features) method must run these steps:

  1. If this is not fully active, then throw an "InvalidAccessError" DOMException exception.

  2. Return the result of running the window open steps with url, name, and features.

8.4.2 Closing the input stream

document.close()

Document/close

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

Closes the input stream that was opened by the document.open() method.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

The close() method must run the following steps:

  1. If this is an XML document, then throw an "InvalidStateError" DOMException.

  2. If this's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an "InvalidStateError" DOMException.

  3. If there is no script-created parser associated with this, then return.

  4. Insert an explicit "EOF" character at the end of the parser's input stream.

  5. If this's pending parsing-blocking script is not null, then return.

  6. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.

8.4.3 document.write()

document.write(...text)

Document/write

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

In general, adds the given string(s) to the Document's input stream.

This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. Users agents are explicitly allowed to avoid executing script elements inserted via this method. And to make matters even worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.

Throws an "InvalidStateError" DOMException when invoked on XML documents.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

This method performs no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

Document objects have an ignore-destructive-writes counter, which is used in conjunction with the processing of script elements to prevent external scripts from being able to use document.write() to blow away the document by implicitly calling document.open(). Initially, the counter must be set to zero.

The document write steps, given a Document object document, a list text, a boolean lineFeed and a string sink, are as follows:

  1. Let string be the empty string.

  2. Let isTrusted be false if text contains a string; otherwise true.

  3. For each value of text:

    1. If value is a TrustedHTML object, then append value's associated data to string.

    2. Otherwise, append value to string.

  4. If isTrusted is false, set string to the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, string, sink, and "script".

  5. If lineFeed is true, append U+000A LINE FEED to string.

  6. If document is an XML document, then throw an "InvalidStateError" DOMException.

  7. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.

  8. If document's active parser was aborted is true, then return.

  9. If the insertion point is undefined, then:

    1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.

    2. Run the document open steps with document.

  10. Insert string into the input stream just before the insertion point.

  11. If document's pending parsing-blocking script is null, then have the HTML parser process string, one code point at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer).

    If the document.write() method was called from script executing inline (i.e. executing because the parser parsed a set of script tags), then this is a reentrant invocation of the parser. If the parser pause flag is set, the tokenizer will abort immediately and no HTML will be parsed, per the tokenizer's parser pause flag check.

The document.write(...text) method steps are to run the document write steps with this, text, false, and "Document write".

8.4.4 document.writeln()

document.writeln(...text)

Document/writeln

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

Adds the given string(s) to the Document's input stream, followed by a newline character. If necessary, calls the open() method implicitly first.

Throws an "InvalidStateError" DOMException when invoked on XML documents.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

This method performs no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

The document.writeln(...text) method steps are to run the document write steps with this, text, true, and "Document writeln".

8.5 DOM parsing and serialization APIs

DOMParser

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
partial interface Element {
  [CEReactions] undefined setHTMLUnsafe((TrustedHTML or DOMString) html);
  DOMString getHTML(optional GetHTMLOptions options = {});

  [CEReactions] attribute (TrustedHTML or [LegacyNullToEmptyString] DOMString) innerHTML;
  [CEReactions] attribute (TrustedHTML or [LegacyNullToEmptyString] DOMString) outerHTML;
  [CEReactions] undefined insertAdjacentHTML(DOMString position, (TrustedHTML or DOMString) string);
};

partial interface ShadowRoot {
  [CEReactions] undefined setHTMLUnsafe((TrustedHTML or DOMString) html);
  DOMString getHTML(optional GetHTMLOptions options = {});

  [CEReactions] attribute (TrustedHTML or [LegacyNullToEmptyString] DOMString) innerHTML;
};

dictionary GetHTMLOptions {
  boolean serializableShadowRoots = false;
  sequence<ShadowRoot> shadowRoots = [];
};

8.5.1 The DOMParser interface

The DOMParser interface allows authors to create new Document objects by parsing strings, as either HTML or XML.

parser = new DOMParser()

DOMParser/DOMParser

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Constructs a new DOMParser object.

document = parser.parseFromString(string, type)

DOMParser/parseFromString

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Parses string using either the HTML or XML parser, according to type, and returns the resulting Document. type can be "text/html" (which will invoke the HTML parser), or any of "text/xml", "application/xml", "application/xhtml+xml", or "image/svg+xml" (which will invoke the XML parser).

For the XML parser, if string cannot be parsed, then the returned Document will contain elements describing the resulting error.

Note that script elements are not evaluated during parsing, and the resulting document's encoding will always be UTF-8. The document's URL will be inherited from parser's relevant global object.

Values other than the above for type will cause a TypeError exception to be thrown.

The design of DOMParser, as a class that needs to be constructed and then have its parseFromString() method called, is an unfortunate historical artifact. If we were designing this functionality today it would be a standalone function. For parsing HTML, the modern alternative is Document.parseHTMLUnsafe().

This method performs no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

[Exposed=Window]
interface DOMParser {
  constructor();

  [NewObject] Document parseFromString((TrustedHTML or DOMString) string, DOMParserSupportedType type);
};

enum DOMParserSupportedType {
  "text/html",
  "text/xml",
  "application/xml",
  "application/xhtml+xml",
  "image/svg+xml"
};

The new DOMParser() constructor steps are to do nothing.

The parseFromString(string, type) method steps are:

  1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, string, "DOMParser parseFromString", and "script".

  2. Let document be a new Document, whose content type is type and URL is this's relevant global object's associated Document's URL.

    The document's encoding will be left as its default, of UTF-8. In particular, any XML declarations or meta elements found while parsing compliantString will have no effect.

  3. Switch on type:

    "text/html"
    1. Parse HTML from a string given document and compliantString.

    Since document does not have a browsing context, scripting is disabled.

    Otherwise
    1. Create an XML parser parser, associated with document, and with XML scripting support disabled.

    2. Parse compliantString using parser.

    3. If the previous step resulted in an XML well-formedness or XML namespace well-formedness error, then:

      1. Assert: document has no child nodes.

      2. Let root be the result of creating an element given document, "parsererror", and "http://www.mozilla.org/newlayout/xml/parsererror.xml".

      3. Optionally, add attributes or children to root to describe the nature of the parsing error.

      4. Append root to document.

  4. Return document.

To parse HTML from a string, given a Document document and a string html:

  1. Set document's type to "html".

  2. Create an HTML parser parser, associated with document.

  3. Place html into the input stream for parser. The encoding confidence is irrelevant.

  4. Start parser and let it run until it has consumed all the characters just inserted into the input stream.

    This might mutate the document's mode.

8.5.2 Unsafe HTML parsing methods

element.setHTMLUnsafe(html)

Parses html using the HTML parser, and replaces the children of element with the result. element provides context for the HTML parser.

shadowRoot.setHTMLUnsafe(html)

Parses html using the HTML parser, and replaces the children of shadowRoot with the result. shadowRoot's host provides context for the HTML parser.

doc = Document.parseHTMLUnsafe(html)

Parses html using the HTML parser, and returns the resulting Document.

Note that script elements are not evaluated during parsing, and the resulting document's encoding will always be UTF-8. The document's URL will be about:blank.

These methods perform no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

Element's setHTMLUnsafe(html) method steps are:

  1. Let compliantHTML be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, html, "Element setHTMLUnsafe", and "script".

  2. Let target be this's template contents if this is a template element; otherwise this.

  3. Unsafely set HTML given target, this, and compliantHTML.

ShadowRoot's setHTMLUnsafe(html) method steps are:

  1. Let compliantHTML be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, html, "ShadowRoot setHTMLUnsafe", and "script".

  2. Unsafely set HTML given this, this's shadow host, and compliantHTML.

To unsafely set HTML, given an Element or DocumentFragment target, an Element contextElement, and a string html:

  1. Let newChildren be the result of the HTML fragment parsing algorithm given contextElement, html, and true.

  2. Let fragment be a new DocumentFragment whose node document is contextElement's node document.

  3. For each node in newChildren, append node to fragment.

  4. Replace all with fragment within target.


The static parseHTMLUnsafe(html) method steps are:

  1. Let compliantHTML be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, html, "Document parseHTMLUnsafe", and "script".

  2. Let document be a new Document, whose content type is "text/html".

    Since document does not have a browsing context, scripting is disabled.

  3. Set document's allow declarative shadow roots to true.

  4. Parse HTML from a string given document and compliantHTML.

  5. Return document.

8.5.3 HTML serialization methods

html = element.getHTML({ serializableShadowRoots, shadowRoots })

Returns the result of serializing element to HTML. Shadow roots within element are serialized according to the provided options:

If neither option is provided, then no shadow roots are serialized.

html = shadowRoot.getHTML({ serializableShadowRoots, shadowRoots })

Returns the result of serializing shadowRoot to HTML, using its shadow host as the context element. Shadow roots within shadowRoot are serialized according to the provided options, as above.

Element's getHTML(options) method steps are to return the result of HTML fragment serialization algorithm with this, options["serializableShadowRoots"], and options["shadowRoots"].

ShadowRoot's getHTML(options) method steps are to return the result of HTML fragment serialization algorithm with this, options["serializableShadowRoots"], and options["shadowRoots"].

8.5.4 The innerHTML property

The innerHTML property has a number of outstanding issues in the DOM Parsing and Serialization issue tracker, documenting various problems with its specification.

element.innerHTML

Returns a fragment of HTML or XML that represents the element's contents.

In the case of an XML document, throws a "InvalidStateError" DOMException if the element cannot be serialized to XML.

element.innerHTML = value

Replaces the contents of the element with nodes parsed from the given string.

In the case of an XML document, throws a "SyntaxError" DOMException if the given string is not well-formed.

shadowRoot.innerHTML

Returns a fragment of HTML that represents the shadow roots's contents.

shadowRoot.innerHTML = value

Replaces the contents of the shadow root with nodes parsed from the given string.

These properties' setters perform no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

The fragment serializing algorithm steps, given an Element, Document or DocumentFragment node and a boolean require well-formed, are:

  1. Let context document be node's node document.

  2. If context document is an HTML document, return the result of HTML fragment serialization algorithm with node, false, and « ».

  3. Return the XML serialization of node given require well-formed.

The fragment parsing algorithm steps, given an Element context and a string markup, are:

  1. Let algorithm be the HTML fragment parsing algorithm.

  2. If context's node document is an XML document, then set algorithm to the XML fragment parsing algorithm.

  3. Let new children be the result of invoking algorithm given markup, with context set to context.

  4. Let fragment be a new DocumentFragment whose node document is context's node document.

  5. Append each Node in new children to fragment (in tree order).

    This ensures the node document for the new nodes is correct.

  6. Return fragment.

Element's innerHTML getter steps are to return the result of running fragment serializing algorithm steps with this and true.

ShadowRoot's innerHTML getter steps are to return the result of running fragment serializing algorithm steps with this and true.

Element's innerHTML setter steps are:

  1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, the given value, "Element innerHTML", and "script".

  2. Let context be this.

  3. Let fragment be the result of invoking the fragment parsing algorithm steps with context and compliantString.

  4. If context is a template element, then set context to the template element's template contents (a DocumentFragment).

    Setting innerHTML on a template element will replace all the nodes in its template contents rather than its children.

  5. Replace all with fragment within context.

ShadowRoot's innerHTML setter steps are:

  1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, the given value, "ShadowRoot innerHTML", and "script".

  2. Let context be this's host.

  3. Let fragment be the result of invoking the fragment parsing algorithm steps with context and compliantString.

  4. Replace all with fragment within this.

8.5.5 The outerHTML property

The outerHTML property has a number of outstanding issues in the DOM Parsing and Serialization issue tracker, documenting various problems with its specification.

element.outerHTML

Returns a fragment of HTML or XML that represents the element and its contents.

In the case of an XML document, throws a "InvalidStateError" DOMException if the element cannot be serialized to XML.

element.outerHTML = value

Replaces the element with nodes parsed from the given string.

In the case of an XML document, throws a "SyntaxError" DOMException if the given string is not well-formed.

Throws a "NoModificationAllowedError" DOMException if the parent of the element is a Document.

This property's setter performs no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

Element's outerHTML getter steps are:

  1. Let element be a fictional node whose only child is this.

  2. Return the result of running fragment serializing algorithm steps with element and true.

Element's outerHTML setter steps are:

  1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, the given value, "Element outerHTML", and "script".

  2. Let parent be this's parent.

  3. If parent is null, return. There would be no way to obtain a reference to the nodes created even if the remaining steps were run.

  4. If parent is a Document, throw a "NoModificationAllowedError" DOMException.

  5. If parent is a DocumentFragment, set parent to the result of creating an element given this's node document, body, and the HTML namespace.

  6. Let fragment be the result of invoking the fragment parsing algorithm steps given parent and compliantString.

  7. Replace this with fragment within this's parent.

8.5.6 The insertAdjacentHTML() method

The insertAdjacentHTML() method has a number of outstanding issues in the DOM Parsing and Serialization issue tracker, documenting various problems with its specification.

element.insertAdjacentHTML(position, string)

Parses string as HTML or XML and inserts the resulting nodes into the tree in the position given by the position argument, as follows:

"beforebegin"
Before the element itself (i.e., after element's previous sibling)
"afterbegin"
Just inside the element, before its first child.
"beforeend"
Just inside the element, after its last child.
"afterend"
After the element itself (i.e., before element's next sibling)

Throws a "SyntaxError" DOMException if the arguments have invalid values (e.g., in the case of an XML document, if the given string is not well-formed).

Throws a "NoModificationAllowedError" DOMException if the given position isn't possible (e.g. inserting elements after the root element of a Document).

This method performs no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

Element's insertAdjacentHTML(position, string) method steps are:

  1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, string, "Element insertAdjacentHTML", and "script".

  2. Let context be null.

  3. Use the first matching item from this list:

    If position is an ASCII case-insensitive match for the string "beforebegin"
    If position is an ASCII case-insensitive match for the string "afterend"
    1. Set context to this's parent.

    2. If context is null or a Document, throw a "NoModificationAllowedError" DOMException.

    If position is an ASCII case-insensitive match for the string "afterbegin"
    If position is an ASCII case-insensitive match for the string "beforeend"
    Set context to this.
    Otherwise

    Throw a "SyntaxError" DOMException.

  4. If context is not an Element or all of the following are true:

    set context to the result of creating an element given this's node document, body, and the HTML namespace.

  5. Let fragment be the result of invoking the fragment parsing algorithm steps with context and compliantString.

  6. Use the first matching item from this list:
    If position is an ASCII case-insensitive match for the string "beforebegin"

    Insert fragment into this's parent before this.

    If position is an ASCII case-insensitive match for the string "afterend"

    Insert fragment into this before its first child.

    If position is an ASCII case-insensitive match for the string "afterbegin"

    Append fragment to this.

    If position is an ASCII case-insensitive match for the string "beforeend"

    Insert fragment into this's parent before this's next sibling.

As with other direct Node-manipulation APIs (and unlike innerHTML), insertAdjacentHTML() does not include any special handling for template elements. In most cases you will want to use templateEl.content.insertAdjacentHTML() instead of directly manipulating the child nodes of a template element.

8.5.7 The createContextualFragment() method

The createContextualFragment() method has a number of outstanding issues in the DOM Parsing and Serialization issue tracker, documenting various problems with its specification.

docFragment = range.createContextualFragment(string)

Returns a DocumentFragment created from the markup string string using range's start node as the context in which fragment is parsed.

This method performs no sanitization to remove potentially-dangerous elements and attributes like script or event handler content attributes.

partial interface Range {
  [CEReactions, NewObject] DocumentFragment createContextualFragment((TrustedHTML or DOMString) string);
};

Range's createContextualFragment(string) method steps are:

  1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, string, and "Range createContextualFragment".

  2. Let node be this's start node.

  3. Let element be null.

  4. If node implements Element, set element to node.

  5. Otherwise, if node implements Text or Comment, set element to node's parent element.

  6. If element is null or all of the following are true:

    then set element to the result of creating an element given this's node document, body, and the HTML namespace.

  7. Let fragment node be the result of invoking the fragment parsing algorithm steps with element and compliantString.

  8. For each script of fragment node's script element descendants:

    1. Set script's already started to false.

    2. Set script's parser document to null.

  9. Return fragment node.

8.6 Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

id = self.setTimeout(handler [, timeout [, ...arguments ] ])

setTimeout

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

id = self.setTimeout(code [, timeout ])

Schedules a timeout to compile and run code after timeout milliseconds.

self.clearTimeout(id)

clearTimeout

Support in all current engines.

Firefox1+Safari4+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Cancels the timeout set with setTimeout() or setInterval() identified by id.

id = self.setInterval(handler [, timeout [, ...arguments ] ])

setInterval

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

id = self.setInterval(code [, timeout ])

Schedules a timeout to compile and run code every timeout milliseconds.

self.clearInterval(id)

clearInterval

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Cancels the timeout set with setInterval() or setTimeout() identified by id.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

Objects that implement the WindowOrWorkerGlobalScope mixin have a map of setTimeout and setInterval IDs, which is an ordered map, initially empty. Each key in this map is a positive integer, corresponding to the return value of a setTimeout() or setInterval() call. Each value is a unique internal value, corresponding to a key in the object's map of active timers.


The setTimeout(handler, timeout, ...arguments) method steps are to return the result of running the timer initialization steps given this, handler, timeout, arguments, and false.

The setInterval(handler, timeout, ...arguments) method steps are to return the result of running the timer initialization steps given this, handler, timeout, arguments, and true.

The clearTimeout(id) and clearInterval(id) method steps are to remove this's map of setTimeout and setInterval IDs[id].

Because clearTimeout() and clearInterval() clear entries from the same map, either method can be used to clear timers created by setTimeout() or setInterval().


To perform the timer initialization steps, given a WindowOrWorkerGlobalScope global, a string or Function or TrustedScript handler, a number timeout, a list arguments, a boolean repeat, and optionally (and only if repeat is true) a number previousId, perform the following steps. They return a number.

  1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.

  2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of setTimeout and setInterval IDs.

  3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.

    The task's timer nesting level is used both for nested calls to setTimeout(), and for the repeating timers created by setInterval(). (Or, indeed, for any combination of the two.) In other words, it represents nested invocations of this algorithm, not of a particular method.

  4. If timeout is less than 0, then set timeout to 0.

  5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.

  6. Let realm be global's relevant realm.

  7. Let initiating script be the active script.

  8. Let uniqueHandle be null.

  9. Let task be a task that runs the following substeps:

    1. Assert: uniqueHandle is a unique internal value, not null.

    2. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.

    3. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.

      This accommodates for the ID having been cleared by a clearTimeout() or clearInterval() call, and being reused by a subsequent setTimeout() or setInterval() call.

    4. Record timing info for timer handler given handler, global's relevant settings object, and repeat.

    5. If handler is a Function, then invoke handler given arguments and "report", and with callback this value set to thisArg.

    6. Otherwise:

      1. If previousId was not given:

        1. Let globalName be "Window" if this's relevant global object is a Window object; "Worker" otherwise.

        2. Let methodName be "setInterval" if repeat is true; "setTimeout" otherwise.

        3. Let sink be a concatenation of globalName, U+0020 SPACE, and methodName.

        4. Set handler to the result of invoking the Get Trusted Type compliant string algorithm with TrustedScript, this's relevant global object, handler, sink, and "script".

      2. Assert: handler is a string.

      3. Perform EnsureCSPDoesNotBlockStringCompilation(realm, « », handler, handler, timer, « », handler). If this throws an exception, catch it, report it for global, and abort these steps.

      4. Let settings object be global's relevant settings object.

      5. Let fetch options be the default classic script fetch options.

      6. Let base URL be settings object's API base URL.

      7. If initiating script is not null, then:

        1. Set fetch options to a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, referrer policy is initiating script's fetch options's referrer policy, and fetch priority is "auto".

        2. Set base URL to initiating script's base URL.

        The effect of these steps ensures that the string compilation done by setTimeout() and setInterval() behaves equivalently to that done by eval(). That is, module script fetches via import() will behave the same in both contexts.

      8. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.

      9. Run the classic script script.

    7. If id does not exist in global's map of setTimeout and setInterval IDs, then abort these steps.

    8. If global's map of setTimeout and setInterval IDs[id] does not equal uniqueHandle, then abort these steps.

      The ID might have been removed via the author code in handler calling clearTimeout() or clearInterval(). Checking that uniqueHandle isn't different accounts for the possibility of the ID, after having been cleared, being reused by a subsequent setTimeout() or setInterval() call.

    9. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.

    10. Otherwise, remove global's map of setTimeout and setInterval IDs[id].

  10. Increment nesting level by one.

  11. Set task's timer nesting level to nesting level.

  12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.

  13. Set uniqueHandle to the result of running steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep.

  14. Set global's map of setTimeout and setInterval IDs[id] to uniqueHandle.

  15. Return id.

Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

So for example, the following rather silly code will result in the log containing "ONE TWO ":

var log = '';
function logger(s) { log += s + ' '; }

setTimeout({ toString: function () {
  setTimeout("logger('ONE')", 100);
  return "logger('TWO')";
} }, 100);

To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:

function doExpensiveWork() {
  var done = false;
  // ...
  // this part of the function takes up to five milliseconds
  // set done to true if we're done
  // ...
  return done;
}

function rescheduleWork() {
  var id = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(id); // clear the timeout if we don't need it
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

Objects that implement the WindowOrWorkerGlobalScope mixin have a map of active timers, which is an ordered map, initially empty. Each key in this map is a unique internal value that represents a timer, and each value is a DOMHighResTimeStamp, representing the expiry time for that timer.

To run steps after a timeout, given a WindowOrWorkerGlobalScope global, a string orderingIdentifier, a number milliseconds, and a set of steps completionSteps, perform the following steps. They return a unique internal value.

  1. Let timerKey be a new unique internal value.

  2. Let startTime be the current high resolution time given global.

  3. Set global's map of active timers[timerKey] to startTime plus milliseconds.

  4. Run the following steps in parallel:

    1. If global is a Window object, wait until global's associated Document has been fully active for a further milliseconds milliseconds (not necessarily consecutively).

      Otherwise, global is a WorkerGlobalScope object; wait until milliseconds milliseconds have passed with the worker not suspended (not necessarily consecutively).

    2. Wait until any invocations of this algorithm that had the same global and orderingIdentifier, that started before this one, and whose milliseconds is less than or equal to this one's, have completed.

    3. Optionally, wait a further implementation-defined length of time.

      This is intended to allow user agents to pad timeouts as needed to optimize the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

    4. Perform completionSteps.

    5. Remove global's map of active timers[timerKey].

  5. Return timerKey.

Run steps after a timeout is meant to be used by other specifications that want to execute developer-supplied code after a developer-supplied timeout, in a similar manner to setTimeout(). (Note, however, it does not have the nesting and clamping behavior of setTimeout().) Such specifications can choose an orderingIdentifier to ensure ordering within their specification's timeouts, while not constraining ordering with respect to other specification's timeouts.

8.7 Microtask queuing

queueMicrotask

Support in all current engines.

Firefox69+Safari12.1+Chrome71+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
self.queueMicrotask(callback)

Queues a microtask to run the given callback.

The queueMicrotask(callback) method must queue a microtask to invoke callback with « » and "report".

The queueMicrotask() method allows authors to schedule a callback on the microtask queue. This allows their code to run once the JavaScript execution context stack is next empty, which happens once all currently executing synchronous JavaScript has run to completion. This doesn't yield control back to the event loop, as would be the case when using, for example, setTimeout(f, 0).

Authors ought to be aware that scheduling a lot of microtasks has the same performance downsides as running a lot of synchronous code. Both will prevent the browser from doing its own work, such as rendering. In many cases, requestAnimationFrame() or requestIdleCallback() is a better choice. In particular, if the goal is to run code before the next rendering cycle, that is the purpose of requestAnimationFrame().

As can be seen from the following examples, the best way of thinking about queueMicrotask() is as a mechanism for rearranging synchronous code, effectively placing the queued code immediately after the currently executing synchronous JavaScript has run to completion.

The most common reason for using queueMicrotask() is to create consistent ordering, even in the cases where information is available synchronously, without introducing undue delay.

For example, consider a custom element firing a load event, that also maintains an internal cache of previously-loaded data. A naïve implementation might look like:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    this._setData(this._cache[url]);
    this.dispatchEvent(new Event("load"));
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

This naïve implementation is problematic, however, in that it causes its users to experience inconsistent behavior. For example, code such as

element.addEventListener("load", () => console.log("loaded"));
console.log("1");
element.loadData();
console.log("2");

will sometimes log "1, 2, loaded" (if the data needs to be fetched), and sometimes log "1, loaded, 2" (if the data is already cached). Similarly, after the call to loadData(), it will be inconsistent whether or not the data is set on the element.

To get a consistent ordering, queueMicrotask() can be used:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    queueMicrotask(() => {
      this._setData(this._cache[url]);
      this.dispatchEvent(new Event("load"));
    });
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

By essentially rearranging the queued code to be after the JavaScript execution context stack empties, this ensures a consistent ordering and update of the element's state.

Another interesting use of queueMicrotask() is to allow uncoordinated "batching" of work by multiple callers. For example, consider a library function that wants to send data somewhere as soon as possible, but doesn't want to make multiple network requests if doing so is easily avoidable. One way to balance this would be like so:

const queuedToSend = [];

function sendData(data) {
  queuedToSend.push(data);

  if (queuedToSend.length === 1) {
    queueMicrotask(() => {
      const stringToSend = JSON.stringify(queuedToSend);
      queuedToSend.length = 0;

      fetch("/endpoint", stringToSend);
    });
  }
}

With this architecture, multiple subsequent calls to sendData() within the currently executing synchronous JavaScript will be batched together into one fetch() call, but with no intervening event loop tasks preempting the fetch (as would have happened with similar code that instead used setTimeout()).

8.8 User prompts

8.8.1 Simple dialogs

window.alert(message)

Window/alert

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Displays a modal alert with the given message, and waits for the user to dismiss it.

result = window.confirm(message)

Window/confirm

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android1+Samsung Internet?Opera Android10.1+

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

result = window.prompt(message [, default])

Window/prompt

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Displays a modal text control prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

The alert() and alert(message) method steps are:

  1. If we cannot show simple dialogs for this, then return.

  2. If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method's first argument.

  3. Set message to the result of normalizing newlines given message.

  4. Set message to the result of optionally truncating message.

  5. Show message to the user, treating U+000A LF as a line break.

  6. Invoke WebDriver BiDi user prompt opened with this, "alert", and message.

  7. Optionally, pause while waiting for the user to acknowledge the message.

  8. Invoke WebDriver BiDi user prompt closed with this and true.

This method is defined using two overloads, instead of using an optional argument, for historical reasons. The practical impact of this is that alert(undefined) is treated as alert("undefined"), but alert() is treated as alert("").

The confirm(message) method steps are:

  1. If we cannot show simple dialogs for this, then return false.

  2. Set message to the result of normalizing newlines given message.

  3. Set message to the result of optionally truncating message.

  4. Show message to the user, treating U+000A LF as a line break, and ask the user to respond with a positive or negative response.

  5. Invoke WebDriver BiDi user prompt opened with this, "confirm", and message.

  6. Pause until the user responds either positively or negatively.

  7. Invoke WebDriver BiDi user prompt closed with this, and true if the user responded positively or false otherwise.

  8. If the user responded positively, return true; otherwise, the user responded negatively: return false.

The prompt(message, default) method steps are:

  1. If we cannot show simple dialogs for this, then return null.

  2. Set message to the result of normalizing newlines given message.

  3. Set message to the result of optionally truncating message.

  4. Set default to the result of optionally truncating default.

  5. Show message to the user, treating U+000A LF as a line break, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.

  6. Invoke WebDriver BiDi user prompt opened with this, "prompt", message, and default.

  7. Pause while waiting for the user's response.

  8. Let result be null if the user aborts, or otherwise the string that the user responded with.

  9. Invoke WebDriver BiDi user prompt closed with this, false if result is null or true otherwise, and result.

  10. Return result.

To optionally truncate a simple dialog string s, return either s itself or some string derived from s that is shorter. User agents should not provide UI for displaying the elided portion of s, as this makes it too easy for abusers to create dialogs of the form "Important security alert! Click 'Show More' for full details!".

For example, a user agent might want to only display the first 100 characters of a message. Or, a user agent might replace the middle of the string with "…". These types of modifications can be useful in limiting the abuse potential of unnaturally large, trustworthy-looking system dialogs.

We cannot show simple dialogs for a Window window when the following algorithm returns true:

  1. If the active sandboxing flag set of window's associated Document has the sandboxed modals flag set, then return true.

  2. If window's relevant settings object's origin and window's relevant settings object's top-level origin are not same origin-domain, then return true.

  3. If window's relevant agent's event loop's termination nesting level is nonzero, then optionally return true.
  4. Optionally, return true. (For example, the user agent might give the user the option to ignore all modal dialogs, and would thus abort at this step whenever the method was invoked.)

  5. Return false.

8.8.2 Printing

Window/print

Support in all current engines.

Firefox1+Safari1.1+Chrome1+
Opera6+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android114+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
window.print()

Prompts the user to print the page.

The print() method steps are:

  1. Let document be this's associated Document.

  2. If document is not fully active, then return.

  3. If document's unload counter is greater than 0, then return.

  4. If document is ready for post-load tasks, then run the printing steps for document.

  5. Otherwise, set document's print when loaded flag.

User agents should also run the printing steps whenever the user asks for the opportunity to obtain a physical form (e.g. printed copy), or the representation of a physical form (e.g. PDF copy), of a document.

The printing steps for a Document document are:

  1. The user agent may display a message to the user or return (or both).

    For instance, a kiosk browser could silently ignore any invocations of the print() method.

    For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.

  2. If the active sandboxing flag set of document has the sandboxed modals flag set, then return.

    If the printing dialog is blocked by a Document's sandbox, then neither the beforeprint nor afterprint events will be fired.

  3. The user agent must fire an event named beforeprint at the relevant global object of document, as well as any child navigable in it.

    Firing in children only doesn't seem right here, and some tasks likely need to be queued. See issue #5096.

    The beforeprint event can be used to annotate the printed copy, for instance adding the time at which the document was printed.

  4. The user agent should offer the user the opportunity to obtain a physical form (or the representation of a physical form) of document. The user agent may wait for the user to either accept or decline before returning; if so, the user agent must pause while the method is waiting. Even if the user agent doesn't wait at this point, the user agent must use the state of the relevant documents as they are at this point in the algorithm if and when it eventually creates the alternate form.

  5. The user agent must fire an event named afterprint at the relevant global object of document, as well as any child navigables in it.

    Firing in children only doesn't seem right here, and some tasks likely need to be queued. See issue #5096.

    The afterprint event can be used to revert annotations added in the earlier event, as well as showing post-printing UI. For instance, if a page is walking the user through the steps of applying for a home loan, the script could automatically advance to the next step after having printed a form or other.

8.9 System state and capabilities

8.9.1 The Navigator object

Navigator

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Instances of Navigator represent the identity and state of the user agent (the client). They also serve as a generic global under which various APIs are located in this and other specifications.

[Exposed=Window]
interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator includes NavigatorID;
Navigator includes NavigatorLanguage;
Navigator includes NavigatorOnLine;
Navigator includes NavigatorContentUtils;
Navigator includes NavigatorCookies;
Navigator includes NavigatorPlugins;
Navigator includes NavigatorConcurrentHardware;

These interface mixins are defined separately so that WorkerNavigator can reuse parts of the Navigator interface.

Each Window has an associated Navigator, which is a Navigator object. Upon creation of the Window object, its associated Navigator must be set to a new Navigator object created in the Window object's relevant realm.

Window/navigator

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

The navigator and clientInformation getter steps are to return this's associated Navigator.

8.9.1.1 Client identification
interface mixin NavigatorID {
  readonly attribute DOMString appCodeName; // constant "Mozilla"
  readonly attribute DOMString appName; // constant "Netscape"
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  readonly attribute DOMString product; // constant "Gecko"
  [Exposed=Window] readonly attribute DOMString productSub;
  readonly attribute DOMString userAgent;
  [Exposed=Window] readonly attribute DOMString vendor;
  [Exposed=Window] readonly attribute DOMString vendorSub; // constant ""
};

In certain cases, despite the best efforts of the entire industry, web browsers have bugs and limitations that web authors are forced to work around.

This section defines a collection of attributes that can be used to determine, from script, the kind of user agent in use, in order to work around these issues.

The user agent has a navigator compatibility mode, which is either Chrome, Gecko, or WebKit.

The navigator compatibility mode constrains the NavigatorID mixin to the combinations of attribute values and presence of taintEnabled() and oscpu that are known to be compatible with existing web content.

Client detection should always be limited to detecting known current versions; future versions and unknown versions should always be assumed to be fully compliant.

self.navigator.appCodeName

Returns the string "Mozilla".

self.navigator.appName

Returns the string "Netscape".

self.navigator.appVersion

Returns the version of the browser.

self.navigator.platform

Returns the name of the platform.

self.navigator.product

Returns the string "Gecko".

window.navigator.productSub

Returns either the string "20030107", or the string "20100101".

self.navigator.userAgent

Navigator/userAgent

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

WorkerNavigator/userAgent

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Returns the complete `User-Agent` header.

window.navigator.vendor

Returns either the empty string, the string "Apple Computer, Inc.", or the string "Google Inc.".

window.navigator.vendorSub

Returns the empty string.

appCodeName

Must return the string "Mozilla".

appName

Must return the string "Netscape".

appVersion

Must return the appropriate string that starts with "5.0 (", as follows:

Let trail be the substring of default `User-Agent` value that follows the "Mozilla/" prefix.

If the navigator compatibility mode is Chrome or WebKit

Return trail.

If the navigator compatibility mode is Gecko

If trail starts with "5.0 (Windows", then return "5.0 (Windows)".

Otherwise, return the prefix of trail up to but not including the first U+003B (;), concatenated with the character U+0029 RIGHT PARENTHESIS. For example, "5.0 (Macintosh)", "5.0 (Android 10)", or "5.0 (X11)".

platform

Must return a string representing the platform on which the browser is executing (e.g. "MacIntel", "Win32", "Linux x86_64", "Linux armv81") or, for privacy and compatibility, a string that is commonly returned on another platform.

product

Must return the string "Gecko".

productSub

Must return the appropriate string from the following list:

If the navigator compatibility mode is Chrome or WebKit

The string "20030107".

If the navigator compatibility mode is Gecko

The string "20100101".

userAgent

Must return the default `User-Agent` value.

vendor

Must return the appropriate string from the following list:

If the navigator compatibility mode is Chrome

The string "Google Inc.".

If the navigator compatibility mode is Gecko

The empty string.

If the navigator compatibility mode is WebKit

The string "Apple Computer, Inc.".

vendorSub

Must return the empty string.

If the navigator compatibility mode is Gecko, then the user agent must also support the following partial interface:

partial interface mixin NavigatorID {
  [Exposed=Window] boolean taintEnabled(); // constant false
  [Exposed=Window] readonly attribute DOMString oscpu;
};

The taintEnabled() method must return false.

The oscpu attribute's getter must return either the empty string or a string representing the platform on which the browser is executing, e.g. "Windows NT 10.0; Win64; x64", "Linux x86_64".

(This is a tracking vector.) Any information in this API that varies from user to user can be used to profile the user. In fact, if enough such information is available, a user can actually be uniquely identified. For this reason, user agent implementers are strongly urged to include as little information in this API as possible.

8.9.1.2 Language preferences
interface mixin NavigatorLanguage {
  readonly attribute DOMString language;
  readonly attribute FrozenArray<DOMString> languages;
};
self.navigator.language

Navigator/language

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

WorkerNavigator/language

Support in all current engines.

Firefox3.5+Safari10+Chrome4+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Returns a language tag representing the user's preferred language.

self.navigator.languages

Navigator/languages

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera24+Edge79+
Edge (Legacy)16+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet3.0+Opera Android24+

WorkerNavigator/languages

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera24+Edge79+
Edge (Legacy)16+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet3.0+Opera Android24+

Returns an array of language tags representing the user's preferred languages, with the most preferred language first.

The most preferred language is the one returned by navigator.language.

A languagechange event is fired at the Window or WorkerGlobalScope object when the user agent's understanding of what the user's preferred languages are changes.

language

Must return a valid BCP 47 language tag representing either a plausible language or the user's most preferred language. [BCP47]

languages

Must return a frozen array of valid BCP 47 language tags representing either one or more plausible languages, or the user's preferred languages, ordered by preference with the most preferred language first. The same object must be returned until the user agent needs to return different values, or values in a different order. [BCP47]

Whenever the user agent needs to make the navigator.languages attribute of a Window or WorkerGlobalScope object global return a new set of language tags, the user agent must queue a global task on the DOM manipulation task source given global to fire an event named languagechange at global, and wait until that task begins to be executed before actually returning a new value.

To determine a plausible language, the user agent should bear in mind the following:

(This is a tracking vector.) To avoid introducing any more fingerprinting vectors, user agents should use the same list for the APIs defined in this function as for the HTTP `Accept-Language` header.

interface mixin NavigatorOnLine {
  readonly attribute boolean onLine;
};
self.navigator.onLine

Navigator/onLine

Support in all current engines.

Firefox1.5+Safari4+Chrome2+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS?Chrome Android18+WebView Android🔰 37+Samsung Internet?Opera Android10.1+

WorkerNavigator/onLine

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android?WebView Android🔰 4.4+Samsung Internet?Opera Android11+

Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.

The events online and offline are fired when the value of this attribute changes.

The onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.

When the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope global changes from true to false, the user agent must queue a global task on the networking task source given global to fire an event named offline at global.

On the other hand, when the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope global changes from false to true, the user agent must queue a global task on the networking task source given global to fire an event named online at the Window or WorkerGlobalScope object.

This attribute is inherently unreliable. A computer can be connected to a network without having Internet access.

In this example, an indicator is updated as the browser goes online and offline.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Online status</title>
  <script>
   function updateIndicator() {
     document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
   }
  </script>
 </head>
 <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
  <p>The network is: <span id="indicator">(state unknown)</span>
 </body>
</html>
8.9.1.4 Custom scheme handlers: the registerProtocolHandler() method

Navigator/registerProtocolHandler

Firefox2+SafariNoChrome13+
Opera11.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android?Safari iOS?Chrome AndroidNoWebView Android?Samsung Internet?Opera Android?
interface mixin NavigatorContentUtils {
  [SecureContext] undefined registerProtocolHandler(DOMString scheme, USVString url);
  [SecureContext] undefined unregisterProtocolHandler(DOMString scheme, USVString url);
};
window.navigator.registerProtocolHandler(scheme, url)

Registers a handler for scheme at url. For example, an online telephone messaging service could register itself as a handler of the sms: scheme, so that if the user clicks on such a link, they are given the opportunity to use that web site. [SMS]

The string "%s" in url is used as a placeholder for where to put the URL of the content to be handled.

Throws a "SecurityError" DOMException if the user agent blocks the registration (this might happen if trying to register as a handler for "http", for instance).

Throws a "SyntaxError" DOMException if the "%s" string is missing in url.

window.navigator.unregisterProtocolHandler(scheme, url)

Navigator/unregisterProtocolHandler

Support in one engine only.

FirefoxNoSafariNoChrome38+
Opera25+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome AndroidNoWebView Android?Samsung Internet?Opera Android?

Unregisters the handler given by the arguments.

Throws a "SecurityError" DOMException if the user agent blocks the deregistration (this might happen if with invalid schemes, for instance).

Throws a "SyntaxError" DOMException if the "%s" string is missing in url.

The registerProtocolHandler(scheme, url) method steps are:

  1. Let (normalizedScheme, normalizedURLString) be the result of running normalize protocol handler parameters with scheme, url, and this's relevant settings object.

  2. In parallel: register a protocol handler for normalizedScheme and normalizedURLString. User agents may, within the constraints described, do whatever they like. A user agent could, for instance, prompt the user and offer the user the opportunity to add the site to a shortlist of handlers, or make the handlers their default, or cancel the request. User agents could also silently collect the information, providing it only when relevant to the user.

    User agents should keep track of which sites have registered handlers (even if the user has declined such registrations) so that the user is not repeatedly prompted with the same request.

    If the registerProtocolHandler() automation mode of this's relevant global object's associated Document is not "none", the user agent should first verify that it is in an automation context (see WebDriver's security considerations). The user agent should then bypass the above communication of information and gathering of user consent, and instead do the following based on the value of the registerProtocolHandler() automation mode:

    "autoAccept"

    Act as if the user has seen the registration details and accepted the request.

    "autoReject"

    Act as if the user has seen the registration details and rejected the request.

    When the user agent uses this handler for a URL inputURL:

    1. Assert: inputURL's scheme is normalizedScheme.

    2. Set the username given inputURL and the empty string.

    3. Set the password given inputURL and the empty string.

    4. Let inputURLString be the serialization of inputURL.

    5. Let encodedURL be the result of running UTF-8 percent-encode on inputURLString using the component percent-encode set.

    6. Let handlerURLString be normalizedURLString.

    7. Replace the first instance of "%s" in handlerURLString with encodedURL.

    8. Let resultURL be the result of parsing handlerURLString.

    9. Navigate an appropriate navigable to resultURL.

    If the user had visited a site at https://example.com/ that made the following call:

    navigator.registerProtocolHandler('web+soup', 'soup?url=%s')

    ...and then, much later, while visiting https://www.example.net/, clicked on a link such as:

    <a href="web+soup:chicken-kïwi">Download our Chicken Kïwi soup!</a>

    ...then the UA might navigate to the following URL:

    https://example.com/soup?url=web+soup:chicken-k%C3%AFwi

    This site could then do whatever it is that it does with soup (synthesize it and ship it to the user, or whatever).

    This does not define when the handler is used. To some extent, the processing model for navigating across documents defines some cases where it is relevant, but in general user agents may use this information wherever they would otherwise consider handing schemes to native plugins or helper applications.

The unregisterProtocolHandler(scheme, url) method steps are:

  1. Let (normalizedScheme, normalizedURLString) be the result of running normalize protocol handler parameters with scheme, url, and this's relevant settings object.

  2. In parallel: unregister the handler described by normalizedScheme and normalizedURLString.


To normalize protocol handler parameters, given a string scheme, a string url, and an environment settings object environment, run these steps:

  1. Set scheme to scheme, converted to ASCII lowercase.

  2. If scheme is neither a safelisted scheme nor a string starting with "web+" followed by one or more ASCII lower alphas, then throw a "SecurityError" DOMException.

    This means that including a colon in scheme (as in "mailto:") will throw.

    The following schemes are the safelisted schemes:

    This list can be changed. If there are schemes that ought to be added, please send feedback.

  3. If url does not contain "%s", then throw a "SyntaxError" DOMException.

  4. Let urlRecord be the result of encoding-parsing a URL given url, relative to environment.

  5. If urlRecord is failure, then throw a "SyntaxError" DOMException.

    This is forcibly the case if the %s placeholder is in the host or port of the URL.

  6. If urlRecord's scheme is not an HTTP(S) scheme or urlRecord's origin is not same origin with environment's origin, then throw a "SecurityError" DOMException.

  7. Assert: the result of Is url potentially trustworthy? given urlRecord is "Potentially Trustworthy".

    Because normalize protocol handler parameters is run within a secure context, this is implied by the same origin condition.

  8. Return (scheme, urlRecord).

    The serialization of urlRecord will by definition not be a valid URL string as it includes the string "%s" which is not a valid component in a URL.

8.9.1.4.1 Security and privacy

Custom scheme handlers can introduce a number of concerns, in particular privacy concerns.

Hijacking all web usage. User agents should not allow schemes that are key to its normal operation, such as an HTTP(S) scheme, to be rerouted through third-party sites. This would allow a user's activities to be trivially tracked, and would allow user information, even in secure connections, to be collected.

Hijacking defaults. User agents are strongly urged to not automatically change any defaults, as this could lead the user to send data to remote hosts that the user is not expecting. New handlers registering themselves should never automatically cause those sites to be used.

Registration spamming. User agents should consider the possibility that a site will attempt to register a large number of handlers, possibly from multiple domains (e.g., by redirecting through a series of pages each on a different domain, and each registering a handler for web+spam: — analogous practices abusing other web browser features have been used by pornography web sites for many years). User agents should gracefully handle such hostile attempts, protecting the user.

Hostile handler metadata. User agents should protect against typical attacks against strings embedded in their interface, for example ensuring that markup or escape characters in such strings are not executed, that null bytes are properly handled, that over-long strings do not cause crashes or buffer overruns, and so forth.

Leaking private data. Web page authors may reference a custom scheme handler using URL data considered private. They might do so with the expectation that the user's choice of handler points to a page inside the organization, ensuring that sensitive data will not be exposed to third parties. However, a user may have registered a handler pointing to an external site, resulting in a data leak to that third party. Implementers might wish to consider allowing administrators to disable custom handlers on certain subdomains, content types, or schemes.

Interface interference. User agents should be prepared to handle intentionally long arguments to the methods. For example, if the user interface exposed consists of an "accept" button and a "deny" button, with the "accept" binding containing the name of the handler, it's important that a long name not cause the "deny" button to be pushed off the screen.

8.9.1.4.2 User agent automation

Each Document has a registerProtocolHandler() automation mode. It defaults to "none", but it also can be either "autoAccept" or "autoReject".

For the purposes of user agent automation and website testing, this standard defines Set RPH Registration Mode WebDriver extension command. It instructs the user agent to place a Document into a mode where it will automatically simulate a user either accepting or rejecting and registration confirmation prompt dialog.

HTTP Method URI Template
`POST` /session/{session id}/custom-handlers/set-mode

The remote end steps are:

  1. If parameters is not a JSON Object, return a WebDriver error with WebDriver error code invalid argument.

  2. Let mode be the result of getting a property named "mode" from parameters.

  3. If mode is not "autoAccept", "autoReject", or "none", return a WebDriver error with WebDriver error code invalid argument.

  4. Let document be the current browsing context's active document.

  5. Set document's registerProtocolHandler() automation mode to mode.

  6. Return success with data null.

8.9.1.5 Cookies
interface mixin NavigatorCookies {
  readonly attribute boolean cookieEnabled;
};
window.navigator.cookieEnabled

Navigator/cookieEnabled

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Returns false if setting a cookie will be ignored, and true otherwise.

The cookieEnabled attribute must return true if the user agent attempts to handle cookies according to HTTP State Management Mechanism, and false if it ignores cookie change requests. [COOKIES]

8.9.1.6 PDF viewing support
window.navigator.pdfViewerEnabled

Returns true if the user agent supports inline viewing of PDF files when navigating to them, or false otherwise. In the latter case, PDF files will be handled by external software.

interface mixin NavigatorPlugins {
  [SameObject] readonly attribute PluginArray plugins;
  [SameObject] readonly attribute MimeTypeArray mimeTypes;
  boolean javaEnabled();
  readonly attribute boolean pdfViewerEnabled;
};

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface PluginArray {
  undefined refresh();
  readonly attribute unsigned long length;
  getter Plugin? item(unsigned long index);
  getter Plugin? namedItem(DOMString name);
};

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface MimeTypeArray {
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface Plugin {
  readonly attribute DOMString name;
  readonly attribute DOMString description;
  readonly attribute DOMString filename;
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

[Exposed=Window]
interface MimeType {
  readonly attribute DOMString type;
  readonly attribute DOMString description;
  readonly attribute DOMString suffixes;
  readonly attribute Plugin enabledPlugin;
};

Although these days detecting PDF viewer support can be done via navigator.pdfViewerEnabled, for historical reasons, there are a number of complex and intertwined interfaces that provide the same capability, which legacy code relies on. This section specifies both the simple modern variant and the complicated historical one.

Each user agent has a PDF viewer supported boolean, whose value is implementation-defined (and might vary according to user preferences).

This value also impacts the navigation processing model.


Each Window object has a PDF viewer plugin objects list. If the user agent's PDF viewer supported is false, then it is the empty list. Otherwise, it is a list containing five Plugin objects, whose names are, respectively:

  1. "PDF Viewer"
  2. "Chrome PDF Viewer"
  3. "Chromium PDF Viewer"
  4. "Microsoft Edge PDF Viewer"
  5. "WebKit built-in PDF"

The values of the above list form the PDF viewer plugin names list.

These names were chosen based on evidence of what websites historically search for, and thus what is necessary for user agents to expose in order to maintain compatibility with existing content. They are ordered alphabetically. The "PDF Viewer" name was then inserted in the 0th position so that the enabledPlugin getter could point to a generic plugin name.

Each Window object has a PDF viewer mime type objects list. If the user agent's PDF viewer supported is false, then it is the empty list. Otherwise, it is a list containing two MimeType objects, whose types are, respectively:

  1. "application/pdf"
  2. "text/pdf"

The values of the above list form the PDF viewer mime types list.


Each NavigatorPlugins object has a plugins array, which is a new PluginArray, and a mime types array, which is a new MimeTypeArray.

The NavigatorPlugins mixin's plugins getter steps are to return this's plugins array.

The NavigatorPlugins mixin's mimeTypes getter steps are to return this's mime types array.

The NavigatorPlugins mixin's javaEnabled() method steps are to return false.

Navigator/pdfViewerEnabled

Support in all current engines.

Firefox99+Safari16.4+Chrome94+
Opera?Edge94+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The NavigatorPlugins mixin's pdfViewerEnabled getter steps are to return the user agent's PDF viewer supported.


The PluginArray interface supports named properties. If the user agent's PDF viewer supported is true, then they are the PDF viewer plugin names. Otherwise, they are the empty list.

The PluginArray interface's namedItem(name) method steps are:

  1. For each Plugin plugin of this's relevant global object's PDF viewer plugin objects: if plugin's name is name, then return plugin.

  2. Return null.

The PluginArray interface supports indexed properties. The supported property indices are the indices of this's relevant global object's PDF viewer plugin objects.

The PluginArray interface's item(index) method steps are:

  1. Let plugins be this's relevant global object's PDF viewer plugin objects.

  2. If index < plugins's size, then return plugins[index].

  3. Return null.

The PluginArray interface's length getter steps are to return this's relevant global object's PDF viewer plugin objects's size.

The PluginArray interface's refresh() method steps are to do nothing.


The MimeTypeArray interface supports named properties. If the user agent's PDF viewer supported is true, then they are the PDF viewer mime types. Otherwise, they are the empty list.

The MimeTypeArray interface's namedItem(name) method steps are:

  1. For each MimeType mimeType of this's relevant global object's PDF viewer mime type objects: if mimeType's type is name, then return mimeType.

  2. Return null.

The MimeTypeArray interface supports indexed properties. The supported property indices are the indices of this's relevant global object's PDF viewer mime type objects.

The MimeTypeArray interface's item(index) method steps are:

  1. Let mimeTypes be this's relevant global object's PDF viewer mime type objects.

  2. If index < mimeTypes's size, then return mimeTypes[index].

  3. Return null.

The MimeTypeArray interface's length getter steps are to return this's relevant global object's PDF viewer mime type objects's size.


Each Plugin object has a name, which is set when the object is created.

The Plugin interface's name getter steps are to return this's name.

The Plugin interface's description getter steps are to return "Portable Document Format".

The Plugin interface's filename getter steps are to return "internal-pdf-viewer".

The Plugin interface supports named properties. If the user agent's PDF viewer supported is true, then they are the PDF viewer mime types. Otherwise, they are the empty list.

The Plugin interface's namedItem(name) method steps are:

  1. For each MimeType mimeType of this's relevant global object's PDF viewer mime type objects: if mimeType's type is name, then return mimeType.

  2. Return null.

The Plugin interface supports indexed properties. The supported property indices are the indices of this's relevant global object's PDF viewer mime type objects.

The Plugin interface's item(index) method steps are:

  1. Let mimeTypes be this's relevant global object's PDF viewer mime type objects.

  2. If index < mimeType's size, then return mimeTypes[index].

  3. Return null.

The Plugin interface's length getter steps are to return this's relevant global object's PDF viewer mime type objects's size.


Each MimeType object has a type, which is set when the object is created.

The MimeType interface's type getter steps are to return this's type.

The MimeType interface's description getter steps are to return "Portable Document Format".

The MimeType interface's suffixes getter steps are to return "pdf".

The MimeType interface's enabledPlugin getter steps are to return this's relevant global object's PDF viewer plugin objects[0] (i.e., the generic "PDF Viewer" one).

8.10 Images

ImageBitmap

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
[Exposed=(Window,Worker), Serializable, Transferable]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  undefined close();
};

typedef (CanvasImageSource or
         Blob or
         ImageData) ImageBitmapSource;

enum ImageOrientation { "from-image", "flipY" };
enum PremultiplyAlpha { "none", "premultiply", "default" };
enum ColorSpaceConversion { "none", "default" };
enum ResizeQuality { "pixelated", "low", "medium", "high" };

dictionary ImageBitmapOptions {
  ImageOrientation imageOrientation = "from-image";
  PremultiplyAlpha premultiplyAlpha = "default";
  ColorSpaceConversion colorSpaceConversion = "default";
  [EnforceRange] unsigned long resizeWidth;
  [EnforceRange] unsigned long resizeHeight;
  ResizeQuality resizeQuality = "low";
};

An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

promise = self.createImageBitmap(image [, options ])

createImageBitmap

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
promise = self.createImageBitmap(image, sx, sy, sw, sh [, options ])

Takes image, which can be an img element, an SVG image element, a video element, a canvas element, a Blob object, an ImageData object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image's pixel coordinate space, not in CSS pixels.

If options is provided, the ImageBitmap object's bitmap data is modified according to options. For example, if the premultiplyAlpha option is set to "premultiply", the bitmap data's color channels are premultiplied by its alpha channel.

Rejects the promise with an "InvalidStateError" DOMException if the source image is not in a valid state (e.g., an img element that hasn't loaded successfully, an ImageBitmap object whose [[Detached]] internal slot value is true, an ImageData object whose data attribute value's [[ViewedArrayBuffer]] internal slot is detached, or a Blob whose data cannot be interpreted as a bitmap image).

Rejects the promise with a "SecurityError" DOMException if the script is not allowed to access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).

imageBitmap.close()

ImageBitmap/close

Support in all current engines.

Firefox46+Safari15+Chrome52+
Opera37+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android37+

Releases imageBitmap's underlying bitmap data.

imageBitmap.width

ImageBitmap/width

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the natural width of the image, in CSS pixels.

imageBitmap.height

ImageBitmap/height

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the natural height of the image, in CSS pixels.

An ImageBitmap object whose [[Detached]] internal slot value is false always has associated bitmap data, with a width and a height. However, it is possible for this data to be corrupted. If an ImageBitmap object's media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by content from a different origin. The flag is initially set to true and may be changed to false by the steps of createImageBitmap().


ImageBitmap objects are serializable objects and transferable objects.

Their serialization steps, given value and serialized, are:

  1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.

  2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.

Their deserialization steps, given serialized, value, and targetRealm, are:

  1. Set value's bitmap data to serialized.[[BitmapData]].

Their transfer steps, given value and dataHolder, are:

  1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.

  2. Set dataHolder.[[BitmapData]] to value's bitmap data.

  3. Unset value's bitmap data.

Their transfer-receiving steps, given dataHolder and value, are:

  1. Set value's bitmap data to dataHolder.[[BitmapData]].


The createImageBitmap(image, options) and createImageBitmap(image sx, sy, sw, sh, options) methods, when invoked, must run these steps:

  1. If either sw or sh is given and is 0, then return a promise rejected with a RangeError.

  2. If either options's resizeWidth or options's resizeHeight is present and is 0, then return a promise rejected with an "InvalidStateError" DOMException.

  3. Check the usability of the image argument. If this throws an exception or returns bad, then return a promise rejected with an "InvalidStateError" DOMException.

  4. Let p be a new promise.

  5. Let imageBitmap be a new ImageBitmap object.

  6. Switch on image:

    img
    SVG image
    1. If image's media data has no natural dimensions (e.g., it's a vector graphic with no specified content size) and either options's resizeWidth or options's resizeHeight is not present, then return a promise rejected with an "InvalidStateError" DOMException.

    2. If image's media data has no natural dimensions (e.g., it's a vector graphic with no specified content size), it should be rendered to a bitmap of the size specified by the resizeWidth and the resizeHeight options.

    3. Set imageBitmap's bitmap data to a copy of image's media data, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

    4. If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.

    5. Run this step in parallel:

      1. Resolve p with imageBitmap.

    video
    1. If image's networkState attribute is NETWORK_EMPTY, then return a promise rejected with an "InvalidStateError" DOMException.

    2. Set imageBitmap's bitmap data to a copy of the frame at the current playback position, at the media resource's natural width and natural height (i.e., after any aspect-ratio correction has been applied), cropped to the source rectangle with formatting.

    3. If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.

    4. Run this step in parallel:

      1. Resolve p with imageBitmap.

    canvas
    1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.

    2. Set the origin-clean flag of the imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.

    3. Run this step in parallel:

      1. Resolve p with imageBitmap.

    Blob

    Run these steps in parallel:

    1. Let imageData be the result of reading image's data. If an error occurs during reading of the object, then reject p with an "InvalidStateError" DOMException and abort these steps.

    2. Apply the image sniffing rules to determine the file format of imageData, with MIME type of image (as given by image's type attribute) giving the official type.

    3. If imageData is not in a supported image file format (e.g., it's not an image at all), or if imageData is corrupted in some fatal way such that the image dimensions cannot be obtained (e.g., a vector graphic with no natural size), then reject p with an "InvalidStateError" DOMException and abort these steps.

    4. Set imageBitmap's bitmap data to imageData, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

    5. Resolve p with imageBitmap.

    ImageData
    1. Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot.

    2. If IsDetachedBuffer(buffer) is true, then return a promise rejected with an "InvalidStateError" DOMException.

    3. Set imageBitmap's bitmap data to image's image data, cropped to the source rectangle with formatting.

    4. Run this step in parallel:

      1. Resolve p with imageBitmap.

    ImageBitmap
    1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.

    2. Set the origin-clean flag of imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.

    3. Run this step in parallel:

      1. Resolve p with imageBitmap.

    VideoFrame
    1. Set imageBitmap's bitmap data to a copy of image's visible pixel data, cropped to the source rectangle with formatting.

    2. Run this step in parallel:

      1. Resolve p with imageBitmap.

  7. Return p.

When the steps above require that the user agent crop bitmap data to the source rectangle with formatting, the user agent must run the following steps:

  1. Let input be the bitmap data being transformed.

  2. If sx, sy, sw and sh are specified, let sourceRectangle be a rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh). Otherwise, let sourceRectangle be a rectangle whose corners are the four points (0, 0), (width of input, 0), (width of input, height of input), (0, height of input).

    If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point.

  3. Let outputWidth be determined as follows:

    If the resizeWidth member of options is specified
    the value of the resizeWidth member of options
    If the resizeWidth member of options is not specified, but the resizeHeight member is specified
    the width of sourceRectangle, times the value of the resizeHeight member of options, divided by the height of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the width of sourceRectangle
  4. Let outputHeight be determined as follows:

    If the resizeHeight member of options is specified
    the value of the resizeHeight member of options
    If the resizeHeight member of options is not specified, but the resizeWidth member is specified
    the height of sourceRectangle, times the value of the resizeWidth member of options, divided by the width of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the height of sourceRectangle
  5. Place input on an infinite transparent black grid plane, positioned so that its top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane's grid.

  6. Let output be the rectangle on the plane denoted by sourceRectangle.

  7. Scale output to the size specified by outputWidth and outputHeight. The user agent should use the value of the resizeQuality option to guide the choice of scaling algorithm.

  8. If the value of the imageOrientation member of options is "flipY", output must be flipped vertically, disregarding any image orientation metadata of the source (such as EXIF metadata), if any. [EXIF]

    If the value is "from-image", no extra step is needed.

    There used to be a "none" enum value. It was renamed to "from-image". In the future, "none" will be added back with a different meaning.

  9. If image is an img element or a Blob object, let val be the value of the colorSpaceConversion member of options, and then run these substeps:

    1. If val is "default", the color space conversion behavior is implementation-specific, and should be chosen according to the default color space that the implementation uses for drawing images onto the canvas.

    2. If val is "none", output must be decoded without performing any color space conversions. This means that the image decoding algorithm must ignore color profile metadata embedded in the source data as well as the display device color profile.

  10. Let val be the value of premultiplyAlpha member of options, and then run these substeps:

    1. If val is "default", the alpha premultiplication behavior is implementation-specific, and should be chosen according to implementation deems optimal for drawing images onto the canvas.

    2. If val is "premultiply", the output that is not premultiplied by alpha must have its color components multiplied by alpha and that is premultiplied by alpha must be left untouched.

    3. If val is "none", the output that is not premultiplied by alpha must be left untouched and that is premultiplied by alpha must have its color components divided by alpha.

  11. Return output.

The close() method steps are:

  1. Set this's [[Detached]] internal slot value to true.

  2. Unset this's bitmap data.

The width getter steps are:

  1. If this's [[Detached]] internal slot's value is true, then return 0.

  2. Return this's width, in CSS pixels.

The height getter steps are:

  1. If this's [[Detached]] internal slot's value is true, then return 0.

  2. Return this's height, in CSS pixels.

The ResizeQuality enumeration is used to express a preference for the interpolation quality to use when scaling images.

The "pixelated" value indicates a preference for scaling the image to preserve the pixelation of the original as much as possible, with minor smoothing as necessary to avoid distorting the image when the target size is not a clean multiple of the original.

To implement "pixelated", for each axis independently, first determine the integer multiple of its natural size that puts it closest to the target size and is greater than zero. Scale it to this integer-multiple-size using nearest neighbor, then scale it the rest of the way to the target size using bilinear interpolation.

The "low" value indicates a preference for a low level of image interpolation quality. Low-quality image interpolation may be more computationally efficient than higher settings.

The "medium" value indicates a preference for a medium level of image interpolation quality.

The "high" value indicates a preference for a high level of image interpolation quality. High-quality image interpolation may be more computationally expensive than lower settings.

Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-scaling algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used, except for "pixelated" as described above.

Using this API, a sprite sheet can be precut and prepared:

var sprites = {};
function loadMySprites() {
  var image = new Image();
  image.src = 'mysprites.png';
  var resolver;
  var promise = new Promise(function (arg) { resolver = arg });
  image.onload = function () {
    resolver(Promise.all([
      createImageBitmap(image,  0,  0, 40, 40).then(function (image) { sprites.person = image }),
      createImageBitmap(image, 40,  0, 40, 40).then(function (image) { sprites.grass  = image }),
      createImageBitmap(image, 80,  0, 40, 40).then(function (image) { sprites.tree   = image }),
      createImageBitmap(image,  0, 40, 40, 40).then(function (image) { sprites.hut    = image }),
      createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple  = image }),
      createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake  = image })
    ]));
  };
  return promise;
}

function runDemo() {
  var canvas = document.querySelector('canvas#demo');
  var context = canvas.getContext('2d');
  context.drawImage(sprites.tree, 30, 10);
  context.drawImage(sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

8.11 Animation frames

Some objects include the AnimationFrameProvider interface mixin.

callback FrameRequestCallback = undefined (DOMHighResTimeStamp time);

interface mixin AnimationFrameProvider {
  unsigned long requestAnimationFrame(FrameRequestCallback callback);
  undefined cancelAnimationFrame(unsigned long handle);
};
Window includes AnimationFrameProvider;
DedicatedWorkerGlobalScope includes AnimationFrameProvider;

Each AnimationFrameProvider object also has a target object that stores the provider's internal state. It is defined as follows:

If the AnimationFrameProvider is a Window
The Window's associated Document
If the AnimationFrameProvider is a DedicatedWorkerGlobalScope
The DedicatedWorkerGlobalScope

Each target object has a map of animation frame callbacks, which is an ordered map that must be initially empty, and an animation frame callback identifier, which is a number that must initially be zero.

An AnimationFrameProvider provider is considered supported if any of the following are true:


Window/requestAnimationFrame

Support in all current engines.

Firefox23+Safari7+Chrome24+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android23+Safari iOS?Chrome Android?WebView Android4.4+Samsung Internet?Opera Android?

The requestAnimationFrame(callback) method steps are:

  1. If this is not supported, then throw a "NotSupportedError" DOMException.

  2. Let target be this's target object.

  3. Increment target's animation frame callback identifier by one, and let handle be the result.

  4. Let callbacks be target's map of animation frame callbacks.

  5. Set callbacks[handle] to callback.

  6. Return handle.

Window/cancelAnimationFrame

Support in all current engines.

Firefox23+Safari7+Chrome24+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The cancelAnimationFrame(handle) method steps are:

  1. If this is not supported, then throw a "NotSupportedError" DOMException.

  2. Let callbacks be this's target object's map of animation frame callbacks.

  3. Remove callbacks[handle].

To run the animation frame callbacks for a target object target with a timestamp now:

  1. Let callbacks be target's map of animation frame callbacks.

  2. Let callbackHandles be the result of getting the keys of callbacks.

  3. For each handle in callbackHandles, if handle exists in callbacks:

    1. Let callback be callbacks[handle].

    2. Remove callbacks[handle].

    3. Invoke callback with « now » and "report".

Inside workers, requestAnimationFrame() can be used together with an OffscreenCanvas transferred from a canvas element. First, in the document, transfer control to the worker:

const offscreenCanvas = document.getElementById("c").transferControlToOffscreen();
worker.postMessage(offscreenCanvas, [offscreenCanvas]);

Then, in the worker, the following code will draw a rectangle moving from left to right:

let ctx, pos = 0;
function draw(dt) {
  ctx.clearRect(0, 0, 100, 100);
  ctx.fillRect(pos, 0, 10, 10);
  pos += 10 * dt;
  requestAnimationFrame(draw);
}

self.onmessage = function(ev) {
  const transferredCanvas = ev.data;
  ctx = transferredCanvas.getContext("2d");
  draw();
};

9 Communication

The WebSocket interface used to be defined here. It is now defined in WebSockets. [WEBSOCKETS]

9.1 The MessageEvent interface

MessageEvent

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Messages in server-sent events, cross-document messaging, channel messaging, broadcast channels, and WebSockets use the MessageEvent interface for their message events: [WEBSOCKETS]

[Exposed=(Window,Worker,AudioWorklet)]
interface MessageEvent : Event {
  constructor(DOMString type, optional MessageEventInit eventInitDict = {});

  readonly attribute any data;
  readonly attribute USVString origin;
  readonly attribute DOMString lastEventId;
  readonly attribute MessageEventSource? source;
  readonly attribute FrozenArray<MessagePort> ports;

  undefined initMessageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any data = null, optional USVString origin = "", optional DOMString lastEventId = "", optional MessageEventSource? source = null, optional sequence<MessagePort> ports = []);
};

dictionary MessageEventInit : EventInit {
  any data = null;
  USVString origin = "";
  DOMString lastEventId = "";
  MessageEventSource? source = null;
  sequence<MessagePort> ports = [];
};

typedef (WindowProxy or MessagePort or ServiceWorker) MessageEventSource;
event.data

MessageEvent/data

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Returns the data of the message.

event.origin

MessageEvent/origin

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Returns the origin of the message, for server-sent events and cross-document messaging.

event.lastEventId

MessageEvent/lastEventId

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)17+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Returns the last event ID string, for server-sent events.

event.source

MessageEvent/source

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects.

event.ports

MessageEvent/ports

Support in all current engines.

Firefox3+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+

Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.

The data attribute must return the value it was initialized to. It represents the message being sent.

The origin attribute must return the value it was initialized to. It represents, in server-sent events and cross-document messaging, the origin of the document that sent the message (typically the scheme, hostname, and port of the document, but not its path or fragment).

The lastEventId attribute must return the value it was initialized to. It represents, in server-sent events, the last event ID string of the event source.

The source attribute must return the value it was initialized to. It represents, in cross-document messaging, the WindowProxy of the browsing context of the Window object from which the message came; and in the connect events used by shared workers, the newly connecting MessagePort.

The ports attribute must return the value it was initialized to. It represents, in cross-document messaging and channel messaging, the MessagePort array being sent.

The initMessageEvent(type, bubbles, cancelable, data, origin, lastEventId, source, ports) method must initialize the event in a manner analogous to the similarly-named initEvent() method. [DOM]

Various APIs (e.g., WebSocket, EventSource) use the MessageEvent interface for their message event without using the MessagePort API.

9.2 Server-sent events

Server-sent_events

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera11+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

9.2.1 Introduction

This section is non-normative.

To enable servers to push data to web pages over HTTP or using dedicated server-push protocols, this specification introduces the EventSource interface.

Using this API consists of creating an EventSource object and registering an event listener.

var source = new EventSource('updates.cgi');
source.onmessage = function (event) {
  alert(event.data);
};

On the server-side, the script ("updates.cgi" in this case) sends messages in the following form, with the text/event-stream MIME type:

data: This is the first message.

data: This is the second message, it
data: has two lines.

data: This is the third message.

Authors can separate events by using different event types. Here is a stream that has two event types, "add" and "remove":

event: add
data: 73857293

event: remove
data: 2153

event: add
data: 113411

The script to handle such a stream would look like this (where addHandler and removeHandler are functions that take one argument, the event):

var source = new EventSource('updates.cgi');
source.addEventListener('add', addHandler, false);
source.addEventListener('remove', removeHandler, false);

The default event type is "message".

Event streams are always decoded as UTF-8. There is no way to specify another character encoding.


Event stream requests can be redirected using HTTP 301 and 307 redirects as with normal HTTP requests. Clients will reconnect if the connection is closed; a client can be told to stop reconnecting using the HTTP 204 No Content response code.

Using this API rather than emulating it using XMLHttpRequest or an iframe allows the user agent to make better use of network resources in cases where the user agent implementer and the network operator are able to coordinate in advance. Amongst other benefits, this can result in significant savings in battery life on portable devices. This is discussed further in the section below on connectionless push.

9.2.2 The EventSource interface

EventSource

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera11+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Exposed=(Window,Worker)]
interface EventSource : EventTarget {
  constructor(USVString url, optional EventSourceInit eventSourceInitDict = {});

  readonly attribute USVString url;
  readonly attribute boolean withCredentials;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSED = 2;
  readonly attribute unsigned short readyState;

  // networking
  attribute EventHandler onopen;
  attribute EventHandler onmessage;
  attribute EventHandler onerror;
  undefined close();
};

dictionary EventSourceInit {
  boolean withCredentials = false;
};

Each EventSource object has the following associated with it:

Apart from url these are not currently exposed on the EventSource object.

source = new EventSource( url [, { withCredentials: true } ])

EventSource/EventSource

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera11+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Creates a new EventSource object.

url is a string giving the URL that will provide the event stream.

Setting withCredentials to true will set the credentials mode for connection requests to url to "include".

source.close()

EventSource/close

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.

source.url

EventSource/url

Support in all current engines.

Firefox6+Safari6+Chrome18+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Returns the URL providing the event stream.

source.withCredentials

EventSource/withCredentials

Support in all current engines.

Firefox6+Safari7+Chrome26+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.

source.readyState

EventSource/readyState

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Returns the state of this EventSource object's connection. It can have the values described below.

The EventSource(url, eventSourceInitDict) constructor, when invoked, must run these steps:

  1. Let ev be a new EventSource object.

  2. Let settings be ev's relevant settings object.

  3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.

  4. If urlRecord is failure, then throw a "SyntaxError" DOMException.

  5. Set ev's url to urlRecord.

  6. Let corsAttributeState be Anonymous.

  7. If the value of eventSourceInitDict's withCredentials member is true, then set corsAttributeState to Use Credentials and set ev's withCredentials attribute to true.

  8. Let request be the result of creating a potential-CORS request given urlRecord, the empty string, and corsAttributeState.

  9. Set request's client to settings.

  10. User agents may set (`Accept`, `text/event-stream`) in request's header list.

  11. Set request's cache mode to "no-store".

  12. Set request's initiator type to "other".

  13. Set ev's request to request.

  14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.

  15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody and processResponse set to the following steps given response res:

    1. If res is an aborted network error, then fail the connection.

    2. Otherwise, if res is a network error, then reestablish the connection, unless the user agent knows that to be futile, in which case the user agent may fail the connection.

    3. Otherwise, if res's status is not 200, or if res's `Content-Type` is not `text/event-stream`, then fail the connection.

    4. Otherwise, announce the connection and interpret res's body line by line.

  16. Return ev.


The url attribute's getter must return the serialization of this EventSource object's url.

The withCredentials attribute must return the value to which it was last initialized. When the object is created, it must be initialized to false.

The readyState attribute represents the state of the connection. It can have the following values:

CONNECTING (numeric value 0)
The connection has not yet been established, or it was closed and the user agent is reconnecting.
OPEN (numeric value 1)
The user agent has an open connection and is dispatching events as it receives them.
CLOSED (numeric value 2)
The connection is not open, and the user agent is not trying to reconnect. Either there was a fatal error or the close() method was invoked.

When the object is created its readyState must be set to CONNECTING (0). The rules given below for handling the connection define when the value changes.

The close() method must abort any instances of the fetch algorithm started for this EventSource object, and must set the readyState attribute to CLOSED.

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the EventSource interface:

Event handler Event handler event type
onopen

EventSource/open_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
open
onmessage

EventSource/message_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
message
onerror

EventSource/error_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
error

9.2.3 Processing model

When a user agent is to announce the connection, the user agent must queue a task which, if the readyState attribute is set to a value other than CLOSED, sets the readyState attribute to OPEN and fires an event named open at the EventSource object.

When a user agent is to reestablish the connection, the user agent must run the following steps. These steps are run in parallel, not as part of a task. (The tasks that it queues, of course, are run like normal tasks and not themselves in parallel.)

  1. Queue a task to run the following steps:

    1. If the readyState attribute is set to CLOSED, abort the task.

    2. Set the readyState attribute to CONNECTING.

    3. Fire an event named error at the EventSource object.

  2. Wait a delay equal to the reconnection time of the event source.

  3. Optionally, wait some more. In particular, if the previous attempt failed, then user agents might introduce an exponential backoff delay to avoid overloading a potentially already overloaded server. Alternatively, if the operating system has reported that there is no network connectivity, user agents might wait for the operating system to announce that the network connection has returned before retrying.

  4. Wait until the aforementioned task has run, if it has not yet run.

  5. Queue a task to run the following steps:

    1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.

    2. Let request be the EventSource object's request.

    3. If the EventSource object's last event ID string is not the empty string, then:

      1. Let lastEventIDValue be the EventSource object's last event ID string, encoded as UTF-8.

      2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.

    4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.

When a user agent is to fail the connection, the user agent must queue a task which, if the readyState attribute is set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires an event named error at the EventSource object. Once the user agent has failed the connection, it does not attempt to reconnect.


The task source for any tasks that are queued by EventSource objects is the remote event task source.

9.2.4 The `Last-Event-ID` header

The Last-Event-ID` HTTP request header reports an EventSource object's last event ID string to the server when the user agent is to reestablish the connection.

See whatwg/html issue #7363 to define the value space better. It is essentially any UTF-8 encoded string, that does not contain U+0000 NULL, U+000A LF, or U+000D CR.

9.2.5 Parsing an event stream

This event stream format's MIME type is text/event-stream.

The event stream format is as described by the stream production of the following ABNF, the character set for which is Unicode. [ABNF]

stream        = [ bom ] *event
event         = *( comment / field ) end-of-line
comment       = colon *any-char end-of-line
field         = 1*name-char [ colon [ space ] *any-char ] end-of-line
end-of-line   = ( cr lf / cr / lf )

; characters
lf            = %x000A ; U+000A LINE FEED (LF)
cr            = %x000D ; U+000D CARRIAGE RETURN (CR)
space         = %x0020 ; U+0020 SPACE
colon         = %x003A ; U+003A COLON (:)
bom           = %xFEFF ; U+FEFF BYTE ORDER MARK
name-char     = %x0000-0009 / %x000B-000C / %x000E-0039 / %x003B-10FFFF
                ; a scalar value other than U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), or U+003A COLON (:)
any-char      = %x0000-0009 / %x000B-000C / %x000E-10FFFF
                ; a scalar value other than U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR)

Event streams in this format must always be encoded as UTF-8. [ENCODING]

Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character, or a single U+000D CARRIAGE RETURN (CR) character.

Since connections established to remote servers for such resources are expected to be long-lived, UAs should ensure that appropriate buffering is used. In particular, while line buffering with lines are defined to end with a single U+000A LINE FEED (LF) character is safe, block buffering or line buffering with different expected line endings can cause delays in event dispatch.

9.2.6 Interpreting an event stream

Streams must be decoded using the UTF-8 decode algorithm.

The UTF-8 decode algorithm strips one leading UTF-8 Byte Order Mark (BOM), if any.

The stream must then be parsed by reading everything line by line, with a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character not preceded by a U+000D CARRIAGE RETURN (CR) character, and a single U+000D CARRIAGE RETURN (CR) character not followed by a U+000A LINE FEED (LF) character being the ways in which a line can end.

When a stream is parsed, a data buffer, an event type buffer, and a last event ID buffer must be associated with it. They must be initialized to the empty string.

Lines must be processed, in the order they are received, as follows:

If the line is empty (a blank line)

Dispatch the event, as defined below.

If the line starts with a U+003A COLON character (:)

Ignore the line.

If the line contains a U+003A COLON character (:)

Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.

Collect the characters on the line after the first U+003A COLON character (:), and let value be that string. If value starts with a U+0020 SPACE character, remove it from value.

Process the field using the steps described below, using field as the field name and value as the field value.

Otherwise, the string is not empty but does not contain a U+003A COLON character (:)

Process the field using the steps described below, using the whole line as the field name, and the empty string as the field value.

Once the end of the file is reached, any pending data must be discarded. (If the file ends in the middle of an event, before the final empty line, the incomplete event is not dispatched.)


The steps to process the field given a field name and a field value depend on the field name, as given in the following list. Field names must be compared literally, with no case folding performed.

If the field name is "event"

Set the event type buffer to field value.

If the field name is "data"

Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.

If the field name is "id"

If the field value does not contain U+0000 NULL, then set the last event ID buffer to the field value. Otherwise, ignore the field.

If the field name is "retry"

If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. Otherwise, ignore the field.

Otherwise

The field is ignored.

When the user agent is required to dispatch the event, the user agent must process the data buffer, the event type buffer, and the last event ID buffer using steps appropriate for the user agent.

For web browsers, the appropriate steps to dispatch the event are as follows:

  1. Set the last event ID string of the event source to the value of the last event ID buffer. The buffer does not get reset, so the last event ID string of the event source remains set to this value until the next time it is set by the server.

  2. If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and return.

  3. If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.

  4. Let event be the result of creating an event using MessageEvent, in the relevant realm of the EventSource object.

  5. Initialize event's type attribute to "message", its data attribute to data, its origin attribute to the serialization of the origin of the event stream's final URL (i.e., the URL after redirects), and its lastEventId attribute to the last event ID string of the event source.

  6. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal the value of the event type buffer.

  7. Set the data buffer and the event type buffer to the empty string.

  8. Queue a task which, if the readyState attribute is set to a value other than CLOSED, dispatches the newly created event at the EventSource object.

If an event doesn't have an "id" field, but an earlier event did set the event source's last event ID string, then the event's lastEventId field will be set to the value of whatever the last seen "id" field was.

For other user agents, the appropriate steps to dispatch the event are implementation dependent, but at a minimum they must set the data and event type buffers to the empty string before returning.

The following event stream, once followed by a blank line:

data: YHOO
data: +2
data: 10

...would cause an event message with the interface MessageEvent to be dispatched on the EventSource object. The event's data attribute would contain the string "YHOO\n+2\n10" (where "\n" represents a newline).

This could be used as follows:

var stocks = new EventSource("https://stocks.example.com/ticker.php");
stocks.onmessage = function (event) {
  var data = event.data.split('\n');
  updateStocks(data[0], data[1], data[2]);
};

...where updateStocks() is a function defined as:

function updateStocks(symbol, delta, value) { ... }

...or some such.

The following stream contains four blocks. The first block has just a comment, and will fire nothing. The second block has two fields with names "data" and "id" respectively; an event will be fired for this block, with the data "first event", and will then set the last event ID to "1" so that if the connection died between this block and the next, the server would be sent a `Last-Event-ID` header with the value `1`. The third block fires an event with data "second event", and also has an "id" field, this time with no value, which resets the last event ID to the empty string (meaning no `Last-Event-ID` header will now be sent in the event of a reconnection being attempted). Finally, the last block just fires an event with the data " third event" (with a single leading space character). Note that the last still has to end with a blank line, the end of the stream is not enough to trigger the dispatch of the last event.

: test stream

data: first event
id: 1

data:second event
id

data:  third event

The following stream fires two events:

data

data
data

data:

The first block fires events with the data set to the empty string, as would the last block if it was followed by a blank line. The middle block fires an event with the data set to a single newline character. The last block is discarded because it is not followed by a blank line.

The following stream fires two identical events:

data:test

data: test

This is because the space after the colon is ignored if present.

9.2.7 Authoring notes

Legacy proxy servers are known to, in certain cases, drop HTTP connections after a short timeout. To protect against such proxy servers, authors can include a comment line (one starting with a ':' character) every 15 seconds or so.

Authors wishing to relate event source connections to each other or to specific documents previously served might find that relying on IP addresses doesn't work, as individual clients can have multiple IP addresses (due to having multiple proxy servers) and individual IP addresses can have multiple clients (due to sharing a proxy server). It is better to include a unique identifier in the document when it is served and then pass that identifier as part of the URL when the connection is established.

Authors are also cautioned that HTTP chunking can have unexpected negative effects on the reliability of this protocol, in particular if the chunking is done by a different layer unaware of the timing requirements. If this is a problem, chunking can be disabled for serving event streams.

Clients that support HTTP's per-server connection limitation might run into trouble when opening multiple pages from a site if each page has an EventSource to the same domain. Authors can avoid this using the relatively complex mechanism of using unique domain names per connection, or by allowing the user to enable or disable the EventSource functionality on a per-page basis, or by sharing a single EventSource object using a shared worker.

9.2.8 Connectionless push and other features

User agents running in controlled environments, e.g. browsers on mobile handsets tied to specific carriers, may offload the management of the connection to a proxy on the network. In such a situation, the user agent for the purposes of conformance is considered to include both the handset software and the network proxy.

For example, a browser on a mobile device, after having established a connection, might detect that it is on a supporting network and request that a proxy server on the network take over the management of the connection. The timeline for such a situation might be as follows:

  1. Browser connects to a remote HTTP server and requests the resource specified by the author in the EventSource constructor.
  2. The server sends occasional messages.
  3. In between two messages, the browser detects that it is idle except for the network activity involved in keeping the TCP connection alive, and decides to switch to sleep mode to save power.
  4. The browser disconnects from the server.
  5. The browser contacts a service on the network, and requests that the service, a "push proxy", maintain the connection instead.
  6. The "push proxy" service contacts the remote HTTP server and requests the resource specified by the author in the EventSource constructor (possibly including a `Last-Event-ID` HTTP header, etc.).
  7. The browser allows the mobile device to go to sleep.
  8. The server sends another message.
  9. The "push proxy" service uses a technology such as OMA push to convey the event to the mobile device, which wakes only enough to process the event and then returns to sleep.

This can reduce the total data usage, and can therefore result in considerable power savings.

As well as implementing the existing API and text/event-stream wire format as defined by this specification and in more distributed ways as described above, formats of event framing defined by other applicable specifications may be supported. This specification does not define how they are to be parsed or processed.

9.2.9 Garbage collection

While an EventSource object's readyState is CONNECTING, and the object has one or more event listeners registered for open, message or error events, there must be a strong reference from the Window or WorkerGlobalScope object that the EventSource object's constructor was invoked from to the EventSource object itself.

While an EventSource object's readyState is OPEN, and the object has one or more event listeners registered for message or error events, there must be a strong reference from the Window or WorkerGlobalScope object that the EventSource object's constructor was invoked from to the EventSource object itself.

While there is a task queued by an EventSource object on the remote event task source, there must be a strong reference from the Window or WorkerGlobalScope object that the EventSource object's constructor was invoked from to that EventSource object.

If a user agent is to forcibly close an EventSource object (this happens when a Document object goes away permanently), the user agent must abort any instances of the fetch algorithm started for this EventSource object, and must set the readyState attribute to CLOSED.

If an EventSource object is garbage collected while its connection is still open, the user agent must abort any instance of the fetch algorithm opened by this EventSource.

9.2.10 Implementation advice

This section is non-normative.

User agents are strongly urged to provide detailed diagnostic information about EventSource objects and their related network connections in their development consoles, to aid authors in debugging code using this API.

For example, a user agent could have a panel displaying all the EventSource objects a page has created, each listing the constructor's arguments, whether there was a network error, what the CORS status of the connection is and what headers were sent by the client and received from the server to lead to that status, the messages that were received and how they were parsed, and so forth.

Implementations are especially encouraged to report detailed information to their development consoles whenever an error event is fired, since little to no information can be made available in the events themselves.

9.3 Cross-document messaging

Window/postMessage

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android≤37+Samsung Internet?Opera Android10.1+

Web browsers, for security and privacy reasons, prevent documents in different domains from affecting each other; that is, cross-site scripting is disallowed.

While this is an important security feature, it prevents pages from different domains from communicating even when those pages are not hostile. This section introduces a messaging system that allows documents to communicate with each other regardless of their source domain, in a way designed to not enable cross-site scripting attacks.

The postMessage() API can be used as a tracking vector.

9.3.1 Introduction

This section is non-normative.

For example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might look like:

var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello world', 'https://b.example.org/');

To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B might look like:

window.addEventListener('message', receiver, false);
function receiver(e) {
  if (e.origin == 'https://example.com') {
    if (e.data == 'Hello world') {
      e.source.postMessage('Hello', e.origin);
    } else {
      alert(e.data);
    }
  }
}

This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place.

9.3.2 Security

9.3.2.1 Authors

Use of this API requires extra care to protect users from hostile entities abusing a site for their own purposes.

Authors should check the origin attribute to ensure that messages are only accepted from domains that they expect to receive messages from. Otherwise, bugs in the author's message handling code could be exploited by hostile sites.

Furthermore, even after checking the origin attribute, authors should also check that the data in question is of the expected format. Otherwise, if the source of the event has been attacked using a cross-site scripting flaw, further unchecked processing of information sent using the postMessage() method could result in the attack being propagated into the receiver.

Authors should not use the wildcard keyword (*) in the targetOrigin argument in messages that contain any confidential information, as otherwise there is no way to guarantee that the message is only delivered to the recipient to which it was intended.


Authors who accept messages from any origin are encouraged to consider the risks of a denial-of-service attack. An attacker could send a high volume of messages; if the receiving page performs expensive computation or causes network traffic to be sent for each such message, the attacker's message could be multiplied into a denial-of-service attack. Authors are encouraged to employ rate limiting (only accepting a certain number of messages per minute) to make such attacks impractical.

9.3.2.2 User agents

The integrity of this API is based on the inability for scripts of one origin to post arbitrary events (using dispatchEvent() or otherwise) to objects in other origins (those that are not the same).

Implementers are urged to take extra care in the implementation of this feature. It allows authors to transmit information from one domain to another domain, which is normally disallowed for security reasons. It also requires that UAs be careful to allow access to certain properties but not others.


User agents are also encouraged to consider rate-limiting message traffic between different origins, to protect naïve sites from denial-of-service attacks.

9.3.3 Posting messages

window.postMessage(message [, options ])

Window/postMessage

Support in all current engines.

Firefox3+Safari4+Chrome2+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Posts a message to the given window. Messages can be structured objects, e.g. nested objects and arrays, can contain JavaScript values (strings, numbers, Date objects, etc.), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.

Objects listed in the transfer member of options are transferred, not just cloned, meaning that they are no longer usable on the sending side.

A target origin can be specified using the targetOrigin member of options. If not provided, it defaults to "/". This default restricts the message to same-origin targets only.

If the origin of the target window doesn't match the given target origin, the message is discarded, to avoid information leakage. To send the message to the target regardless of origin, set the target origin to "*".

Throws a "DataCloneError" DOMException if transfer array contains duplicate objects or if message could not be cloned.

window.postMessage(message, targetOrigin [, transfer ])

This is an alternate version of postMessage() where the target origin is specified as a parameter. Calling window.postMessage(message, target, transfer) is equivalent to window.postMessage(message, {targetOrigin, transfer}).

When posting a message to a Window of a browsing context that has just been navigated to a new Document is likely to result in the message not receiving its intended recipient: the scripts in the target browsing context have to have had time to set up listeners for the messages. Thus, for instance, in situations where a message is to be sent to the Window of newly created child iframe, authors are advised to have the child Document post a message to their parent announcing their readiness to receive messages, and for the parent to wait for this message before beginning posting messages.

The window post message steps, given a targetWindow, message, and options, are as follows:

  1. Let targetRealm be targetWindow's realm.

  2. Let incumbentSettings be the incumbent settings object.

  3. Let targetOrigin be options["targetOrigin"].

  4. If targetOrigin is a single U+002F SOLIDUS character (/), then set targetOrigin to incumbentSettings's origin.

  5. Otherwise, if targetOrigin is not a single U+002A ASTERISK character (*), then:

    1. Let parsedURL be the result of running the URL parser on targetOrigin.

    2. If parsedURL is failure, then throw a "SyntaxError" DOMException.

    3. Set targetOrigin to parsedURL's origin.

  6. Let transfer be options["transfer"].

  7. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.

  8. Queue a global task on the posted message task source given targetWindow to run the following steps:

    1. If the targetOrigin argument is not a single literal U+002A ASTERISK character (*) and targetWindow's associated Document's origin is not same origin with targetOrigin, then return.

    2. Let origin be the serialization of incumbentSettings's origin.

    3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).

    4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).

      If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent, with the origin attribute initialized to origin and the source attribute initialized to source, and then return.

    5. Let messageClone be deserializeRecord.[[Deserialized]].

    6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.

    7. Fire an event named message at targetWindow, using MessageEvent, with the origin attribute initialized to origin, the source attribute initialized to source, the data attribute initialized to messageClone, and the ports attribute initialized to newPorts.

The Window interface's postMessage(message, options) method steps are to run the window post message steps given this, message, and options.

The Window interface's postMessage(message, targetOrigin, transfer) method steps are to run the window post message steps given this, message, and «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]».

9.4 Channel messaging

Channel_Messaging_API

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Channel_Messaging_API/Using_channel_messaging

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

9.4.1 Introduction

This section is non-normative.

To enable independent pieces of code (e.g. running in different browsing contexts) to communicate directly, authors can use channel messaging.

Communication channels in this mechanism are implemented as two-ways pipes, with a port at each end. Messages sent in one port are delivered at the other port, and vice-versa. Messages are delivered as DOM events, without interrupting or blocking running tasks.

To create a connection (two "entangled" ports), the MessageChannel() constructor is called:

var channel = new MessageChannel();

One of the ports is kept as the local port, and the other port is sent to the remote code, e.g. using postMessage():

otherWindow.postMessage('hello', 'https://example.com', [channel.port2]);

To send messages, the postMessage() method on the port is used:

channel.port1.postMessage('hello');

To receive messages, one listens to message events:

channel.port1.onmessage = handleMessage;
function handleMessage(event) {
  // message is in event.data
  // ...
}

Data sent on a port can be structured data; for example here an array of strings is passed on a MessagePort:

port1.postMessage(['hello', 'world']);
9.4.1.1 Examples

This section is non-normative.

In this example, two JavaScript libraries are connected to each other using MessagePorts. This allows the libraries to later be hosted in different frames, or in Worker objects, without any change to the APIs.

<script src="contacts.js"></script> <!-- exposes a contacts object -->
<script src="compose-mail.js"></script> <!-- exposes a composer object -->
<script>
 var channel = new MessageChannel();
 composer.addContactsProvider(channel.port1);
 contacts.registerConsumer(channel.port2);
</script>

Here's what the "addContactsProvider()" function's implementation could look like:

function addContactsProvider(port) {
  port.onmessage = function (event) {
    switch (event.data.messageType) {
      case 'search-result': handleSearchResult(event.data.results); break;
      case 'search-done': handleSearchDone(); break;
      case 'search-error': handleSearchError(event.data.message); break;
      // ...
    }
  };
};

Alternatively, it could be implemented as follows:

function addContactsProvider(port) {
  port.addEventListener('message', function (event) {
    if (event.data.messageType == 'search-result')
      handleSearchResult(event.data.results);
  });
  port.addEventListener('message', function (event) {
    if (event.data.messageType == 'search-done')
      handleSearchDone();
  });
  port.addEventListener('message', function (event) {
    if (event.data.messageType == 'search-error')
      handleSearchError(event.data.message);
  });
  // ...
  port.start();
};

The key difference is that when using addEventListener(), the start() method must also be invoked. When using onmessage, the call to start() is implied.

The start() method, whether called explicitly or implicitly (by setting onmessage), starts the flow of messages: messages posted on message ports are initially paused, so that they don't get dropped on the floor before the script has had a chance to set up its handlers.

9.4.1.2 Ports as the basis of an object-capability model on the web

This section is non-normative.

Ports can be viewed as a way to expose limited capabilities (in the object-capability model sense) to other actors in the system. This can either be a weak capability system, where the ports are merely used as a convenient model within a particular origin, or as a strong capability model, where they are provided by one origin provider as the only mechanism by which another origin consumer can effect change in or obtain information from provider.

For example, consider a situation in which a social web site embeds in one iframe the user's email contacts provider (an address book site, from a second origin), and in a second iframe a game (from a third origin). The outer social site and the game in the second iframe cannot access anything inside the first iframe; together they can only:

The contacts provider can use these methods, most particularly the third one, to provide an API that can be accessed by other origins to manipulate the user's address book. For example, it could respond to a message "add-contact Guillaume Tell <tell@pomme.example.net>" by adding the given person and email address to the user's address book.

To avoid any site on the web being able to manipulate the user's contacts, the contacts provider might only allow certain trusted sites, such as the social site, to do this.

Now suppose the game wanted to add a contact to the user's address book, and that the social site was willing to allow it to do so on its behalf, essentially "sharing" the trust that the contacts provider had with the social site. There are several ways it could do this; most simply, it could just proxy messages between the game site and the contacts site. However, this solution has a number of difficulties: it requires the social site to either completely trust the game site not to abuse the privilege, or it requires that the social site verify each request to make sure it's not a request that it doesn't want to allow (such as adding multiple contacts, reading the contacts, or deleting them); it also requires some additional complexity if there's ever the possibility of multiple games simultaneously trying to interact with the contacts provider.

Using message channels and MessagePort objects, however, all of these problems can go away. When the game tells the social site that it wants to add a contact, the social site can ask the contacts provider not for it to add a contact, but for the capability to add a single contact. The contacts provider then creates a pair of MessagePort objects, and sends one of them back to the social site, who forwards it on to the game. The game and the contacts provider then have a direct connection, and the contacts provider knows to only honor a single "add contact" request, nothing else. In other words, the game has been granted the capability to add a single contact.

9.4.1.3 Ports as the basis of abstracting out service implementations

This section is non-normative.

Continuing the example from the previous section, consider the contacts provider in particular. While an initial implementation might have simply used XMLHttpRequest objects in the service's iframe, an evolution of the service might instead want to use a shared worker with a single WebSocket connection.

If the initial design used MessagePort objects to grant capabilities, or even just to allow multiple simultaneous independent sessions, the service implementation can switch from the XMLHttpRequests-in-each-iframe model to the shared-WebSocket model without changing the API at all: the ports on the service provider side can all be forwarded to the shared worker without it affecting the users of the API in the slightest.

9.4.2 Message channels

MessageChannel

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Exposed=(Window,Worker)]
interface MessageChannel {
  constructor();

  readonly attribute MessagePort port1;
  readonly attribute MessagePort port2;
};
channel = new MessageChannel()

MessageChannel/MessageChannel

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Returns a new MessageChannel object with two new MessagePort objects.

channel.port1

MessageChannel/port1

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Returns the first MessagePort object.

channel.port2

MessageChannel/port2

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Returns the second MessagePort object.

A MessageChannel object has an associated port 1 and an associated port 2, both MessagePort objects.

The new MessageChannel() constructor steps are:

  1. Set this's port 1 to a new MessagePort in this's relevant realm.

  2. Set this's port 2 to a new MessagePort in this's relevant realm.

  3. Entangle this's port 1 and this's port 2.

The port1 getter steps are to return this's port 1.

The port2 getter steps are to return this's port 2.

9.4.3 Message ports

MessagePort

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Each channel has two message ports. Data sent through one port is received by the other port, and vice versa.

[Exposed=(Window,Worker,AudioWorklet), Transferable]
interface MessagePort : EventTarget {
  undefined postMessage(any message, sequence<object> transfer);
  undefined postMessage(any message, optional StructuredSerializeOptions options = {});
  undefined start();
  undefined close();

  // event handlers
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
  attribute EventHandler onclose;
};

dictionary StructuredSerializeOptions {
  sequence<object> transfer = [];
};
port.postMessage(message [, transfer])

MessagePort/postMessage

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+
port.postMessage(message [, { transfer }])

Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side.

Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned.

port.start()

MessagePort/start

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Begins dispatching messages received on the port.

port.close()

MessagePort/close

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Disconnects the port, so that it is no longer active.

Each MessagePort object can be entangled with another (a symmetric relationship). Each MessagePort object also has a task source called the port message queue, initially empty. A port message queue can be enabled or disabled, and is initially disabled. Once enabled, a port can never be disabled again (though messages in the queue can get moved to another queue or removed altogether, which has much the same effect). A MessagePort also has a has been shipped flag, which must initially be false.

When a port's port message queue is enabled, the event loop must use it as one of its task sources. When a port's relevant global object is a Window, all tasks queued on its port message queue must be associated with the port's relevant global object's associated Document.

If the document is fully active, but the event listeners were all created in the context of documents that are not fully active, then the messages will not be received unless and until the documents become fully active again.

Each event loop has a task source called the unshipped port message queue. This is a virtual task source: it must act as if it contained the tasks of each port message queue of each MessagePort whose has been shipped flag is false, whose port message queue is enabled, and whose relevant agent's event loop is that event loop, in the order in which they were added to their respective task source. When a task would be removed from the unshipped port message queue, it must instead be removed from its port message queue.

When a MessagePort's has been shipped flag is false, its port message queue must be ignored for the purposes of the event loop. (The unshipped port message queue is used instead.)

The has been shipped flag is set to true when a port, its twin, or the object it was cloned from, is or has been transferred. When a MessagePort's has been shipped flag is true, its port message queue acts as a first-class task source, unaffected to any unshipped port message queue.

When the user agent is to entangle two MessagePort objects, it must run the following steps:

  1. If one of the ports is already entangled, then disentangle it and the port that it was entangled with.

    If those two previously entangled ports were the two ports of a MessageChannel object, then that MessageChannel object no longer represents an actual channel: the two ports in that object are no longer entangled.

  2. Associate the two ports to be entangled, so that they form the two parts of a new channel. (There is no MessageChannel object that represents this channel.)

    Two ports A and B that have gone through this step are now said to be entangled; one is entangled to the other, and vice versa.

    While this specification describes this process as instantaneous, implementations are more likely to implement it via message passing. As with all algorithms, the key is "merely" that the end result be indistinguishable, in a black-box sense, from the specification.

The disentangle steps, given a MessagePort initiatorPort which initiates disentangling, are as follows:

  1. Let otherPort be the MessagePort which initiatorPort was entangled with.

  2. Assert: otherPort exists.

  3. Disentangle initiatorPort and otherPort, so that they are no longer entangled or associated with each other.

  4. Fire an event named close at otherPort.

The close event will be fired even if the port is not explicitly closed. The cases where this event is dispatched are:

We only dispatch the event on otherPort because initiatorPort explicitly triggered the close, its Document no longer exists, or it was already garbage collected, as described above.


MessagePort objects are transferable objects. Their transfer steps, given value and dataHolder, are:

  1. Set value's has been shipped flag to true.

  2. Set dataHolder.[[PortMessageQueue]] to value's port message queue.

  3. If value is entangled with another port remotePort, then:

    1. Set remotePort's has been shipped flag to true.

    2. Set dataHolder.[[RemotePort]] to remotePort.

  4. Otherwise, set dataHolder.[[RemotePort]] to null.

Their transfer-receiving steps, given dataHolder and value, are:

  1. Set value's has been shipped flag to true.

  2. Move all the tasks that are to fire message events in dataHolder.[[PortMessageQueue]] to the port message queue of value, if any, leaving value's port message queue in its initial disabled state, and, if value's relevant global object is a Window, associating the moved tasks with value's relevant global object's associated Document.

  3. If dataHolder.[[RemotePort]] is not null, then entangle dataHolder.[[RemotePort]] and value. (This will disentangle dataHolder.[[RemotePort]] from the original port that was transferred.)


The message port post message steps, given sourcePort, targetPort, message and options are as follows:

  1. Let transfer be options["transfer"].

  2. If transfer contains sourcePort, then throw a "DataCloneError" DOMException.

  3. Let doomed be false.

  4. If targetPort is not null and transfer contains targetPort, then set doomed to true and optionally report to a developer console that the target port was posted to itself, causing the communication channel to be lost.

  5. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.

  6. If targetPort is null, or if doomed is true, then return.

  7. Add a task that runs the following steps to the port message queue of targetPort:

    1. Let finalTargetPort be the MessagePort in whose port message queue the task now finds itself.

      This can be different from targetPort, if targetPort itself was transferred and thus all its tasks moved along with it.

    2. Let targetRealm be finalTargetPort's relevant realm.

    3. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).

      If this throws an exception, catch it, fire an event named messageerror at finalTargetPort, using MessageEvent, and then return.

    4. Let messageClone be deserializeRecord.[[Deserialized]].

    5. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.

    6. Fire an event named message at finalTargetPort, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.

The postMessage(message, options) method steps are:

  1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.

  2. Run the message port post message steps providing this, targetPort, message and options.

The postMessage(message, transfer) method steps are:

  1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.

  2. Let options be «[ "transfer" → transfer ]».

  3. Run the message port post message steps providing this, targetPort, message and options.


The start() method steps are to enable this's port message queue, if it is not already enabled.


The close() method steps are:

  1. Set this's [[Detached]] internal slot value to true.

  2. If this is entangled, disentangle it.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the MessagePort interface:

Event handler Event handler event type
onmessage

MessagePort/message_event

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+
message
onmessageerror

MessagePort/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+
messageerror
onclose close

The first time a MessagePort object's onmessage IDL attribute is set, the port's port message queue must be enabled, as if the start() method had been called.

9.4.4 Ports and garbage collection

When a MessagePort object o is garbage collected, if o is entangled, then the user agent must disentangle o.

When a MessagePort object o is entangled and message or messageerror event listener is registered, user agents must act as if o's entangled MessagePort object has a strong reference to o.

Furthermore, a MessagePort object must not be garbage collected while there exists an event referenced by a task in a task queue that is to be dispatched on that MessagePort object, or while the MessagePort object's port message queue is enabled and not empty.

Thus, a message port can be received, given an event listener, and then forgotten, and so long as that event listener could receive a message, the channel will be maintained.

Of course, if this was to occur on both sides of the channel, then both ports could be garbage collected, since they would not be reachable from live code, despite having a strong reference to each other. However, if a message port has a pending message, it is not garbage collected.

Authors are strongly encouraged to explicitly close MessagePort objects to disentangle them, so that their resources can be recollected. Creating many MessagePort objects and discarding them without closing them can lead to high transient memory usage since garbage collection is not necessarily performed promptly, especially for MessagePorts where garbage collection can involve cross-process coordination.

9.5 Broadcasting to other browsing contexts

BroadcastChannel

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Broadcast_Channel_API

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Pages on a single origin opened by the same user in the same user agent but in different unrelated browsing contexts sometimes need to send notifications to each other, for example "hey, the user logged in over here, check your credentials again".

For elaborate cases, e.g. to manage locking of shared state, to manage synchronization of resources between a server and multiple local clients, to share a WebSocket connection with a remote host, and so forth, shared workers are the most appropriate solution.

For simple cases, though, where a shared worker would be an unreasonable overhead, authors can use the simple channel-based broadcast mechanism described in this section.

[Exposed=(Window,Worker)]
interface BroadcastChannel : EventTarget {
  constructor(DOMString name);

  readonly attribute DOMString name;
  undefined postMessage(any message);
  undefined close();
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
};
broadcastChannel = new BroadcastChannel(name)

BroadcastChannel/BroadcastChannel

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns a new BroadcastChannel object via which messages for the given channel name can be sent and received.

broadcastChannel.name

BroadcastChannel/name

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the channel name (as passed to the constructor).

broadcastChannel.postMessage(message)

BroadcastChannel/postMessage

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays.

broadcastChannel.close()

BroadcastChannel/close

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Closes the BroadcastChannel object, opening it up to garbage collection.

A BroadcastChannel object has a channel name and a closed flag.

The new BroadcastChannel(name) constructor steps are:

  1. Set this's channel name to name.

  2. Set this's closed flag to false.

The name getter steps are to return this's channel name.

A BroadcastChannel object is said to be eligible for messaging when its relevant global object is either:

The postMessage(message) method steps are:

  1. If this is not eligible for messaging, then return.

  2. If this's closed flag is true, then throw an "InvalidStateError" DOMException.

  3. Let serialized be StructuredSerialize(message). Rethrow any exceptions.

  4. Let sourceOrigin be this's relevant settings object's origin.

  5. Let sourceStorageKey be the result of running obtain a storage key for non-storage purposes with this's relevant settings object.

  6. Let destinations be a list of BroadcastChannel objects that match the following criteria:

  7. Remove source from destinations.

  8. Sort destinations such that all BroadcastChannel objects whose relevant agents are the same are sorted in creation order, oldest first. (This does not define a complete ordering. Within this constraint, user agents may sort the list in any implementation-defined manner.)

  9. For each destination in destinations, queue a global task on the DOM manipulation task source given destination's relevant global object to perform the following steps:

    1. If destination's closed flag is true, then abort these steps.

    2. Let targetRealm be destination's relevant realm.

    3. Let data be StructuredDeserialize(serialized, targetRealm).

      If this throws an exception, catch it, fire an event named messageerror at destination, using MessageEvent, with the origin attribute initialized to the serialization of sourceOrigin, and then abort these steps.

    4. Fire an event named message at destination, using MessageEvent, with the data attribute initialized to data and the origin attribute initialized to the serialization of sourceOrigin.

While a BroadcastChannel object whose closed flag is false has an event listener registered for message or messageerror events, there must be a strong reference from the BroadcastChannel object's relevant global object to the BroadcastChannel object itself.

The close() method steps are to set this's closed flag to true.

Authors are strongly encouraged to explicitly close BroadcastChannel objects when they are no longer needed, so that they can be garbage collected. Creating many BroadcastChannel objects and discarding them while leaving them with an event listener and without closing them can lead to an apparent memory leak, since the objects will continue to live for as long as they have an event listener (or until their page or worker is closed).


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the BroadcastChannel interface:

Event handler Event handler event type
onmessage

BroadcastChannel/message_event

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
message
onmessageerror

BroadcastChannel/messageerror_event

Support in all current engines.

Firefox57+Safari15.4+Chrome60+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+
messageerror

Suppose a page wants to know when the user logs out, even when the user does so from another tab at the same site:

var authChannel = new BroadcastChannel('auth');
authChannel.onmessage = function (event) {
  if (event.data == 'logout')
    showLogout();
}

function logoutRequested() {
  // called when the user asks us to log them out
  doLogout();
  showLogout();
  authChannel.postMessage('logout');
}

function doLogout() {
  // actually log the user out (e.g. clearing cookies)
  // ...
}

function showLogout() {
  // update the UI to indicate we're logged out
  // ...
}

10 Web workers

Web_Workers_API

Support in all current engines.

Firefox3.5+Safari4+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Web_Workers_API/Using_web_workers

10.1 Introduction

10.1.1 Scope

This section is non-normative.

This specification defines an API for running scripts in the background independently of any user interface scripts.

This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.

Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image. The examples below show some appropriate uses of workers.

Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.

10.1.2 Examples

This section is non-normative.

There are a variety of uses that workers can be put to. The following subsections show various examples of this use.

10.1.2.1 A background number-crunching worker

This section is non-normative.

The simplest use of workers is for performing a computationally expensive task without interrupting the user interface.

In this example, the main document spawns a worker to (naïvely) compute prime numbers, and progressively displays the most recently found prime number.

The main page is as follows:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Worker example: One-core computation</title>
 </head>
 <body>
  <p>The highest prime number discovered so far is: <output id="result"></output></p>
  <script>
   var worker = new Worker('worker.js');
   worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
   };
  </script>
 </body>
</html>

The Worker() constructor call creates a worker and returns a Worker object representing that worker, which is used to communicate with the worker. That object's onmessage event handler allows the code to receive messages from the worker.

The worker itself is as follows:

var n = 1;
search: while (true) {
  n += 1;
  for (var i = 2; i <= Math.sqrt(n); i += 1)
    if (n % i == 0)
     continue search;
  // found a prime!
  postMessage(n);
}

The bulk of this code is simply an unoptimized search for a prime number. The postMessage() method is used to send a message back to the page when a prime is found.

View this example online.

10.1.2.2 Using a JavaScript module as a worker

This section is non-normative.

All of our examples so far show workers that run classic scripts. Workers can instead be instantiated using module scripts, which have the usual benefits: the ability to use the JavaScript import statement to import other modules; strict mode by default; and top-level declarations not polluting the worker's global scope.

As the import statement is available, the importScripts() method will automatically fail inside module workers.

In this example, the main document uses a worker to do off-main-thread image manipulation. It imports the filters used from another module.

The main page is as follows:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Worker example: image decoding</title>

<p>
  <label>
    Type an image URL to decode
    <input type="url" id="image-url" list="image-list">
    <datalist id="image-list">
      <option value="https://html.spec.whatwg.org/images/drawImage.png">
      <option value="https://html.spec.whatwg.org/images/robots.jpeg">
      <option value="https://html.spec.whatwg.org/images/arcTo2.png">
    </datalist>
  </label>
</p>

<p>
  <label>
    Choose a filter to apply
    <select id="filter">
      <option value="none">none</option>
      <option value="grayscale">grayscale</option>
      <option value="brighten">brighten by 20%</option>
    </select>
  </label>
</p>

<div id="output"></div>

<script type="module">
  const worker = new Worker("worker.js", { type: "module" });
  worker.onmessage = receiveFromWorker;

  const url = document.querySelector("#image-url");
  const filter = document.querySelector("#filter");
  const output = document.querySelector("#output");

  url.oninput = updateImage;
  filter.oninput = sendToWorker;

  let imageData, context;

  function updateImage() {
    const img = new Image();
    img.src = url.value;

    img.onload = () => {
      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;

      context = canvas.getContext("2d");
      context.drawImage(img, 0, 0);
      imageData = context.getImageData(0, 0, canvas.width, canvas.height);

      sendToWorker();
      output.replaceChildren(canvas);
    };
  }

  function sendToWorker() {
    worker.postMessage({ imageData, filter: filter.value });
  }

  function receiveFromWorker(e) {
    context.putImageData(e.data, 0, 0);
  }
</script>

The worker file is then:

import * as filters from "./filters.js";

self.onmessage = e => {
  const { imageData, filter } = e.data;
  filters[filter](imageData);
  self.postMessage(imageData, [imageData.data.buffer]);
};

Which imports the file filters.js:

export function none() {}

export function grayscale({ data: d }) {
  for (let i = 0; i < d.length; i += 4) {
    const [r, g, b] = [d[i], d[i + 1], d[i + 2]];

    // CIE luminance for the RGB
    // The human eye is bad at seeing red and blue, so we de-emphasize them.
    d[i] = d[i + 1] = d[i + 2] = 0.2126 * r + 0.7152 * g + 0.0722 * b;
  }
};

export function brighten({ data: d }) {
  for (let i = 0; i < d.length; ++i) {
    d[i] *= 1.2;
  }
};

View this example online.

10.1.2.3 Shared workers introduction

SharedWorker

Support in all current engines.

Firefox29+Safari16+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android33+Safari iOS16+Chrome AndroidNoWebView Android?Samsung Internet4.0–5.0Opera Android11–14

This section is non-normative.

This section introduces shared workers using a Hello World example. Shared workers use slightly different APIs, since each worker can have multiple connections.

This first example shows how you connect to a worker and how a worker can send a message back to the page when it connects to it. Received messages are displayed in a log.

Here is the HTML page:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 1</title>
<pre id="log">Log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.onmessage = function(e) { // note: not worker.onmessage!
    log.textContent += '\n' + e.data;
  }
</script>

Here is the JavaScript worker:

onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Hello World!');
}

View this example online.


This second example extends the first one by changing two things: first, messages are received using addEventListener() instead of an event handler IDL attribute, and second, a message is sent to the worker, causing the worker to send another message in return. Received messages are again displayed in a log.

Here is the HTML page:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 2</title>
<pre id="log">Log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.addEventListener('message', function(e) {
    log.textContent += '\n' + e.data;
  }, false);
  worker.port.start(); // note: need this when using addEventListener
  worker.port.postMessage('ping');
</script>

Here is the JavaScript worker:

onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Hello World!');
  port.onmessage = function(e) {
    port.postMessage('pong'); // not e.ports[0].postMessage!
    // e.target.postMessage('pong'); would work also
  }
}

View this example online.


Finally, the example is extended to show how two pages can connect to the same worker; in this case, the second page is merely in an iframe on the first page, but the same principle would apply to an entirely separate page in a separate top-level traversable.

Here is the outer HTML page:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 3</title>
<pre id="log">Log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.addEventListener('message', function(e) {
    log.textContent += '\n' + e.data;
  }, false);
  worker.port.start();
  worker.port.postMessage('ping');
</script>
<iframe src="inner.html"></iframe>

Here is the inner HTML page:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 3 inner frame</title>
<pre id=log>Inner log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.onmessage = function(e) {
   log.textContent += '\n' + e.data;
  }
</script>

Here is the JavaScript worker:

var count = 0;
onconnect = function(e) {
  count += 1;
  var port = e.ports[0];
  port.postMessage('Hello World! You are connection #' + count);
  port.onmessage = function(e) {
    port.postMessage('pong');
  }
}

View this example online.

10.1.2.4 Shared state using a shared worker

This section is non-normative.

In this example, multiple windows (viewers) can be opened that are all viewing the same map. All the windows share the same map information, with a single worker coordinating all the viewers. Each viewer can move around independently, but if they set any data on the map, all the viewers are updated.

The main page isn't interesting, it merely provides a way to open the viewers:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Workers example: Multiviewer</title>
  <script>
   function openViewer() {
     window.open('viewer.html');
   }
  </script>
 </head>
 <body>
  <p><button type=button onclick="openViewer()">Open a new
  viewer</button></p>
  <p>Each viewer opens in a new window. You can have as many viewers
  as you like, they all view the same data.</p>
 </body>
</html>

The viewer is more involved:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Workers example: Multiviewer viewer</title>
  <script>
   var worker = new SharedWorker('worker.js', 'core');

   // CONFIGURATION
   function configure(event) {
     if (event.data.substr(0, 4) != 'cfg ') return;
     var name = event.data.substr(4).split(' ', 1)[0];
     // update display to mention our name is name
     document.getElementsByTagName('h1')[0].textContent += ' ' + name;
     // no longer need this listener
     worker.port.removeEventListener('message', configure, false);
   }
   worker.port.addEventListener('message', configure, false);

   // MAP
   function paintMap(event) {
     if (event.data.substr(0, 4) != 'map ') return;
     var data = event.data.substr(4).split(',');
     // display tiles data[0] .. data[8]
     var canvas = document.getElementById('map');
     var context = canvas.getContext('2d');
     for (var y = 0; y < 3; y += 1) {
       for (var x = 0; x < 3; x += 1) {
         var tile = data[y * 3 + x];
         if (tile == '0')
           context.fillStyle = 'green';
         else
           context.fillStyle = 'maroon';
         context.fillRect(x * 50, y * 50, 50, 50);
       }
     }
   }
   worker.port.addEventListener('message', paintMap, false);

   // PUBLIC CHAT
   function updatePublicChat(event) {
     if (event.data.substr(0, 4) != 'txt ') return;
     var name = event.data.substr(4).split(' ', 1)[0];
     var message = event.data.substr(4 + name.length + 1);
     // display "<name> message" in public chat
     var public = document.getElementById('public');
     var p = document.createElement('p');
     var n = document.createElement('button');
     n.textContent = '<' + name + '> ';
     n.onclick = function () { worker.port.postMessage('msg ' + name); };
     p.appendChild(n);
     var m = document.createElement('span');
     m.textContent = message;
     p.appendChild(m);
     public.appendChild(p);
   }
   worker.port.addEventListener('message', updatePublicChat, false);

   // PRIVATE CHAT
   function startPrivateChat(event) {
     if (event.data.substr(0, 4) != 'msg ') return;
     var name = event.data.substr(4).split(' ', 1)[0];
     var port = event.ports[0];
     // display a private chat UI
     var ul = document.getElementById('private');
     var li = document.createElement('li');
     var h3 = document.createElement('h3');
     h3.textContent = 'Private chat with ' + name;
     li.appendChild(h3);
     var div = document.createElement('div');
     var addMessage = function(name, message) {
       var p = document.createElement('p');
       var n = document.createElement('strong');
       n.textContent = '<' + name + '> ';
       p.appendChild(n);
       var t = document.createElement('span');
       t.textContent = message;
       p.appendChild(t);
       div.appendChild(p);
     };
     port.onmessage = function (event) {
       addMessage(name, event.data);
     };
     li.appendChild(div);
     var form = document.createElement('form');
     var p = document.createElement('p');
     var input = document.createElement('input');
     input.size = 50;
     p.appendChild(input);
     p.appendChild(document.createTextNode(' '));
     var button = document.createElement('button');
     button.textContent = 'Post';
     p.appendChild(button);
     form.onsubmit = function () {
       port.postMessage(input.value);
       addMessage('me', input.value);
       input.value = '';
       return false;
     };
     form.appendChild(p);
     li.appendChild(form);
     ul.appendChild(li);
   }
   worker.port.addEventListener('message', startPrivateChat, false);

   worker.port.start();
  </script>
 </head>
 <body>
  <h1>Viewer</h1>
  <h2>Map</h2>
  <p><canvas id="map" height=150 width=150></canvas></p>
  <p>
   <button type=button onclick="worker.port.postMessage('mov left')">Left</button>
   <button type=button onclick="worker.port.postMessage('mov up')">Up</button>
   <button type=button onclick="worker.port.postMessage('mov down')">Down</button>
   <button type=button onclick="worker.port.postMessage('mov right')">Right</button>
   <button type=button onclick="worker.port.postMessage('set 0')">Set 0</button>
   <button type=button onclick="worker.port.postMessage('set 1')">Set 1</button>
  </p>
  <h2>Public Chat</h2>
  <div id="public"></div>
  <form onsubmit="worker.port.postMessage('txt ' + message.value); message.value = ''; return false;">
   <p>
    <input type="text" name="message" size="50">
    <button>Post</button>
   </p>
  </form>
  <h2>Private Chat</h2>
  <ul id="private"></ul>
 </body>
</html>

There are several key things worth noting about the way the viewer is written.

Multiple listeners. Instead of a single message processing function, the code here attaches multiple event listeners, each one performing a quick check to see if it is relevant for the message. In this example it doesn't make much difference, but if multiple authors wanted to collaborate using a single port to communicate with a worker, it would allow for independent code instead of changes having to all be made to a single event handling function.

Registering event listeners in this way also allows you to unregister specific listeners when you are done with them, as is done with the configure() method in this example.

Finally, the worker:

var nextName = 0;
function getNextName() {
  // this could use more friendly names
  // but for now just return a number
  return nextName++;
}

var map = [
 [0, 0, 0, 0, 0, 0, 0],
 [1, 1, 0, 1, 0, 1, 1],
 [0, 1, 0, 1, 0, 0, 0],
 [0, 1, 0, 1, 0, 1, 1],
 [0, 0, 0, 1, 0, 0, 0],
 [1, 0, 0, 1, 1, 1, 1],
 [1, 1, 0, 1, 1, 0, 1],
];

function wrapX(x) {
  if (x < 0) return wrapX(x + map[0].length);
  if (x >= map[0].length) return wrapX(x - map[0].length);
  return x;
}

function wrapY(y) {
  if (y < 0) return wrapY(y + map.length);
  if (y >= map[0].length) return wrapY(y - map.length);
  return y;
}

function wrap(val, min, max) {
  if (val < min)
    return val + (max-min)+1;
  if (val > max)
    return val - (max-min)-1;
  return val;
}

function sendMapData(viewer) {
  var data = '';
  for (var y = viewer.y-1; y <= viewer.y+1; y += 1) {
    for (var x = viewer.x-1; x <= viewer.x+1; x += 1) {
      if (data != '')
        data += ',';
      data += map[wrap(y, 0, map[0].length-1)][wrap(x, 0, map.length-1)];
    }
  }
  viewer.port.postMessage('map ' + data);
}

var viewers = {};
onconnect = function (event) {
  var name = getNextName();
  event.ports[0]._data = { port: event.ports[0], name: name, x: 0, y: 0, };
  viewers[name] = event.ports[0]._data;
  event.ports[0].postMessage('cfg ' + name);
  event.ports[0].onmessage = getMessage;
  sendMapData(event.ports[0]._data);
};

function getMessage(event) {
  switch (event.data.substr(0, 4)) {
    case 'mov ':
      var direction = event.data.substr(4);
      var dx = 0;
      var dy = 0;
      switch (direction) {
        case 'up': dy = -1; break;
        case 'down': dy = 1; break;
        case 'left': dx = -1; break;
        case 'right': dx = 1; break;
      }
      event.target._data.x = wrapX(event.target._data.x + dx);
      event.target._data.y = wrapY(event.target._data.y + dy);
      sendMapData(event.target._data);
      break;
    case 'set ':
      var value = event.data.substr(4);
      map[event.target._data.y][event.target._data.x] = value;
      for (var viewer in viewers)
        sendMapData(viewers[viewer]);
      break;
    case 'txt ':
      var name = event.target._data.name;
      var message = event.data.substr(4);
      for (var viewer in viewers)
        viewers[viewer].port.postMessage('txt ' + name + ' ' + message);
      break;
    case 'msg ':
      var party1 = event.target._data;
      var party2 = viewers[event.data.substr(4).split(' ', 1)[0]];
      if (party2) {
        var channel = new MessageChannel();
        party1.port.postMessage('msg ' + party2.name, [channel.port1]);
        party2.port.postMessage('msg ' + party1.name, [channel.port2]);
      }
      break;
  }
}

Connecting to multiple pages. The script uses the onconnect event listener to listen for multiple connections.

Direct channels. When the worker receives a "msg" message from one viewer naming another viewer, it sets up a direct connection between the two, so that the two viewers can communicate directly without the worker having to proxy all the messages.

View this example online.

10.1.2.5 Delegation

This section is non-normative.

With multicore CPUs becoming prevalent, one way to obtain better performance is to split computationally expensive tasks amongst multiple workers. In this example, a computationally expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten subworkers.

The main page is as follows, it just reports the result:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Worker example: Multicore computation</title>
 </head>
 <body>
  <p>Result: <output id="result"></output></p>
  <script>
   var worker = new Worker('worker.js');
   worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
   };
  </script>
 </body>
</html>

The worker itself is as follows:

// settings
var num_workers = 10;
var items_per_worker = 1000000;

// start the workers
var result = 0;
var pending_workers = num_workers;
for (var i = 0; i < num_workers; i += 1) {
  var worker = new Worker('core.js');
  worker.postMessage(i * items_per_worker);
  worker.postMessage((i+1) * items_per_worker);
  worker.onmessage = storeResult;
}

// handle the results
function storeResult(event) {
  result += 1*event.data;
  pending_workers -= 1;
  if (pending_workers <= 0)
    postMessage(result); // finished!
}

It consists of a loop to start the subworkers, and then a handler that waits for all the subworkers to respond.

The subworkers are implemented as follows:

var start;
onmessage = getStart;
function getStart(event) {
  start = 1*event.data;
  onmessage = getEnd;
}

var end;
function getEnd(event) {
  end = 1*event.data;
  onmessage = null;
  work();
}

function work() {
  var result = 0;
  for (var i = start; i < end; i += 1) {
    // perform some complex calculation here
    result += 1;
  }
  postMessage(result);
  close();
}

They receive two numbers in two events, perform the computation for the range of numbers thus specified, and then report the result back to the parent.

View this example online.

10.1.2.6 Providing libraries

This section is non-normative.

Suppose that a cryptography library is made available that provides three tasks:

Generate a public/private key pair
Takes a port, on which it will send two messages, first the public key and then the private key.
Given a plaintext and a public key, return the corresponding ciphertext
Takes a port, to which any number of messages can be sent, the first giving the public key, and the remainder giving the plaintext, each of which is encrypted and then sent on that same channel as the ciphertext. The user can close the port when it is done encrypting content.
Given a ciphertext and a private key, return the corresponding plaintext
Takes a port, to which any number of messages can be sent, the first giving the private key, and the remainder giving the ciphertext, each of which is decrypted and then sent on that same channel as the plaintext. The user can close the port when it is done decrypting content.

The library itself is as follows:

function handleMessage(e) {
  if (e.data == "genkeys")
    genkeys(e.ports[0]);
  else if (e.data == "encrypt")
    encrypt(e.ports[0]);
  else if (e.data == "decrypt")
    decrypt(e.ports[0]);
}

function genkeys(p) {
  var keys = _generateKeyPair();
  p.postMessage(keys[0]);
  p.postMessage(keys[1]);
}

function encrypt(p) {
  var key, state = 0;
  p.onmessage = function (e) {
    if (state == 0) {
      key = e.data;
      state = 1;
    } else {
      p.postMessage(_encrypt(key, e.data));
    }
  };
}

function decrypt(p) {
  var key, state = 0;
  p.onmessage = function (e) {
    if (state == 0) {
      key = e.data;
      state = 1;
    } else {
      p.postMessage(_decrypt(key, e.data));
    }
  };
}

// support being used as a shared worker as well as a dedicated worker
if ('onmessage' in this) // dedicated worker
  onmessage = handleMessage;
else // shared worker
  onconnect = function (e) { e.port.onmessage = handleMessage; }


// the "crypto" functions:

function _generateKeyPair() {
  return [Math.random(), Math.random()];
}

function _encrypt(k, s) {
  return 'encrypted-' + k + ' ' + s;
}

function _decrypt(k, s) {
  return s.substr(s.indexOf(' ')+1);
}

Note that the crypto functions here are just stubs and don't do real cryptography.

This library could be used as follows:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Worker example: Crypto library</title>
  <script>
   const cryptoLib = new Worker('libcrypto-v1.js'); // or could use 'libcrypto-v2.js'
   function startConversation(source, message) {
     const messageChannel = new MessageChannel();
     source.postMessage(message, [messageChannel.port2]);
     return messageChannel.port1;
   }
   function getKeys() {
     let state = 0;
     startConversation(cryptoLib, "genkeys").onmessage = function (e) {
       if (state === 0)
         document.getElementById('public').value = e.data;
       else if (state === 1)
         document.getElementById('private').value = e.data;
       state += 1;
     };
   }
   function enc() {
     const port = startConversation(cryptoLib, "encrypt");
     port.postMessage(document.getElementById('public').value);
     port.postMessage(document.getElementById('input').value);
     port.onmessage = function (e) {
       document.getElementById('input').value = e.data;
       port.close();
     };
   }
   function dec() {
     const port = startConversation(cryptoLib, "decrypt");
     port.postMessage(document.getElementById('private').value);
     port.postMessage(document.getElementById('input').value);
     port.onmessage = function (e) {
       document.getElementById('input').value = e.data;
       port.close();
     };
   }
  </script>
  <style>
   textarea { display: block; }
  </style>
 </head>
 <body onload="getKeys()">
  <fieldset>
   <legend>Keys</legend>
   <p><label>Public Key: <textarea id="public"></textarea></label></p>
   <p><label>Private Key: <textarea id="private"></textarea></label></p>
  </fieldset>
  <p><label>Input: <textarea id="input"></textarea></label></p>
  <p><button onclick="enc()">Encrypt</button> <button onclick="dec()">Decrypt</button></p>
 </body>
</html>

A later version of the API, though, might want to offload all the crypto work onto subworkers. This could be done as follows:

function handleMessage(e) {
  if (e.data == "genkeys")
    genkeys(e.ports[0]);
  else if (e.data == "encrypt")
    encrypt(e.ports[0]);
  else if (e.data == "decrypt")
    decrypt(e.ports[0]);
}

function genkeys(p) {
  var generator = new Worker('libcrypto-v2-generator.js');
  generator.postMessage('', [p]);
}

function encrypt(p) {
  p.onmessage = function (e) {
    var key = e.data;
    var encryptor = new Worker('libcrypto-v2-encryptor.js');
    encryptor.postMessage(key, [p]);
  };
}

function encrypt(p) {
  p.onmessage = function (e) {
    var key = e.data;
    var decryptor = new Worker('libcrypto-v2-decryptor.js');
    decryptor.postMessage(key, [p]);
  };
}

// support being used as a shared worker as well as a dedicated worker
if ('onmessage' in this) // dedicated worker
  onmessage = handleMessage;
else // shared worker
  onconnect = function (e) { e.ports[0].onmessage = handleMessage };

The little subworkers would then be as follows.

For generating key pairs:

onmessage = function (e) {
  var k = _generateKeyPair();
  e.ports[0].postMessage(k[0]);
  e.ports[0].postMessage(k[1]);
  close();
}

function _generateKeyPair() {
  return [Math.random(), Math.random()];
}

For encrypting:

onmessage = function (e) {
  var key = e.data;
  e.ports[0].onmessage = function (e) {
    var s = e.data;
    postMessage(_encrypt(key, s));
  }
}

function _encrypt(k, s) {
  return 'encrypted-' + k + ' ' + s;
}

For decrypting:

onmessage = function (e) {
  var key = e.data;
  e.ports[0].onmessage = function (e) {
    var s = e.data;
    postMessage(_decrypt(key, s));
  }
}

function _decrypt(k, s) {
  return s.substr(s.indexOf(' ')+1);
}

Notice how the users of the API don't have to even know that this is happening — the API hasn't changed; the library can delegate to subworkers without changing its API, even though it is accepting data using message channels.

View this example online.

10.1.3 Tutorials

10.1.3.1 Creating a dedicated worker

This section is non-normative.

Creating a worker requires a URL to a JavaScript file. The Worker() constructor is invoked with the URL to that file as its only argument; a worker is then created and returned:

var worker = new Worker('helper.js');

If you want your worker script to be interpreted as a module script instead of the default classic script, you need to use a slightly different signature:

var worker = new Worker('helper.mjs', { type: "module" });
10.1.3.2 Communicating with a dedicated worker

This section is non-normative.

Dedicated workers use MessagePort objects behind the scenes, and thus support all the same features, such as sending structured data, transferring binary data, and transferring other ports.

To receive messages from a dedicated worker, use the onmessage event handler IDL attribute on the Worker object:

worker.onmessage = function (event) { ... };

You can also use the addEventListener() method.

The implicit MessagePort used by dedicated workers has its port message queue implicitly enabled when it is created, so there is no equivalent to the MessagePort interface's start() method on the Worker interface.

To send data to a worker, use the postMessage() method. Structured data can be sent over this communication channel. To send ArrayBuffer objects efficiently (by transferring them rather than cloning them), list them in an array in the second argument.

worker.postMessage({
  operation: 'find-edges',
  input: buffer, // an ArrayBuffer object
  threshold: 0.6,
}, [buffer]);

To receive a message inside the worker, the onmessage event handler IDL attribute is used.

onmessage = function (event) { ... };

You can again also use the addEventListener() method.

In either case, the data is provided in the event object's data attribute.

To send messages back, you again use postMessage(). It supports the structured data in the same manner.

postMessage(event.data.input, [event.data.input]); // transfer the buffer back
10.1.3.3 Shared workers

SharedWorker

Support in all current engines.

Firefox29+Safari16+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android33+Safari iOS16+Chrome AndroidNoWebView Android?Samsung Internet4.0–5.0Opera Android11–14

This section is non-normative.

Shared workers are identified by the URL of the script used to create it, optionally with an explicit name. The name allows multiple instances of a particular shared worker to be started.

Shared workers are scoped by origin. Two different sites using the same names will not collide. However, if a page tries to use the same shared worker name as another page on the same site, but with a different script URL, it will fail.

Creating shared workers is done using the SharedWorker() constructor. This constructor takes the URL to the script to use for its first argument, and the name of the worker, if any, as the second argument.

var worker = new SharedWorker('service.js');

Communicating with shared workers is done with explicit MessagePort objects. The object returned by the SharedWorker() constructor holds a reference to the port on its port attribute.

worker.port.onmessage = function (event) { ... };
worker.port.postMessage('some message');
worker.port.postMessage({ foo: 'structured', bar: ['data', 'also', 'possible']});

Inside the shared worker, new clients of the worker are announced using the connect event. The port for the new client is given by the event object's source attribute.

onconnect = function (event) {
  var newPort = event.source;
  // set up a listener
  newPort.onmessage = function (event) { ... };
  // send a message back to the port
  newPort.postMessage('ready!'); // can also send structured data, of course
};

10.2 Infrastructure

This standard defines two kinds of workers: dedicated workers, and shared workers. Dedicated workers, once created, are linked to their creator, but message ports can be used to communicate from a dedicated worker to multiple other browsing contexts or workers. Shared workers, on the other hand, are named, and once created any script running in the same origin can obtain a reference to that worker and communicate with it. Service Workers defines a third kind. [SW]

10.2.1 The global scope

The global scope is the "inside" of a worker.

10.2.1.1 The WorkerGlobalScope common interface

WorkerGlobalScope

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Exposed=Worker]
interface WorkerGlobalScope : EventTarget {
  readonly attribute WorkerGlobalScope self;
  readonly attribute WorkerLocation location;
  readonly attribute WorkerNavigator navigator;
  undefined importScripts((TrustedScriptURL or USVString)... urls);

  attribute OnErrorEventHandler onerror;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onunhandledrejection;
};

WorkerGlobalScope serves as the base class for specific types of worker global scope objects, including DedicatedWorkerGlobalScope, SharedWorkerGlobalScope, and ServiceWorkerGlobalScope.

A WorkerGlobalScope object has an associated owner set (a set of Document and WorkerGlobalScope objects). It is initially empty and populated when the worker is created or obtained.

It is a set, instead of a single owner, to accommodate SharedWorkerGlobalScope objects.

A WorkerGlobalScope object has an associated type ("classic" or "module"). It is set during creation.

A WorkerGlobalScope object has an associated url (null or a URL). It is initially null.

A WorkerGlobalScope object has an associated name (a string). It is set during creation.

The name can have different semantics for each subclass of WorkerGlobalScope. For DedicatedWorkerGlobalScope instances, it is simply a developer-supplied name, useful mostly for debugging purposes. For SharedWorkerGlobalScope instances, it allows obtaining a reference to a common shared worker via the SharedWorker() constructor. For ServiceWorkerGlobalScope objects, it doesn't make sense (and as such isn't exposed through the JavaScript API at all).

A WorkerGlobalScope object has an associated policy container (a policy container). It is initially a new policy container.

A WorkerGlobalScope object has an associated embedder policy (an embedder policy).

A WorkerGlobalScope object has an associated module map. It is a module map, initially empty.

A WorkerGlobalScope object has an associated cross-origin isolated capability boolean. It is initially false.

workerGlobal.self

WorkerGlobalScope/self

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android34+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android?
Returns workerGlobal.
workerGlobal.location

WorkerGlobalScope/location

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android?
Returns workerGlobal's WorkerLocation object.
workerGlobal.navigator

WorkerGlobalScope/navigator

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)17+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android?
Returns workerGlobal's WorkerNavigator object.
workerGlobal.importScripts(...urls)

WorkerGlobalScope/importScripts

Support in all current engines.

Firefox4+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
Fetches each URL in urls, executes them one-by-one in the order they are passed, and then returns (or throws if something went amiss).

The self attribute must return the WorkerGlobalScope object itself.

The location attribute must return the WorkerLocation object whose associated WorkerGlobalScope object is the WorkerGlobalScope object.

While the WorkerLocation object is created after the WorkerGlobalScope object, this is not problematic as it cannot be observed from script.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the WorkerGlobalScope interface:

Event handler Event handler event type
onerror

WorkerGlobalScope/error_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android?
error
onlanguagechange

WorkerGlobalScope/languagechange_event

Support in all current engines.

Firefox74+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
languagechange
onoffline

WorkerGlobalScope/offline_event

Firefox29+Safari8+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
offline
ononline

WorkerGlobalScope/online_event

Firefox29+Safari8+ChromeNo
Opera?EdgeNo
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
online
onrejectionhandled rejectionhandled
onunhandledrejection unhandledrejection
10.2.1.2 Dedicated workers and the DedicatedWorkerGlobalScope interface

DedicatedWorkerGlobalScope

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Global=(Worker,DedicatedWorker),Exposed=DedicatedWorker]
interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
  [Replaceable] readonly attribute DOMString name;

  undefined postMessage(any message, sequence<object> transfer);
  undefined postMessage(any message, optional StructuredSerializeOptions options = {});

  undefined close();

  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
};

DedicatedWorkerGlobalScope objects act as if they had an implicit MessagePort associated with them. This port is part of a channel that is set up when the worker is created, but it is not exposed. This object must never be garbage collected before the DedicatedWorkerGlobalScope object.

All messages received by that port must immediately be retargeted at the DedicatedWorkerGlobalScope object.

dedicatedWorkerGlobal.name

DedicatedWorkerGlobalScope/name

Support in all current engines.

Firefox55+Safari12.1+Chrome70+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns dedicatedWorkerGlobal's name, i.e. the value given to the Worker constructor. Primarily useful for debugging.

dedicatedWorkerGlobal.postMessage(message [, transfer ])

DedicatedWorkerGlobalScope/postMessage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
dedicatedWorkerGlobal.postMessage(message [, { transfer } ])

Clones message and transmits it to the Worker object associated with dedicatedWorkerGlobal. transfer can be passed as a list of objects that are to be transferred rather than cloned.

dedicatedWorkerGlobal.close()

DedicatedWorkerGlobalScope/close

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Aborts dedicatedWorkerGlobal.

The name getter steps are to return this's name. Its value represents the name given to the worker using the Worker constructor, used primarily for debugging purposes.

The postMessage(message, transfer) and postMessage(message, options) methods on DedicatedWorkerGlobalScope objects act as if, when invoked, it immediately invoked the respective postMessage(message, transfer) and postMessage(message, options) on the port, with the same arguments, and returned the same return value.

To close a worker, given a workerGlobal, run these steps:

  1. Discard any tasks that have been added to workerGlobal's relevant agent's event loop's task queues.

  2. Set workerGlobal's closing flag to true. (This prevents any further tasks from being queued.)

The close() method steps are to close a worker given this.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the DedicatedWorkerGlobalScope interface:

Event handler Event handler event type
onmessage

DedicatedWorkerGlobalScope/message_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+
message
onmessageerror

DedicatedWorkerGlobalScope/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+
messageerror
10.2.1.3 Shared workers and the SharedWorkerGlobalScope interface

SharedWorkerGlobalScope

Support in all current engines.

Firefox29+Safari16+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS16+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
[Global=(Worker,SharedWorker),Exposed=SharedWorker]
interface SharedWorkerGlobalScope : WorkerGlobalScope {
  [Replaceable] readonly attribute DOMString name;

  undefined close();

  attribute EventHandler onconnect;
};

A SharedWorkerGlobalScope object has an associated constructor origin, constructor url, and credentials. They are initialized when the SharedWorkerGlobalScope object is created, in the run a worker algorithm.

Shared workers receive message ports through connect events on their SharedWorkerGlobalScope object for each connection.

sharedWorkerGlobal.name

SharedWorkerGlobalScope/name

Support in all current engines.

Firefox29+Safari16+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS16+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Returns sharedWorkerGlobal's name, i.e. the value given to the SharedWorker constructor. Multiple SharedWorker objects can correspond to the same shared worker (and SharedWorkerGlobalScope), by reusing the same name.

sharedWorkerGlobal.close()

SharedWorkerGlobalScope/close

Support in all current engines.

Firefox29+Safari16+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS16+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Aborts sharedWorkerGlobal.

The name getter steps are to return this's name. Its value represents the name that can be used to obtain a reference to the worker using the SharedWorker constructor.

The close() method steps are to close a worker given this.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the SharedWorkerGlobalScope interface:

Event handler Event handler event type
onconnect

SharedWorkerGlobalScope/connect_event

Support in all current engines.

Firefox29+Safari16+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS16+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
connect

10.2.2 The event loop

A worker event loop's task queues only have events, callbacks, and networking activity as tasks. These worker event loops are created by the run a worker algorithm.

Each WorkerGlobalScope object has a closing flag, which must be initially false, but which can get set to true by the algorithms in the processing model section below.

Once the WorkerGlobalScope's closing flag is set to true, the event loop's task queues must discard any further tasks that would be added to them (tasks already on the queue are unaffected except where otherwise specified). Effectively, once the closing flag is true, timers stop firing, notifications for all pending background operations are dropped, etc.

10.2.3 The worker's lifetime

Workers communicate with other workers and with Windows through message channels and their MessagePort objects.

Each WorkerGlobalScope object worker global scope has a list of the worker's ports, which consists of all the MessagePort objects that are entangled with another port and that have one (but only one) port owned by worker global scope. This list includes the implicit MessagePort in the case of dedicated workers.

Given an environment settings object o when creating or obtaining a worker, the relevant owner to add depends on the type of global object specified by o. If o's global object is a WorkerGlobalScope object (i.e., if we are creating a nested dedicated worker), then the relevant owner is that global object. Otherwise, o's global object is a Window object, and the relevant owner is that Window's associated Document.


A worker is said to be a permissible worker if its WorkerGlobalScope's owner set is not empty or:

The second part of this definition allows a shared worker to survive for a short time while a page is loading, in case that page is going to contact the shared worker again. This can be used by user agents as a way to avoid the cost of restarting a shared worker used by a site when the user is navigating from page to page within that site.

A worker is said to be an active needed worker if any of its owners are either Document objects that are fully active or active needed workers.

A worker is said to be a protected worker if it is an active needed worker and either it has outstanding timers, database transactions, or network connections, or its list of the worker's ports is not empty, or its WorkerGlobalScope is actually a SharedWorkerGlobalScope object (i.e., the worker is a shared worker).

A worker is said to be a suspendable worker if it is not an active needed worker but it is a permissible worker.

10.2.4 Processing model

When a user agent is to run a worker for a script with Worker or SharedWorker object worker, URL url, environment settings object outside settings, MessagePort outside port, and a WorkerOptions dictionary options, it must run the following steps.

  1. Let is shared be true if worker is a SharedWorker object, and false otherwise.

  2. Let owner be the relevant owner to add given outside settings.

  3. Let unsafeWorkerCreationTime be the unsafe shared current time.

  4. Let agent be the result of obtaining a dedicated/shared worker agent given outside settings and is shared. Run the rest of these steps in that agent.

  5. Let realm execution context be the result of creating a new realm given agent and the following customizations:

  6. Let worker global scope be the global object of realm execution context's Realm component.

    This is the DedicatedWorkerGlobalScope or SharedWorkerGlobalScope object created in the previous step.

  7. Set up a worker environment settings object with realm execution context, outside settings, and unsafeWorkerCreationTime, and let inside settings be the result.

  8. Set worker global scope's name to the value of options's name member.

  9. Append owner to worker global scope's owner set.

  10. If is shared is true, then:

    1. Set worker global scope's constructor origin to outside settings's origin.

    2. Set worker global scope's constructor url to url.

    3. Set worker global scope's type to the value of options's type member.

    4. Set worker global scope's credentials to the value of options's credentials member.

  11. Let destination be "sharedworker" if is shared is true, and "worker" otherwise.

  12. Obtain script by switching on the value of options's type member:

    "classic"
    Fetch a classic worker script given url, outside settings, destination, inside settings, and with onComplete and performFetch as defined below.
    "module"
    Fetch a module worker script graph given url, outside settings, destination, the value of the credentials member of options, inside settings, and with onComplete and performFetch as defined below.

    In both cases, let performFetch be the following perform the fetch hook given request, isTopLevel and processCustomFetchResponse:

    1. If isTopLevel is false, fetch request with processResponseConsumeBody set to processCustomFetchResponse, and abort these steps.

    2. Set request's reserved client to inside settings.
    3. Fetch request with processResponseConsumeBody set to the following steps given response response and null, failure, or a byte sequence bodyBytes:

      1. Set worker global scope's url to response's url.

      2. Initialize worker global scope's policy container given worker global scope, response, and inside settings.

      3. If the Run CSP initialization for a global object algorithm returns "Blocked" when executed upon worker global scope, set response to a network error. [CSP]

      4. If worker global scope's embedder policy's value is compatible with cross-origin isolation and is shared is true, then set agent's agent cluster's cross-origin isolation mode to "logical" or "concrete". The one chosen is implementation-defined.

        This really ought to be set when the agent cluster is created, which requires a redesign of this section.

      5. If the result of checking a global object's embedder policy with worker global scope, outside settings, and response is false, then set response to a network error.

      6. Set worker global scope's cross-origin isolated capability to true if agent's agent cluster's cross-origin isolation mode is "concrete".

      7. If is shared is false and owner's cross-origin isolated capability is false, then set worker global scope's cross-origin isolated capability to false.

      8. If is shared is false and response's url's scheme is "data", then set worker global scope's cross-origin isolated capability to false.

        This is a conservative default for now, while we figure out how workers in general, and data: URL workers in particular (which are cross-origin from their owner), will be treated in the context of permissions policies. See w3c/webappsec-permissions-policy issue #207 for more details.

      9. Run processCustomFetchResponse with response and bodyBytes.

    In both cases, let onComplete given script be the following steps:

    1. If script is null or if script's error to rethrow is non-null, then:

      1. Queue a global task on the DOM manipulation task source given worker's relevant global object to fire an event named error at worker.

      2. Run the environment discarding steps for inside settings.

      3. Abort these steps.

    2. Associate worker with worker global scope.

    3. Let inside port be a new MessagePort object in inside settings's realm.

    4. Associate inside port with worker global scope.

    5. Entangle outside port and inside port.

    6. Create a new WorkerLocation object and associate it with worker global scope.

    7. Closing orphan workers: Start monitoring the worker such that no sooner than it stops being a protected worker, and no later than it stops being a permissible worker, worker global scope's closing flag is set to true.

    8. Suspending workers: Start monitoring the worker, such that whenever worker global scope's closing flag is false and the worker is a suspendable worker, the user agent suspends execution of script in that worker until such time as either the closing flag switches to true or the worker stops being a suspendable worker.

    9. Set inside settings's execution ready flag.

    10. If script is a classic script, then run the classic script script. Otherwise, it is a module script; run the module script script.

      In addition to the usual possibilities of returning a value or failing due to an exception, this could be prematurely aborted by the terminate a worker algorithm defined below.

    11. Enable outside port's port message queue.

    12. If is shared is false, enable the port message queue of the worker's implicit port.

    13. If is shared is true, then queue a global task on DOM manipulation task source given worker global scope to fire an event named connect at worker global scope, using MessageEvent, with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing inside port, and the source attribute initialized to inside port.

    14. Enable the client message queue of the ServiceWorkerContainer object whose associated service worker client is worker global scope's relevant settings object.

    15. Event loop: Run the responsible event loop specified by inside settings until it is destroyed.

      The handling of events or the execution of callbacks by tasks run by the event loop might get prematurely aborted by the terminate a worker algorithm defined below.

      The worker processing model remains on this step until the event loop is destroyed, which happens after the closing flag is set to true, as described in the event loop processing model.

    16. Clear the worker global scope's map of active timers.

    17. Disentangle all the ports in the list of the worker's ports.

    18. Empty worker global scope's owner set.


When a user agent is to terminate a worker it must run the following steps in parallel with the worker's main loop (the "run a worker" processing model defined above):

  1. Set the worker's WorkerGlobalScope object's closing flag to true.

  2. If there are any tasks queued in the WorkerGlobalScope object's relevant agent's event loop's task queues, discard them without processing them.

  3. Abort the script currently running in the worker.

  4. If the worker's WorkerGlobalScope object is actually a DedicatedWorkerGlobalScope object (i.e. the worker is a dedicated worker), then empty the port message queue of the port that the worker's implicit port is entangled with.

User agents may invoke the terminate a worker algorithm when a worker stops being an active needed worker and the worker continues executing even after its closing flag was set to true.

10.2.5 Runtime script errors

Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error did not occur while handling a previous script error, the user agent will report it for the worker's WorkerGlobalScope object.

10.2.6 Creating workers

10.2.6.1 The AbstractWorker mixin
interface mixin AbstractWorker {
  attribute EventHandler onerror;
};

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the AbstractWorker interface:

Event handler Event handler event type
onerror

ServiceWorker/error_event

Support in all current engines.

Firefox44+Safari11.1+Chrome40+
Opera?Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

SharedWorker/error_event

Support in all current engines.

Firefox29+Safari16+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android33+Safari iOS16+Chrome AndroidNoWebView Android?Samsung Internet4.0–5.0Opera Android11–14

Worker/error_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
error
10.2.6.2 Script settings for workers

To set up a worker environment settings object, given a JavaScript execution context execution context, an environment settings object outside settings, and a number unsafeWorkerCreationTime:

  1. Let inherited origin be outside settings's origin.

  2. Let realm be the value of execution context's Realm component.

  3. Let worker global scope be realm's global object.

  4. Let settings object be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return execution context.

    The module map

    Return worker global scope's module map.

    The API base URL

    Return worker global scope's url.

    The origin

    Return a unique opaque origin if worker global scope's url's scheme is "data", and inherited origin otherwise.

    The policy container

    Return worker global scope's policy container.

    The cross-origin isolated capability

    Return worker global scope's cross-origin isolated capability.

    The time origin

    Return the result of coarsening unsafeWorkerCreationTime with worker global scope's cross-origin isolated capability.

  5. Set settings object's id to a new unique opaque string, creation URL to worker global scope's url, top-level creation URL to null, target browsing context to null, and active service worker to null.

  6. If worker global scope is a DedicatedWorkerGlobalScope object, then set settings object's top-level origin to outside settings's top-level origin.

  7. Otherwise, set settings object's top-level origin to an implementation-defined value.

    See Client-Side Storage Partitioning for the latest on properly defining this.

  8. Set realm's [[HostDefined]] field to settings object.

  9. Return settings object.

10.2.6.3 Dedicated workers and the Worker interface

Worker

Support in all current engines.

Firefox3.5+Safari4+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Exposed=(Window,DedicatedWorker,SharedWorker)]
interface Worker : EventTarget {
  constructor((TrustedScriptURL or USVString) scriptURL, optional WorkerOptions options = {});

  undefined terminate();

  undefined postMessage(any message, sequence<object> transfer);
  undefined postMessage(any message, optional StructuredSerializeOptions options = {});
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
};

dictionary WorkerOptions {
  WorkerType type = "classic";
  RequestCredentials credentials = "same-origin"; // credentials is only used if type is "module"
  DOMString name = "";
};

enum WorkerType { "classic", "module" };

Worker includes AbstractWorker;
worker = new Worker(scriptURL [, options ])

Worker/Worker

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+

Returns a new Worker object. scriptURL will be fetched and executed in the background, creating a new global environment for which worker represents the communication channel. options can be used to define the name of that global environment via the name option, primarily for debugging purposes. It can also ensure this new global environment supports JavaScript modules (specify type: "module"), and if that is specified, can also be used to specify how scriptURL is fetched through the credentials option.

worker.terminate()

Worker/terminate

Support in all current engines.

Firefox3.5+Safari4+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
Aborts worker's associated global environment.
worker.postMessage(message [, transfer ])

Worker/postMessage

Support in all current engines.

Firefox3.5+Safari4+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
worker.postMessage(message [, { transfer } ])

Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned.

The terminate() method, when invoked, must cause the terminate a worker algorithm to be run on the worker with which the object is associated.

Worker objects act as if they had an implicit MessagePort associated with them. This port is part of a channel that is set up when the worker is created, but it is not exposed. This object must never be garbage collected before the Worker object.

All messages received by that port must immediately be retargeted at the Worker object.

The postMessage(message, transfer) and postMessage(message, options) methods on Worker objects act as if, when invoked, they immediately invoked the respective postMessage(message, transfer) and postMessage(message, options) on the port, with the same arguments, and returned the same return value.

The postMessage() method's first argument can be structured data:

worker.postMessage({opcode: 'activate', device: 1938, parameters: [23, 102]});

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the Worker interface:

Event handler Event handler event type
onmessage message
onmessageerror messageerror

When the Worker(scriptURL, options) constructor is invoked, the user agent must run the following steps:

  1. Let compliantScriptURL be the result of invoking the Get Trusted Type compliant string algorithm with TrustedScriptURL, this's relevant global object, scriptURL, "Worker constructor", and "script".

  2. Let outside settings be the current settings object.

  3. Let worker URL be the result of encoding-parsing a URL given compliantScriptURL, relative to outside settings.

    Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin.

  4. If worker URL is failure, then throw a "SyntaxError" DOMException.

  5. Let worker be a new Worker object.

  6. Let outside port be a new MessagePort in outside settings's realm.

  7. Associate the outside port with worker.

  8. Run this step in parallel:

    1. Run a worker given worker, worker URL, outside settings, outside port, and options.

  9. Return worker.

10.2.6.4 Shared workers and the SharedWorker interface

SharedWorker

Support in all current engines.

Firefox29+Safari16+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android33+Safari iOS16+Chrome AndroidNoWebView Android?Samsung Internet4.0–5.0Opera Android11–14
[Exposed=Window]
interface SharedWorker : EventTarget {
  constructor((TrustedScriptURL or USVString) scriptURL, optional (DOMString or WorkerOptions) options = {});

  readonly attribute MessagePort port;
};
SharedWorker includes AbstractWorker;
sharedWorker = new SharedWorker(scriptURL [, name ])

SharedWorker/SharedWorker

Support in all current engines.

Firefox29+Safari16+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android33+Safari iOS16+Chrome AndroidNoWebView Android?Samsung Internet4.0–5.0Opera Android11–14

Returns a new SharedWorker object. scriptURL will be fetched and executed in the background, creating a new global environment for which sharedWorker represents the communication channel. name can be used to define the name of that global environment.

sharedWorker = new SharedWorker(scriptURL [, options ])

Returns a new SharedWorker object. scriptURL will be fetched and executed in the background, creating a new global environment for which sharedWorker represents the communication channel. options can be used to define the name of that global environment via the name option. It can also ensure this new global environment supports JavaScript modules (specify type: "module"), and if that is specified, can also be used to specify how scriptURL is fetched through the credentials option. Note that attempting to construct a shared worker with options whose type or credentials values mismatch an existing shared worker will cause the returned sharedWorker to fire an error event and not connect to the existing shared worker.

sharedWorker.port

SharedWorker/port

Support in all current engines.

Firefox29+Safari16+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android33+Safari iOS16+Chrome AndroidNoWebView Android?Samsung Internet4.0–5.0Opera Android11–14

Returns sharedWorker's MessagePort object which can be used to communicate with the global environment.

The port attribute must return the value it was assigned by the object's constructor. It represents the MessagePort for communicating with the shared worker.

A user agent has an associated shared worker manager which is the result of starting a new parallel queue.

Each user agent has a single shared worker manager for simplicity. Implementations could use one per origin; that would not be observably different and enables more concurrency.

When the SharedWorker(scriptURL, options) constructor is invoked:

  1. Let compliantScriptURL be the result of invoking the Get Trusted Type compliant string algorithm with TrustedScriptURL, this's relevant global object, scriptURL, "SharedWorker constructor", and "script".

  2. If options is a DOMString, set options to a new WorkerOptions dictionary whose name member is set to the value of options and whose other members are set to their default values.

  3. Let outside settings be the current settings object.

  4. Let urlRecord be the result of encoding-parsing a URL given compliantScriptURL, relative to outside settings.

    Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin.

  5. If urlRecord is failure, then throw a "SyntaxError" DOMException.

  6. Let worker be a new SharedWorker object.

  7. Let outside port be a new MessagePort in outside settings's realm.

  8. Assign outside port to the port attribute of worker.

  9. Let callerIsSecureContext be true if outside settings is a secure context; otherwise, false.

  10. Let outside storage key be the result of running obtain a storage key for non-storage purposes given outside settings.

  11. Enqueue the following steps to the shared worker manager:

    1. Let worker global scope be null.

    2. For each scope in the list of all SharedWorkerGlobalScope objects:

      1. Let worker storage key be the result of running obtain a storage key for non-storage purposes given scope's relevant settings object.

      2. If all of the following are true:

        then:

        1. Set worker global scope to scope.

        2. Break.

      data: URLs create a worker with an opaque origin. Both the constructor origin and constructor url are compared so the same data: URL can be used within an origin to get to the same SharedWorkerGlobalScope object, but cannot be used to bypass the same origin restriction.

    3. If worker global scope is not null, but the user agent has been configured to disallow communication between the worker represented by the worker global scope and the scripts whose settings object is outside settings, then set worker global scope to null.

      For example, a user agent could have a development mode that isolates a particular top-level traversable from all other pages, and scripts in that development mode could be blocked from connecting to shared workers running in the normal browser mode.

    4. If worker global scope is not null, then check if worker global scope's type and credentials match the options values. If not, queue a task to fire an event named error and abort these steps.

    5. If worker global scope is not null, then run these subsubsteps:

      1. Let settings object be the relevant settings object for worker global scope.

      2. Let workerIsSecureContext be true if settings object is a secure context; otherwise, false.

      3. If workerIsSecureContext is not callerIsSecureContext, then queue a task to fire an event named error at worker and abort these steps. [SECURE-CONTEXTS]

      4. Associate worker with worker global scope.

      5. Let inside port be a new MessagePort in settings object's realm.

      6. Entangle outside port and inside port.

      7. Queue a task, using the DOM manipulation task source, to fire an event named connect at worker global scope, using MessageEvent, with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing only inside port, and the source attribute initialized to inside port.

      8. Append the relevant owner to add given outside settings to worker global scope's owner set.

    6. Otherwise, in parallel, run a worker given worker, urlRecord, outside settings, outside port, and options.

  12. Return worker.

interface mixin NavigatorConcurrentHardware {
  readonly attribute unsigned long long hardwareConcurrency;
};
self.navigator.hardwareConcurrency

Navigator/hardwareConcurrency

Firefox48+Safari10.1–11Chrome37+
Opera?Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Navigator/hardwareConcurrency

Firefox48+Safari10.1–11Chrome37+
Opera?Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Returns the number of logical processors potentially available to the user agent.

(This is a tracking vector.) The navigator.hardwareConcurrency attribute's getter must return a number between 1 and the number of logical processors potentially available to the user agent. If this cannot be determined, the getter must return 1.

User agents should err toward exposing the number of logical processors available, using lower values only in cases where there are user-agent specific limits in place (such as a limitation on the number of workers that can be created) or when the user agent desires to limit fingerprinting possibilities.

10.3 APIs available to workers

10.3.1 Importing scripts and libraries

The importScripts(...urls) method steps are:

  1. Let urlStrings be « ».

  2. For each url of urls:

    1. Append the result of invoking the Get Trusted Type compliant string algorithm with TrustedScriptURL, this's relevant global object, url, "Worker importScripts", and "script" to urlStrings.

  3. Import scripts into worker global scope given this and urlStrings.

To import scripts into worker global scope, given a WorkerGlobalScope object worker global scope, a list of scalar value strings urls, and an optional perform the fetch hook performFetch:

  1. If worker global scope's type is "module", throw a TypeError exception.

  2. Let settings object be the current settings object.

  3. If urls is empty, return.

  4. Let urlRecords be « ».

  5. For each url of urls:

    1. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings object.

    2. If urlRecord is failure, then throw a "SyntaxError" DOMException.

    3. Append urlRecord to urlRecords.

  6. For each urlRecord of urlRecords:

    1. Fetch a classic worker-imported script given urlRecord and settings object, passing along performFetch if provided. If this succeeds, let script be the result. Otherwise, rethrow the exception.

    2. Run the classic script script, with the rethrow errors argument set to true.

      script will run until it either returns, fails to parse, fails to catch an exception, or gets prematurely aborted by the terminate a worker algorithm defined above.

      If an exception was thrown or if the script was prematurely aborted, then abort all these steps, letting the exception or aborting continue to be processed by the calling script.

Service Workers is an example of a specification that runs this algorithm with its own perform the fetch hook. [SW]

10.3.2 The WorkerNavigator interface

WorkerNavigator

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The navigator attribute of the WorkerGlobalScope interface must return an instance of the WorkerNavigator interface, which represents the identity and state of the user agent (the client):

[Exposed=Worker]
interface WorkerNavigator {};
WorkerNavigator includes NavigatorID;
WorkerNavigator includes NavigatorLanguage;
WorkerNavigator includes NavigatorOnLine;
WorkerNavigator includes NavigatorConcurrentHardware;

10.3.3 The WorkerLocation interface

WorkerLocation

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

WorkerLocation/toString

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android14+
[Exposed=Worker]
interface WorkerLocation {
  stringifier readonly attribute USVString href;
  readonly attribute USVString origin;
  readonly attribute USVString protocol;
  readonly attribute USVString host;
  readonly attribute USVString hostname;
  readonly attribute USVString port;
  readonly attribute USVString pathname;
  readonly attribute USVString search;
  readonly attribute USVString hash;
};

A WorkerLocation object has an associated WorkerGlobalScope object (a WorkerGlobalScope object).

WorkerLocation/href

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The href getter steps are to return this's WorkerGlobalScope object's url, serialized.

WorkerLocation/origin

Support in all current engines.

Firefox29+Safari10+Chrome38+
Opera?Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The origin getter steps are to return the serialization of this's WorkerGlobalScope object's url's origin.

WorkerLocation/protocol

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The protocol getter steps are to return this's WorkerGlobalScope object's url's scheme, followed by ":".

WorkerLocation/host

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The host getter steps are:

  1. Let url be this's WorkerGlobalScope object's url.

  2. If url's host is null, return the empty string.

  3. If url's port is null, return url's host, serialized.

  4. Return url's host, serialized, followed by ":" and url's port, serialized.

WorkerLocation/hostname

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The hostname getter steps are:

  1. Let host be this's WorkerGlobalScope object's url's host.

  2. If host is null, return the empty string.

  3. Return host, serialized.

WorkerLocation/port

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The port getter steps are:

  1. Let port be this's WorkerGlobalScope object's url's port.

  2. If port is null, return the empty string.

  3. Return port, serialized.

WorkerLocation/pathname

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The pathname getter steps are to return the result of URL path serializing this's WorkerGlobalScope object's url.

WorkerLocation/search

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The search getter steps are:

  1. Let query be this's WorkerGlobalScope object's url's query.

  2. If query is either null or the empty string, return the empty string.

  3. Return "?", followed by query.

WorkerLocation/hash

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The hash getter steps are:

  1. Let fragment be this's WorkerGlobalScope object's url's fragment.

  2. If fragment is either null or the empty string, return the empty string.

  3. Return "#", followed by fragment.

11 Worklets

11.1 Introduction

This section is non-normative.

Worklets are a piece of specification infrastructure which can be used for running scripts independent of the main JavaScript execution environment, while not requiring any particular implementation model.

The worklet infrastructure specified here cannot be used directly by web developers. Instead, other specifications build upon it to create directly-usable worklet types, specialized for running in particular parts of the browser implementation pipeline.

11.1.1 Motivations

This section is non-normative.

Allowing extension points to rendering, or other sensitive parts of the implementation pipeline such as audio output, is difficult. If extension points were done with full access to the APIs available on Window, engines would need to abandon previously-held assumptions for what could happen in the middle of those phases. For example, during the layout phase, rendering engines assume that no DOM will be modified.

Additionally, defining extension points in the Window environment would restrict user agents to performing work in the same thread as the Window object. (Unless implementations added complex, high-overhead infrastructure to allow thread-safe APIs, as well as thread-joining guarantees.)

Worklets are designed to allow extension points, while keeping guarantees that user agents currently rely on. This is done through new global environments, based on subclasses of WorkletGlobalScope.

Worklets are similar to web workers. However, they:

As worklets have relatively high overhead, they are best used sparingly. Due to this, a given WorkletGlobalScope is expected to be shared between multiple separate scripts. (This is similar to how a single Window is shared between multiple separate scripts.)

Worklets are a general technology that serve different use cases. Some worklets, such as those defined in CSS Painting API, provide extension points intended for stateless, idempotent, and short-running computations, which have special considerations as described in the next couple of sections. Others, such as those defined in Web Audio API, are used for stateful, long-running operations. [CSSPAINT] [WEBAUDIO]

11.1.2 Code idempotence

Some specifications which use worklets are intended to allow user agents to parallelize work over multiple threads, or to move work between threads as required. In these specifications, user agents might invoke methods on a web-developer-provided class in an implementation-defined order.

As a result of this, to prevent interoperability issues, authors who register classes on such WorkletGlobalScopes should make their code idempotent. That is, a method or set of methods on the class should produce the same output given a particular input.

This specification uses the following techniques in order to encourage authors to write code in an idempotent way:

Together, these restrictions help prevent two different scripts from sharing state using properties of the global object.

Additionally, specifications which use worklets and intend to allow implementation-defined behavior must obey the following:

11.1.3 Speculative evaluation

Some specifications which use worklets can invoke methods on a web-developer-provided class based on the state of the user agent. To increase concurrency between threads, a user agent may invoke a method speculatively, based on potential future states.

In these specifications, user agents might invoke such methods at any time, and with any arguments, not just ones corresponding to the current state of the user agent. The results of such speculative evaluations are not displayed immediately, but can be cached for use if the user agent state matches the speculated state. This can increase the concurrency between the user agent and worklet threads.

As a result of this, to prevent interoperability risks between user agents, authors who register classes on such WorkletGlobalScopes should make their code stateless. That is, the only effect of invoking a method should be its result, and not any side effects such as updating mutable state.

The same techniques which encourage code idempotence also encourage authors to write stateless code.

11.2 Examples

This section is non-normative.

For these examples, we'll use a fake worklet. The Window object provides two Worklet instances, which each run code in their own collection of FakeWorkletGlobalScopes:

partial interface Window {
  [SameObject, SecureContext] readonly attribute Worklet fakeWorklet1;
  [SameObject, SecureContext] readonly attribute Worklet fakeWorklet2;
};

Each Window has two Worklet instances, fake worklet 1 and fake worklet 2. Both of these have their worklet global scope type set to FakeWorkletGlobalScope, and their worklet destination type set to "fakeworklet". User agents should create at least two FakeWorkletGlobalScope instances per worklet.

"fakeworklet" is not actually a valid destination per Fetch. But this illustrates how real worklets would generally have their own worklet-type-specific destination. [FETCH]

The fakeWorklet1 getter steps are to return this's fake worklet 1.

The fakeWorklet2 getter steps are to return this's fake worklet 2.


[Global=(Worklet,FakeWorklet),
 Exposed=FakeWorklet,
 SecureContext]
interface FakeWorkletGlobalScope : WorkletGlobalScope {
  undefined registerFake(DOMString type, Function classConstructor);
};

Each FakeWorkletGlobalScope has a registered class constructors map, which is an ordered map, initially empty.

The registerFake(type, classConstructor) method steps are to set this's registered class constructors map[type] to classConstructor.

11.2.1 Loading scripts

This section is non-normative.

To load scripts into fake worklet 1, a web developer would write:

window.fakeWorklet1.addModule('script1.mjs');
window.fakeWorklet1.addModule('script2.mjs');

Note that which script finishes fetching and runs first is dependent on network timing: it could be either script1.mjs or script2.mjs. This generally won't matter for well-written scripts intended to be loaded in worklets, if they follow the suggestions about preparing for speculative evaluation.

If a web developer wants to perform a task only after the scripts have successfully run and loaded into some worklets, they could write:

Promise.all([
    window.fakeWorklet1.addModule('script1.mjs'),
    window.fakeWorklet2.addModule('script2.mjs')
]).then(() => {
    // Do something which relies on those scripts being loaded.
});

Another important point about script-loading is that loaded scripts can be run in multiple WorkletGlobalScopes per Worklet, as discussed in the section on code idempotence. In particular, the specification above for fake worklet 1 and fake worklet 2 require this. So, consider a scenario such as the following:

// script.mjs
console.log("Hello from a FakeWorkletGlobalScope!");
// app.mjs
window.fakeWorklet1.addModule("script.mjs");

This could result in output such as the following from a user agent's console:

[fakeWorklet1#1] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#4] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#2] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#3] Hello from a FakeWorkletGlobalScope!

If the user agent at some point decided to kill and restart the third instance of FakeWorkletGlobalScope, the console would again print [fakeWorklet1#3] Hello from a FakeWorkletGlobalScope! when this occurs.

11.2.2 Registering a class and invoking its methods

This section is non-normative.

Let's say that one of the intended usages of our fake worklet by web developers is to allow them to customize the highly-complex process of boolean negation. They might register their customization as follows:

// script.mjs
registerFake('negation-processor', class {
  process(arg) {
    return !arg;
  }
});
// app.mjs
window.fakeWorklet1.addModule("script.mjs");

To make use of such registered classes, the specification for fake worklets could define a find the opposite of true algorithm, given a Worklet worklet:

  1. Optionally, create a worklet global scope for worklet.

  2. Let workletGlobalScope be one of worklet's global scopes, chosen in an implementation-defined manner.

  3. Let classConstructor be workletGlobalScope's registered class constructors map["negation-processor"].

  4. Let classInstance be the result of constructing classConstructor, with no arguments.

  5. Let function be Get(classInstance, "process"). Rethrow any exceptions.

  6. Let callback be the result of converting function to a Web IDL Function instance.

  7. Return the result of invoking callback with « true » and "rethrow", and with callback this value set to classInstance.

Another, perhaps better, specification architecture would be to extract the "process" property and convert it into a Function at registration time, as part of the registerFake() method steps.

11.3 Infrastructure

11.3.1 The global scope

Subclasses of WorkletGlobalScope are used to create global objects wherein code loaded into a particular Worklet can execute.

[Exposed=Worklet, SecureContext]
interface WorkletGlobalScope {};

Other specifications are intended to subclass WorkletGlobalScope, adding APIs to register a class, as well as other APIs specific for their worklet type.

Each WorkletGlobalScope has an associated module map. It is a module map, initially empty.

11.3.1.1 Agents and event loops

This section is non-normative.

Each WorkletGlobalScope is contained in its own worklet agent, which has its corresponding event loop. However, in practice, implementation of these agents and event loops is expected to be different from most others.

A worklet agent exists for each WorkletGlobalScope since, in theory, an implementation could use a separate thread for each WorkletGlobalScope instance, and allowing this level of parallelism is best done using agents. However, because their [[CanBlock]] value is false, there is no requirement that agents and threads are one-to-one. This allows implementations the freedom to execute scripts loaded into a worklet on any thread, including one running code from other agents with [[CanBlock]] of false, such as the thread of a similar-origin window agent ("the main thread"). Contrast this with dedicated worker agents, whose true value for [[CanBlock]] effectively requires them to get a dedicated operating system thread.

Worklet event loops are also somewhat special. They are only used for tasks associated with addModule(), tasks wherein the user agent invokes author-defined methods, and microtasks. Thus, even though the event loop processing model specifies that all event loops run continuously, implementations can achieve observably-equivalent results using a simpler strategy, which just invokes author-provided methods and then relies on that process to perform a microtask checkpoint.

11.3.1.2 Creation and termination

To create a worklet global scope for a Worklet worklet:

  1. Let outsideSettings be worklet's relevant settings object.

  2. Let agent be the result of obtaining a worklet agent given outsideSettings. Run the rest of these steps in that agent.

  3. Let realmExecutionContext be the result of creating a new realm given agent and the following customizations:

  4. Let workletGlobalScope be the global object of realmExecutionContext's Realm component.

  5. Let insideSettings be the result of setting up a worklet environment settings object given realmExecutionContext and outsideSettings.

  6. Let pendingAddedModules be a clone of worklet's added modules list.

  7. Let runNextAddedModule be the following steps:

    1. If pendingAddedModules is not empty, then:

      1. Let moduleURL be the result of dequeueing from pendingAddedModules.

      2. Fetch a worklet script graph given moduleURL, insideSettings, worklet's worklet destination type, what credentials mode?, insideSettings, worklet's module responses map, and with the following steps given script:

        This will not actually perform a network request, as it will just reuse responses from worklet's module responses map. The main purpose of this step is to create a new workletGlobalScope-specific module script from the response.

        1. Assert: script is not null, since the fetch succeeded and the source text was successfully parsed when worklet's module responses map was initially populated with moduleURL.

        2. Run a module script given script.

        3. Run runNextAddedModule.

      3. Abort these steps.
    2. Append workletGlobalScope to outsideSettings's global object's associated Document's worklet global scopes.

    3. Append workletGlobalScope to worklet's global scopes.

    4. Run the responsible event loop specified by insideSettings.

  8. Run runNextAddedModule.

To terminate a worklet global scope given a WorkletGlobalScope workletGlobalScope:

  1. Let eventLoop be workletGlobalScope's relevant agent's event loop.

  2. If there are any tasks queued in eventLoop's task queues, discard them without processing them.

  3. Wait for eventLoop to complete the currently running task.

  4. If the previous step doesn't complete within an implementation-defined period of time, then abort the script currently running in the worklet.

  5. Destroy eventLoop.

  6. Remove workletGlobalScope from the global scopes of the Worklet whose global scopes contains workletGlobalScope.

  7. Remove workletGlobalScope from the worklet global scopes of the Document whose worklet global scopes contains workletGlobalScope.

11.3.1.3 Script settings for worklets

To set up a worklet environment settings object, given a JavaScript execution context executionContext and an environment settings object outsideSettings:

  1. Let origin be a unique opaque origin.

  2. Let inheritedAPIBaseURL be outsideSettings's API base URL.

  3. Let inheritedPolicyContainer be a clone of outsideSettings's policy container.

  4. Let realm be the value of executionContext's Realm component.

  5. Let workletGlobalScope be realm's global object.

  6. Let settingsObject be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return executionContext.

    The module map

    Return workletGlobalScope's module map.

    The API base URL

    Return inheritedAPIBaseURL.

    Unlike workers or other globals derived from a single resource, worklets have no primary resource; instead, multiple scripts, each with their own URL, are loaded into the global scope via worklet.addModule(). So this API base URL is rather unlike that of other globals. However, so far this doesn't matter, as no APIs available to worklet code make use of the API base URL.

    The origin

    Return origin.

    The policy container

    Return inheritedPolicyContainer.

    The cross-origin isolated capability

    Return TODO.

    The time origin

    Assert: this algorithm is never called, because the time origin is not available in a worklet context.

  7. Set settingsObject's id to a new unique opaque string, creation URL to inheritedAPIBaseURL, top-level creation URL to null, top-level origin to outsideSettings's top-level origin, target browsing context to null, and active service worker to null.

  8. Set realm's [[HostDefined]] field to settingsObject.

  9. Return settingsObject.

11.3.2 The Worklet class

Worklet

Support in all current engines.

Firefox76+Safari14.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The Worklet class provides the capability to add module scripts into its associated WorkletGlobalScopes. The user agent can then create classes registered on the WorkletGlobalScopes and invoke their methods.

[Exposed=Window, SecureContext]
interface Worklet {
  [NewObject] Promise<undefined> addModule(USVString moduleURL, optional WorkletOptions options = {});
};

dictionary WorkletOptions {
  RequestCredentials credentials = "same-origin";
};

Specifications that create Worklet instances must specify the following for a given instance:

await worklet.addModule(moduleURL[, { credentials }])

Worklet/addModule

Support in all current engines.

Firefox76+Safari14.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Loads and executes the module script given by moduleURL into all of worklet's global scopes. It can also create additional global scopes as part of this process, depending on the worklet type. The returned promise will fulfill once the script has been successfully loaded and run in all global scopes.

The credentials option can be set to a credentials mode to modify the script-fetching process. It defaults to "same-origin".

Any failures in fetching the script or its dependencies will cause the returned promise to be rejected with an "AbortError" DOMException. Any errors in parsing the script or its dependencies will cause the returned promise to be rejected with the exception generated during parsing.

A Worklet has a list of global scopes, which contains instances of the Worklet's worklet global scope type. It is initially empty.

A Worklet has an added modules list, which is a list of URLs, initially empty. Access to this list should be thread-safe.

A Worklet has a module responses map, which is an ordered map from URLs to either "fetching" or tuples consisting of a response and either null, failure, or a byte sequence representing the response body. This map is initially empty, and access to it should be thread-safe.

The added modules list and module responses map exist to ensure that WorkletGlobalScopes created at different times get equivalent module scripts run in them, based on the same source text. This allows the creation of additional WorkletGlobalScopes to be transparent to the author.

In practice, user agents are not expected to implement these data structures, and the algorithms that consult them, using thread-safe programming techniques. Instead, when addModule() is called, user agents can fetch the module graph on the main thread, and send the fetched source text (i.e., the important data contained in the module responses map) to each thread which has a WorkletGlobalScope.

Then, when a user agent creates a new WorkletGlobalScope for a given Worklet, it can simply send the map of fetched source text and the list of entry points from the main thread to the thread containing the new WorkletGlobalScope.

The addModule(moduleURL, options) method steps are:

  1. Let outsideSettings be the relevant settings object of this.

  2. Let moduleURLRecord be the result of encoding-parsing a URL given moduleURL, relative to outsideSettings.

  3. If moduleURLRecord is failure, then return a promise rejected with a "SyntaxError" DOMException.

  4. Let promise be a new promise.

  5. Run the following steps in parallel:

    1. If this's global scopes is empty, then:

      1. Create a worklet global scope given this.

      2. Optionally, create additional global scope instances given this, depending on the specific worklet in question and its specification.

      3. Wait for all steps of the creation process(es) — including those taking place within the worklet agents — to complete, before moving on.

    2. Let pendingTasks be this's global scopes's size.

    3. Let addedSuccessfully be false.

    4. For each workletGlobalScope of this's global scopes, queue a global task on the networking task source given workletGlobalScope to fetch a worklet script graph given moduleURLRecord, outsideSettings, this's worklet destination type, options["credentials"], workletGlobalScope's relevant settings object, this's module responses map, and the following steps given script:

      Only the first of these fetches will actually perform a network request; the ones for other WorkletGlobalScopes will reuse responses from this's module responses map.

      1. If script is null, then:

        1. Queue a global task on the networking task source given this's relevant global object to perform the following steps:

          1. If pendingTasks is not −1, then:

            1. Set pendingTasks to −1.

            2. Reject promise with an "AbortError" DOMException.

        2. Abort these steps.

      2. If script's error to rethrow is not null, then:

        1. Queue a global task on the networking task source given this's relevant global object to perform the following steps:

          1. If pendingTasks is not −1, then:

            1. Set pendingTasks to −1.

            2. Reject promise with script's error to rethrow.

        2. Abort these steps.

      3. If addedSuccessfully is false, then:

        1. Append moduleURLRecord to this's added modules list.

        2. Set addedSuccessfully to true.

      4. Run a module script given script.

      5. Queue a global task on the networking task source given this's relevant global object to perform the following steps:

        1. If pendingTasks is not −1, then:

          1. Set pendingTasks to pendingTasks − 1.

          2. If pendingTasks is 0, then resolve promise.

  6. Return promise.

11.3.3 The worklet's lifetime

The lifetime of a Worklet has no special considerations; it is tied to the object it belongs to, such as the Window.

Each Document has a worklet global scopes, which is a set of WorkletGlobalScopes, initially empty.

The lifetime of a WorkletGlobalScope is, at a minimum, tied to the Document whose worklet global scopes contain it. In particular, destroying the Document will terminate the corresponding WorkletGlobalScope and allow it to be garbage-collected.

Additionally, user agents may, at any time, terminate a given WorkletGlobalScope, unless the specification defining the corresponding worklet type says otherwise. For example, they might terminate them if the worklet agent's event loop has no tasks queued, or if the user agent has no pending operations planning to make use of the worklet, or if the user agent detects abnormal operations such as infinite loops or callbacks exceeding imposed time limits.

Finally, specifications for specific worklet types can give more specific details on when to create WorkletGlobalScopes for a given worklet type. For example, they might create them during specific processes that call upon worklet code, as in the example.

12 Web storage

Web_Storage_API

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Web_Storage_API/Using_the_Web_Storage_API

12.1 Introduction

This section is non-normative.

This specification introduces two related mechanisms, similar to HTTP session cookies, for storing name-value pairs on the client side. [COOKIES]

The first is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.

Cookies don't really handle this case well. For example, a user could be buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same flight without noticing.

To address this, this specification introduces the sessionStorage getter. Sites can add data to the session storage, and it will be accessible to any page from the same site opened in that window.

For example, a page could have a checkbox that the user ticks to indicate that they want insurance:

<label>
 <input type="checkbox" onchange="sessionStorage.insurance = checked ? 'true' : ''">
  I want insurance on this trip.
</label>

A later page could then check, from script, whether the user had checked the checkbox or not:

if (sessionStorage.insurance) { ... }

If the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object.

The second storage mechanism is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, web applications might wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.

Again, cookies do not handle this case well, because they are transmitted with every request.

The localStorage getter is used to access a page's local storage area.

The site at example.com can display a count of how many times the user has loaded its page by putting the following at the bottom of its page:

<p>
  You have viewed this page
  <span id="count">an untold number of</span>
  time(s).
</p>
<script>
  if (!localStorage.pageLoadCount)
    localStorage.pageLoadCount = 0;
  localStorage.pageLoadCount = parseInt(localStorage.pageLoadCount) + 1;
  document.getElementById('count').textContent = localStorage.pageLoadCount;
</script>

Each site has its own separate storage area.

The localStorage getter provides access to shared state. This specification does not define the interaction with other agent clusters in a multiprocess user agent, and authors are encouraged to assume that there is no locking mechanism. A site could, for instance, try to read the value of a key, increment its value, then write it back out, using the new value as a unique identifier for the session; if the site does this twice in two different browser windows at the same time, it might end up using the same "unique" identifier for both sessions, with potentially disastrous effects.

12.2 The API

Storage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

12.2.1 The Storage interface

[Exposed=Window]
interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString? getItem(DOMString key);
  setter undefined setItem(DOMString key, DOMString value);
  deleter undefined removeItem(DOMString key);
  undefined clear();
};
storage.length

Storage/length

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Returns the number of key/value pairs.

storage.key (n)

Storage/key

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs.

value = storage.getItem (key)

Storage/getItem

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
value = storage[key]

Returns the current value associated with the given key, or null if the given key does not exist.

storage.setItem (key, value)

Storage/setItem

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
storage[key] = value

Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.

Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)

Dispatches a storage event on Window objects holding an equivalent Storage object.

storage.removeItem (key)

Storage/removeItem

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
delete storage[key]

Removes the key/value pair with the given key, if a key/value pair with the given key exists.

Dispatches a storage event on Window objects holding an equivalent Storage object.

storage.clear()

Storage/clear

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Removes all key/value pairs, if there are any.

Dispatches a storage event on Window objects holding an equivalent Storage object.

A Storage object has an associated:

map
A storage proxy map.
type
"local" or "session".

To reorder a Storage object storage, reorder storage's map's entries in an implementation-defined manner.

Unfortunate as it is, iteration order is not defined and can change upon most mutations.

To broadcast a Storage object storage, given a key, oldValue, and newValue, run these steps:

  1. Let thisDocument be storage's relevant global object's associated Document.

  2. Let url be thisDocument's URL.

  3. Let remoteStorages be all Storage objects excluding storage whose:

    and, if type is "session", whose relevant settings object's associated Document's node navigable's traversable navigable is thisDocument's node navigable's traversable navigable.

  4. For each remoteStorage of remoteStorages: queue a global task on the DOM manipulation task source given remoteStorage's relevant global object to fire an event named storage at remoteStorage's relevant global object, using StorageEvent, with key initialized to key, oldValue initialized to oldValue, newValue initialized to newValue, url initialized to url, and storageArea initialized to remoteStorage.

    The Document object associated with the resulting task is not necessarily fully active, but events fired on such objects are ignored by the event loop until the Document becomes fully active again.


The length getter steps are to return this's map's size.

The key(index) method steps are:

  1. If index is greater than or equal to this's map's size, then return null.

  2. Let keys be the result of running get the keys on this's map.

  3. Return keys[index].

The supported property names on a Storage object storage are the result of running get the keys on storage's map.

The getItem(key) method steps are:

  1. If this's map[key] does not exist, then return null.

  2. Return this's map[key].

The setItem(key, value) method are:

  1. Let oldValue be null.

  2. Let reorder be true.

  3. If this's map[key] exists:

    1. Set oldValue to this's map[key].

    2. If oldValue is value, then return.

    3. Set reorder to false.

  4. If value cannot be stored, then throw a "QuotaExceededError" DOMException exception.

  5. Set this's map[key] to value.

  6. If reorder is true, then reorder this.

  7. Broadcast this with key, oldValue, and value.

The removeItem(key) method steps are:

  1. If this's map[key] does not exist, then return null.

  2. Set oldValue to this's map[key].

  3. Remove this's map[key].

  4. Reorder this.

  5. Broadcast this with key, oldValue, and null.

The clear() method steps are:

  1. Clear this's map.

  2. Broadcast this with null, null, and null.

12.2.2 The sessionStorage getter

interface mixin WindowSessionStorage {
  readonly attribute Storage sessionStorage;
};
Window includes WindowSessionStorage;
window.sessionStorage

Window/sessionStorage

Support in all current engines.

Firefox2+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Returns the Storage object associated with that window's origin's session storage area.

Throws a "SecurityError" DOMException if the Document's origin is an opaque origin or if the request violates a policy decision (e.g., if the user agent is configured to not allow the page to persist data).

A Document object has an associated session storage holder, which is null or a Storage object. It is initially null.

(This is a tracking vector.) The sessionStorage getter steps are:

  1. If this's associated Document's session storage holder is non-null, then return this's associated Document's session storage holder.

  2. Let map be the result of running obtain a session storage bottle map with this's relevant settings object and "sessionStorage".

  3. If map is failure, then throw a "SecurityError" DOMException.

  4. Let storage be a new Storage object whose map is map.

  5. Set this's associated Document's session storage holder to storage.

  6. Return storage.

After creating a new auxiliary browsing context and document, the session storage is copied over.

12.2.3 The localStorage getter

interface mixin WindowLocalStorage {
  readonly attribute Storage localStorage;
};
Window includes WindowLocalStorage;
window.localStorage

Window/localStorage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11+

Returns the Storage object associated with window's origin's local storage area.

Throws a "SecurityError" DOMException if the Document's origin is an opaque origin or if the request violates a policy decision (e.g., if the user agent is configured to not allow the page to persist data).

A Document object has an associated local storage holder, which is null or a Storage object. It is initially null.

(This is a tracking vector.) The localStorage getter steps are:

  1. If this's associated Document's local storage holder is non-null, then return this's associated Document's local storage holder.

  2. Let map be the result of running obtain a local storage bottle map with this's relevant settings object and "localStorage".

  3. If map is failure, then throw a "SecurityError" DOMException.

  4. Let storage be a new Storage object whose map is map.

  5. Set this's associated Document's local storage holder to storage.

  6. Return storage.

12.2.4 The StorageEvent interface

StorageEvent

Support in all current engines.

Firefox13+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface StorageEvent : Event {
  constructor(DOMString type, optional StorageEventInit eventInitDict = {});

  readonly attribute DOMString? key;
  readonly attribute DOMString? oldValue;
  readonly attribute DOMString? newValue;
  readonly attribute USVString url;
  readonly attribute Storage? storageArea;

  undefined initStorageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional DOMString? key = null, optional DOMString? oldValue = null, optional DOMString? newValue = null, optional USVString url = "", optional Storage? storageArea = null);
};

dictionary StorageEventInit : EventInit {
  DOMString? key = null;
  DOMString? oldValue = null;
  DOMString? newValue = null;
  USVString url = "";
  Storage? storageArea = null;
};
event.key

Returns the key of the storage item being changed.

event.oldValue

Returns the old value of the key of the storage item whose value is being changed.

event.newValue

Returns the new value of the key of the storage item whose value is being changed.

event.url

Returns the URL of the document whose storage item changed.

event.storageArea

Returns the Storage object that was affected.

The key, oldValue, newValue, url, and storageArea attributes must return the values they were initialized to.

The initStorageEvent(type, bubbles, cancelable, key, oldValue, newValue, url, storageArea) method must initialize the event in a manner analogous to the similarly-named initEvent() method. [DOM]

12.3 Privacy

12.3.1 User tracking

A third-party advertiser (or any entity capable of getting content distributed to multiple sites) could use a unique identifier stored in its local storage area to track a user across multiple sessions, building a profile of the user's interests to allow for highly targeted advertising. In conjunction with a site that is aware of the user's real identity (for example an e-commerce site that requires authenticated credentials), this could allow oppressive groups to target individuals with greater accuracy than in a world with purely anonymous web usage.

There are a number of techniques that can be used to mitigate the risk of user tracking:

Blocking third-party storage

User agents may restrict access to the localStorage objects to scripts originating at the domain of the active document of the top-level traversable, for instance denying access to the API for pages from other domains running in iframes.

Expiring stored data

User agents may, possibly in a manner configured by the user, automatically delete stored data after a period of time.

For example, a user agent could be configured to treat third-party local storage areas as session-only storage, deleting the data once the user had closed all the navigables that could access it.

This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when they authenticate with the site itself (e.g. by making a purchase or logging in to a service).

However, this also reduces the usefulness of the API as a long-term storage mechanism. It can also put the user's data at risk, if the user does not fully understand the implications of data expiration.

Treating persistent storage as cookies

If users attempt to protect their privacy by clearing cookies without also clearing data stored in the local storage area, sites can defeat those attempts by using the two features as redundant backup for each other. User agents should present the interfaces for clearing these in a way that helps users to understand this possibility and enables them to delete data in all persistent storage features simultaneously. [COOKIES]

Site-specific safelisting of access to local storage areas

User agents may allow sites to access session storage areas in an unrestricted manner, but require the user to authorize access to local storage areas.

Origin-tracking of stored data

User agents may record the origins of sites that contained content from third-party origins that caused data to be stored.

If this information is then used to present the view of data currently in persistent storage, it would allow the user to make informed decisions about which parts of the persistent storage to prune. Combined with a blocklist ("delete this data and prevent this domain from ever storing data again"), the user can restrict the use of persistent storage to sites that they trust.

Shared blocklists

User agents may allow users to share their persistent storage domain blocklists.

This would allow communities to act together to protect their privacy.

While these suggestions prevent trivial use of this API for user tracking, they do not block it altogether. Within a single domain, a site can continue to track the user during a session, and can then pass all this information to the third party along with any identifying information (names, credit card numbers, addresses) obtained by the site. If a third party cooperates with multiple sites to obtain such information, a profile can still be created.

However, user tracking is to some extent possible even with no cooperation from the user agent whatsoever, for instance by using session identifiers in URLs, a technique already commonly used for innocuous purposes but easily repurposed for user tracking (even retroactively). This information can then be shared with other sites, using visitors' IP addresses and other user-specific data (e.g. user-agent headers and configuration settings) to combine separate sessions into coherent user profiles.

12.3.2 Sensitivity of data

User agents should treat persistently stored data as potentially sensitive; it's quite possible for emails, calendar appointments, health records, or other confidential documents to be stored in this mechanism.

To this end, user agents should ensure that when deleting data, it is promptly deleted from the underlying storage.

12.4 Security

12.4.1 DNS spoofing attacks

Because of the potential for DNS spoofing attacks, one cannot guarantee that a host claiming to be in a certain domain really is from that domain. To mitigate this, pages can use TLS. Pages using TLS can be sure that only the user, software working on behalf of the user, and other pages using TLS that have certificates identifying them as being from the same domain, can access their storage areas.

12.4.2 Cross-directory attacks

Different authors sharing one host name, for example users hosting content on the now defunct geocities.com, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore urged to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.

Even if a path-restriction feature was made available, the usual DOM scripting security model would make it trivial to bypass this protection and access the data from any path.

12.4.3 Implementation risks

The two primary risks when implementing these persistent storage features are letting hostile sites read information from other domains, and letting hostile sites write information that is then read from other domains.

Letting third-party sites read data that is not supposed to be read from their domain causes information leakage. For example, a user's shopping wishlist on one domain could be used by another domain for targeted advertising; or a user's work-in-progress confidential documents stored by a word-processing site could be examined by the site of a competing company.

Letting third-party sites write data to the persistent storage of other domains can result in information spoofing, which is equally dangerous. For example, a hostile site could add items to a user's wishlist; or a hostile site could set a user's session identifier to a known ID that the hostile site can then use to track the user's actions on the victim site.

Thus, strictly following the origin model described in this specification is important for user security.

13 The HTML syntax

This section only describes the rules for resources labeled with an HTML MIME type. Rules for XML resources are discussed in the section below entitled "The XML syntax".

13.1 Writing HTML documents

This section only applies to documents, authoring tools, and markup generators. In particular, it does not apply to conformance checkers; conformance checkers must use the requirements given in the next section ("parsing HTML documents").

Documents must consist of the following parts, in the given order:

  1. Optionally, a single U+FEFF BYTE ORDER MARK (BOM) character.
  2. Any number of comments and ASCII whitespace.
  3. A DOCTYPE.
  4. Any number of comments and ASCII whitespace.
  5. The document element, in the form of an html element.
  6. Any number of comments and ASCII whitespace.

The various types of content mentioned above are described in the next few sections.

In addition, there are some restrictions on how character encoding declarations are to be serialized, as discussed in the section on that topic.

ASCII whitespace before the html element, at the start of the html element and before the head element, will be dropped when the document is parsed; ASCII whitespace after the html element will be parsed as if it were at the end of the body element. Thus, ASCII whitespace around the document element does not round-trip.

It is suggested that newlines be inserted after the DOCTYPE, after any comments that are before the document element, after the html element's start tag (if it is not omitted), and after any comments that are inside the html element but before the head element.

Many strings in the HTML syntax (e.g. the names of elements and their attributes) are case-insensitive, but only for ASCII upper alphas and ASCII lower alphas. For convenience, in this section this is just referred to as "case-insensitive".

13.1.1 The DOCTYPE

A DOCTYPE is a required preamble.

DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.

A DOCTYPE must consist of the following components, in this order:

  1. A string that is an ASCII case-insensitive match for the string "<!DOCTYPE".
  2. One or more ASCII whitespace.
  3. A string that is an ASCII case-insensitive match for the string "html".
  4. Optionally, a DOCTYPE legacy string.
  5. Zero or more ASCII whitespace.
  6. A U+003E GREATER-THAN SIGN character (>).

In other words, <!DOCTYPE html>, case-insensitively.


For the purposes of HTML generators that cannot output HTML markup with the short DOCTYPE "<!DOCTYPE html>", a DOCTYPE legacy string may be inserted into the DOCTYPE (in the position defined above). This string must consist of:

  1. One or more ASCII whitespace.
  2. A string that is an ASCII case-insensitive match for the string "SYSTEM".
  3. One or more ASCII whitespace.
  4. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the quote mark).
  5. The literal string "about:legacy-compat".
  6. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e. the same character as in the earlier step labeled quote mark).

In other words, <!DOCTYPE html SYSTEM "about:legacy-compat"> or <!DOCTYPE html SYSTEM 'about:legacy-compat'>, case-insensitively except for the part in single or double quotes.

The DOCTYPE legacy string should not be used unless the document is generated from a system that cannot output the shorter string.

13.1.2 Elements

There are six different kinds of elements: void elements, the template element, raw text elements, escapable raw text elements, foreign elements, and normal elements.

Void elements
area, base, br, col, embed, hr, img, input, link, meta, source, track, wbr
The template element
template
Raw text elements
script, style
Escapable raw text elements
textarea, title
Foreign elements
Elements from the MathML namespace and the SVG namespace.
Normal elements
All other allowed HTML elements are normal elements.

Tags are used to delimit the start and end of elements in the markup. Raw text, escapable raw text, and normal elements have a start tag to indicate where they begin, and an end tag to indicate where they end. The start and end tags of certain normal elements can be omitted, as described below in the section on optional tags. Those that cannot be omitted must not be omitted. Void elements only have a start tag; end tags must not be specified for void elements. Foreign elements must either have a start tag and an end tag, or a start tag that is marked as self-closing, in which case they must not have an end tag.

The contents of the element must be placed between just after the start tag (which might be implied, in certain cases) and just before the end tag (which again, might be implied in certain cases). The exact allowed contents of each individual element depend on the content model of that element, as described earlier in this specification. Elements must not contain content that their content model disallows. In addition to the restrictions placed on the contents by those content models, however, the five types of elements have additional syntactic requirements.

Void elements can't have any contents (since there's no end tag, no content can be put between the start tag and the end tag).

The template element can have template contents, but such template contents are not children of the template element itself. Instead, they are stored in a DocumentFragment associated with a different Document — without a browsing context — so as to avoid the template contents interfering with the main Document. The markup for the template contents of a template element is placed just after the template element's start tag and just before template element's end tag (as with other elements), and may consist of any text, character references, elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand.

Raw text elements can have text, though it has restrictions described below.

Escapable raw text elements can have text and character references, but the text must not contain an ambiguous ampersand. There are also further restrictions described below.

Foreign elements whose start tag is marked as self-closing can't have any contents (since, again, as there's no end tag, no content can be put between the start tag and the end tag). Foreign elements whose start tag is not marked as self-closing can have text, character references, CDATA sections, other elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand.

The HTML syntax does not support namespace declarations, even in foreign elements.

For instance, consider the following HTML fragment:

<p>
 <svg>
  <metadata>
   <!-- this is invalid -->
   <cdr:license xmlns:cdr="https://www.example.com/cdr/metadata" name="MIT"/>
  </metadata>
 </svg>
</p>

The innermost element, cdr:license, is actually in the SVG namespace, as the "xmlns:cdr" attribute has no effect (unlike in XML). In fact, as the comment in the fragment above says, the fragment is actually non-conforming. This is because SVG 2 does not define any elements called "cdr:license" in the SVG namespace.

Normal elements can have text, character references, other elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand. Some normal elements also have yet more restrictions on what content they are allowed to hold, beyond the restrictions imposed by the content model and those described in this paragraph. Those restrictions are described below.

Tags contain a tag name, giving the element's name. HTML elements all have names that only use ASCII alphanumerics. In the HTML syntax, tag names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that, when converted to all-lowercase, matches the element's tag name; tag names are case-insensitive.

13.1.2.1 Start tags

Start tags must have the following format:

  1. The first character of a start tag must be a U+003C LESS-THAN SIGN character (<).
  2. The next few characters of a start tag must be the element's tag name.
  3. If there are to be any attributes in the next step, there must first be one or more ASCII whitespace.
  4. Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be separated from each other by one or more ASCII whitespace.
  5. After the attributes, or after the tag name if there are no attributes, there may be one or more ASCII whitespace. (Some attributes are required to be followed by a space. See the attributes section below.)
  6. Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/), which on foreign elements marks the start tag as self-closing. On void elements, it does not mark the start tag as self-closing but instead is unnecessary and has no effect of any kind. For such void elements, it should be used only with caution — especially since, if directly preceded by an unquoted attribute value, it becomes part of the attribute value rather than being discarded by the parser.
  7. Finally, start tags must be closed by a U+003E GREATER-THAN SIGN character (>).
13.1.2.2 End tags

End tags must have the following format:

  1. The first character of an end tag must be a U+003C LESS-THAN SIGN character (<).
  2. The second character of an end tag must be a U+002F SOLIDUS character (/).
  3. The next few characters of an end tag must be the element's tag name.
  4. After the tag name, there may be one or more ASCII whitespace.
  5. Finally, end tags must be closed by a U+003E GREATER-THAN SIGN character (>).
13.1.2.3 Attributes

Attributes for an element are expressed inside the element's start tag.

Attributes have a name and a value. Attribute names must consist of one or more characters other than controls, U+0020 SPACE, U+0022 ("), U+0027 ('), U+003E (>), U+002F (/), U+003D (=), and noncharacters. In the HTML syntax, attribute names, even those for foreign elements, may be written with any mix of ASCII lower and ASCII upper alphas.

Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.

Attributes can be specified in four different ways:

Empty attribute syntax

Just the attribute name. The value is implicitly the empty string.

In the following example, the disabled attribute is given with the empty attribute syntax:

<input disabled>

If an attribute using the empty attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

Unquoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal ASCII whitespace, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

In the following example, the value attribute is given with the unquoted attribute value syntax:

<input value=yes>

If an attribute using the unquoted attribute syntax is to be followed by another attribute or by the optional U+002F SOLIDUS character (/) allowed in step 6 of the start tag syntax above, then there must be ASCII whitespace separating the two.

Single-quoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').

In the following example, the type attribute is given with the single-quoted attribute value syntax:

<input type='checkbox'>

If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

Double-quoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0022 QUOTATION MARK character ("), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0022 QUOTATION MARK characters ("), and finally followed by a second single U+0022 QUOTATION MARK character (").

In the following example, the name attribute is given with the double-quoted attribute value syntax:

<input name="be evil">

If an attribute using the double-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.


When a foreign element has one of the namespaced attributes given by the local name and namespace of the first and second cells of a row from the following table, it must be written using the name given by the third cell from the same row.

Local name Namespace Attribute name
actuate XLink namespace xlink:actuate
arcrole XLink namespace xlink:arcrole
href XLink namespace xlink:href
role XLink namespace xlink:role
show XLink namespace xlink:show
title XLink namespace xlink:title
type XLink namespace xlink:type
lang XML namespace xml:lang
space XML namespace xml:space
xmlns XMLNS namespace xmlns
xlink XMLNS namespace xmlns:xlink

No other namespaced attribute can be expressed in the HTML syntax.

Whether the attributes in the table above are conforming or not is defined by other specifications (e.g. SVG 2 and MathML); this section only describes the syntax rules if the attributes are serialized using the HTML syntax.

13.1.2.4 Optional tags

Certain tags can be omitted.

Omitting an element's start tag in the situations described below does not mean the element is not present; it is implied, but it is still there. For example, an HTML document always has a root html element, even if the string <html> doesn't appear anywhere in the markup.

An html element's start tag may be omitted if the first thing inside the html element is not a comment.

For example, in the following case it's ok to remove the "<html>" tag:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

Doing so would make the document look like this:

<!DOCTYPE HTML>

  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

This has the exact same DOM. In particular, note that whitespace around the document element is ignored by the parser. The following example would also have the exact same DOM:

<!DOCTYPE HTML><head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

However, in the following example, removing the start tag moves the comment to before the html element:

<!DOCTYPE HTML>
<html>
  <!-- where is this comment in the DOM? -->
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

With the tag removed, the document actually turns into the same as this:

<!DOCTYPE HTML>
<!-- where is this comment in the DOM? -->
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

This is why the tag can only be removed if it is not followed by a comment: removing the tag when there is a comment there changes the document's resulting parse tree. Of course, if the position of the comment does not matter, then the tag can be omitted, as if the comment had been moved to before the start tag in the first place.

An html element's end tag may be omitted if the html element is not immediately followed by a comment.

A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

A head element's end tag may be omitted if the head element is not immediately followed by ASCII whitespace or a comment.

A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not ASCII whitespace or a comment, except if the first thing inside the body element is a meta, noscript, link, script, style, or template element.

A body element's end tag may be omitted if the body element is not immediately followed by a comment.

Note that in the example above, the head element start and end tags, and the body element start tag, can't be omitted, because they are surrounded by whitespace:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

(The body and html element end tags could be omitted without trouble; any spaces after those get parsed into the body element anyway.)

Usually, however, whitespace isn't an issue. If we first remove the whitespace we don't care about:

<!DOCTYPE HTML><html><head><title>Hello</title></head><body><p>Welcome to this example.</p></body></html>

Then we can omit a number of tags without affecting the DOM:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.</p>

At that point, we can also add some whitespace back:

<!DOCTYPE HTML>
<title>Hello</title>
<p>Welcome to this example.</p>

This would be equivalent to this document, with the omitted tags shown in their parser-implied positions; the only whitespace text node that results from this is the newline at the end of the head element:

<!DOCTYPE HTML>
<html><head><title>Hello</title>
</head><body><p>Welcome to this example.</p></body></html>

An li element's end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.

A dt element's end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.

A dd element's end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.

A p element's end tag may be omitted if the p element is immediately followed by an address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, main, menu, nav, ol, p, pre, search, section, table, or ul element, or if there is no more content in the parent element and the parent element is an HTML element that is not an a, audio, del, ins, map, noscript, or video element, or an autonomous custom element.

We can thus simplify the earlier example further:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.

An rt element's end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.

An rp element's end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.

An optgroup element's end tag may be omitted if the optgroup element is immediately followed by another optgroup element, if it is immediately followed by an hr element, or if there is no more content in the parent element.

An option element's end tag may be omitted if the option element is immediately followed by another option element, if it is immediately followed by an optgroup element, if it is immediately followed by an hr element, or if there is no more content in the parent element.

A colgroup element's start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can't be omitted if the element is empty.)

A colgroup element's end tag may be omitted if the colgroup element is not immediately followed by ASCII whitespace or a comment.

A caption element's end tag may be omitted if the caption element is not immediately followed by ASCII whitespace or a comment.

A thead element's end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.

A tbody element's start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can't be omitted if the element is empty.)

A tbody element's end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.

A tfoot element's end tag may be omitted if there is no more content in the parent element.

A tr element's end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.

A td element's end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.

A th element's end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.

The ability to omit all these table-related tags makes table markup much terser.

Take this example:

<table>
 <caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)</caption>
 <colgroup><col><col><col></colgroup>
 <thead>
  <tr>
   <th>Function</th>
   <th>Control Unit</th>
   <th>Central Station</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Headlights</td>
   <td></td>
   <td></td>
  </tr>
  <tr>
   <td>Interior Lights</td>
   <td></td>
   <td></td>
  </tr>
  <tr>
   <td>Electric locomotive operating sounds</td>
   <td></td>
   <td></td>
  </tr>
  <tr>
   <td>Engineer's cab lighting</td>
   <td></td>
   <td></td>
  </tr>
  <tr>
   <td>Station Announcements - Swiss</td>
   <td></td>
   <td></td>
  </tr>
 </tbody>
</table>

The exact same table, modulo some whitespace differences, could be marked up as follows:

<table>
 <caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)
 <colgroup><col><col><col>
 <thead>
  <tr>
   <th>Function
   <th>Control Unit
   <th>Central Station
 <tbody>
  <tr>
   <td>Headlights
   <td><td><tr>
   <td>Interior Lights
   <td><td><tr>
   <td>Electric locomotive operating sounds
   <td><td><tr>
   <td>Engineer's cab lighting
   <td>
   <td><tr>
   <td>Station Announcements - Swiss
   <td>
   <td></table>

Since the cells take up much less room this way, this can be made even terser by having each row on one line:

<table>
 <caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)
 <colgroup><col><col><col>
 <thead>
  <tr> <th>Function                              <th>Control Unit     <th>Central Station
 <tbody>
  <tr> <td>Headlights                            <td><td><tr> <td>Interior Lights                       <td><td><tr> <td>Electric locomotive operating sounds  <td><td><tr> <td>Engineer's cab lighting               <td>                 <td><tr> <td>Station Announcements - Swiss         <td>                 <td></table>

The only differences between these tables, at the DOM level, is with the precise position of the (in any case semantically-neutral) whitespace.

However, a start tag must never be omitted if it has any attributes.

Returning to the earlier example with all the whitespace removed and then all the optional tags removed:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.

If the body element in this example had to have a class attribute and the html element had to have a lang attribute, the markup would have to become:

<!DOCTYPE HTML><html lang="en"><title>Hello</title><body class="demo"><p>Welcome to this example.

This section assumes that the document is conforming, in particular, that there are no content model violations. Omitting tags in the fashion described in this section in a document that does not conform to the content models described in this specification is likely to result in unexpected DOM differences (this is, in part, what the content models are designed to avoid).

13.1.2.5 Restrictions on content models

For historical reasons, certain elements have extra restrictions beyond even the restrictions given by their content model.

A table element must not contain tr elements, even though these elements are technically allowed inside table elements according to the content models described in this specification. (If a tr element is put inside a table in the markup, it will in fact imply a tbody start tag before it.)

A single newline may be placed immediately after the start tag of pre and textarea elements. This does not affect the processing of the element. The otherwise optional newline must be included if the element's contents themselves start with a newline (because otherwise the leading newline in the contents would be treated like the optional newline, and ignored).

The following two pre blocks are equivalent:

<pre>Hello</pre>
<pre>
Hello</pre>
13.1.2.6 Restrictions on the contents of raw text and escapable raw text elements

The text in raw text and escapable raw text elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

13.1.3 Text

Text is allowed inside elements, attribute values, and comments. Extra constraints are placed on what is and what is not allowed in text based on where the text is to be put, as described in the other sections.

13.1.3.1 Newlines

Newlines in HTML may be represented either as U+000D CARRIAGE RETURN (CR) characters, U+000A LINE FEED (LF) characters, or pairs of U+000D CARRIAGE RETURN (CR), U+000A LINE FEED (LF) characters in that order.

Where character references are allowed, a character reference of a U+000A LINE FEED (LF) character (but not a U+000D CARRIAGE RETURN (CR) character) also represents a newline.

13.1.4 Character references

In certain cases described in other sections, text may be mixed with character references. These can be used to escape characters that couldn't otherwise legally be included in text.

Character references must start with a U+0026 AMPERSAND character (&). Following this, there are three possible kinds of character references:

Named character references
The ampersand must be followed by one of the names given in the named character references section, using the same case. The name must be one that is terminated by a U+003B SEMICOLON character (;).
Decimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), followed by one or more ASCII digits, representing a base-ten integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).
Hexadecimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), which must be followed by either a U+0078 LATIN SMALL LETTER X character (x) or a U+0058 LATIN CAPITAL LETTER X character (X), which must then be followed by one or more ASCII hex digits, representing a hexadecimal integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).

The numeric character reference forms described above are allowed to reference any code point excluding U+000D CR, noncharacters, and controls other than ASCII whitespace.

An ambiguous ampersand is a U+0026 AMPERSAND character (&) that is followed by one or more ASCII alphanumerics, followed by a U+003B SEMICOLON character (;), where these characters do not match any of the names given in the named character references section.

13.1.5 CDATA sections

CDATA sections must consist of the following components, in this order:

  1. The string "<![CDATA[".
  2. Optionally, text, with the additional restriction that the text must not contain the string "]]>".
  3. The string "]]>".

CDATA sections can only be used in foreign content (MathML or SVG). In this example, a CDATA section is used to escape the contents of a MathML ms element:

<p>You can add a string to a number, but this stringifies the number:</p>
<math>
 <ms><![CDATA[x<y]]></ms>
 <mo>+</mo>
 <mn>3</mn>
 <mo>=</mo>
 <ms><![CDATA[x<y3]]></ms>
</math>

13.1.6 Comments

Comments must have the following format:

  1. The string "<!--".
  2. Optionally, text, with the additional restriction that the text must not start with the string ">", nor start with the string "->", nor contain the strings "<!--", "-->", or "--!>", nor end with the string "<!-".
  3. The string "-->".

The text is allowed to end with the string "<!", as in <!--My favorite operators are > and <!-->.

13.2 Parsing HTML documents

This section only applies to user agents, data mining tools, and conformance checkers.

The rules for parsing XML documents into DOM trees are covered by the next section, entitled "The XML syntax".

User agents must use the parsing rules described in this section to generate the DOM trees from text/html resources. Together, these rules define what is referred to as the HTML parser.

While the HTML syntax described in this specification bears a close resemblance to SGML and XML, it is a separate language with its own parsing rules.

Some earlier versions of HTML (in particular from HTML2 to HTML4) were based on SGML and used SGML parsing rules. However, few (if any) web browsers ever implemented true SGML parsing for HTML documents; the only user agents to strictly handle HTML as an SGML application have historically been validators. The resulting confusion — with validators claiming documents to have one representation while widely deployed web browsers interoperably implemented a different representation — has wasted decades of productivity. This version of HTML thus returns to a non-SGML basis.

Authors interested in using SGML tools in their authoring pipeline are encouraged to use XML tools and the XML serialization of HTML.

For the purposes of conformance checkers, if a resource is determined to be in the HTML syntax, then it is an HTML document.

As stated in the terminology section, references to element types that do not explicitly specify a namespace always refer to elements in the HTML namespace. For example, if the spec talks about "a menu element", then that is an element with the local name "menu", the namespace "http://www.w3.org/1999/xhtml", and the interface HTMLMenuElement. Where possible, references to such elements are hyperlinked to their definition.

13.2.1 Overview of the parsing model

The input to the HTML parsing process consists of a stream of code points, which is passed through a tokenization stage followed by a tree construction stage. The output is a Document object.

Implementations that do not support scripting do not have to actually create a DOM Document object, but the DOM tree in such cases is still used as the model for the rest of the specification.

In the common case, the data handled by the tokenization stage comes from the network, but it can also come from script running in the user agent, e.g. using the document.write() API.

There is only one set of states for the tokenizer stage and the tree construction stage, but the tree construction stage is reentrant, meaning that while the tree construction stage is handling one token, the tokenizer might be resumed, causing further tokens to be emitted and processed before the first token's processing is complete.

In the following example, the tree construction stage will be called upon to handle a "p" start tag token while handling the "script" end tag token:

...
<script>
 document.write('<p>');
</script>
...

To handle these cases, parsers have a script nesting level, which must be initially set to zero, and a parser pause flag, which must be initially set to false.

13.2.2 Parse errors

This specification defines the parsing rules for HTML documents, whether they are syntactically correct or not. Certain points in the parsing algorithm are said to be parse errors. The error handling for parse errors is well-defined (that's the processing rules described throughout this specification), but user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification.

Conformance checkers must report at least one parse error condition to the user if one or more parse error conditions exist in the document and must not report parse error conditions if none exist in the document. Conformance checkers may report more than one parse error condition if more than one parse error condition exists in the document.

Parse errors are only errors with the syntax of HTML. In addition to checking for parse errors, conformance checkers will also verify that the document obeys all the other conformance requirements described in this specification.

Some parse errors have dedicated codes outlined in the table below that should be used by conformance checkers in reports.

Error descriptions in the table below are non-normative.

Code Description
abrupt-closing-of-empty-comment

This error occurs if the parser encounters an empty comment that is abruptly closed by a U+003E (>) code point (i.e., <!--> or <!--->). The parser behaves as if the comment is closed correctly.

abrupt-doctype-public-identifier

This error occurs if the parser encounters a U+003E (>) code point in the DOCTYPE public identifier (e.g., <!DOCTYPE html PUBLIC "foo>). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

abrupt-doctype-system-identifier

This error occurs if the parser encounters a U+003E (>) code point in the DOCTYPE system identifier (e.g., <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "foo>). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

absence-of-digits-in-numeric-character-reference

This error occurs if the parser encounters a numeric character reference that doesn't contain any digits (e.g., &#qux;). In this case the parser doesn't resolve the character reference.

cdata-in-html-content

This error occurs if the parser encounters a CDATA section outside of foreign content (SVG or MathML). The parser treats such CDATA sections (including leading "[CDATA[" and trailing "]]" strings) as comments.

character-reference-outside-unicode-range

This error occurs if the parser encounters a numeric character reference that references a code point that is greater than the valid Unicode range. The parser resolves such a character reference to a U+FFFD REPLACEMENT CHARACTER.

control-character-in-input-stream

This error occurs if the input stream contains a control code point that is not ASCII whitespace or U+0000 NULL. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM.

control-character-reference

This error occurs if the parser encounters a numeric character reference that references a control code point that is not ASCII whitespace or is a U+000D CARRIAGE RETURN. The parser resolves such character references as-is except C1 control references that are replaced according to the numeric character reference end state.

duplicate-attribute

This error occurs if the parser encounters an attribute in a tag that already has an attribute with the same name. The parser ignores all such duplicate occurrences of the attribute.

end-tag-with-attributes

This error occurs if the parser encounters an end tag with attributes. Attributes in end tags are ignored and do not make their way into the DOM.

end-tag-with-trailing-solidus

This error occurs if the parser encounters an end tag that has a U+002F (/) code point right before the closing U+003E (>) code point (e.g., </div/>). Such a tag is treated as a regular end tag.

eof-before-tag-name

This error occurs if the parser encounters the end of the input stream where a tag name is expected. In this case the parser treats the beginning of a start tag (i.e., <) or an end tag (i.e., </) as text content.

eof-in-cdata

This error occurs if the parser encounters the end of the input stream in a CDATA section. The parser treats such CDATA sections as if they are closed immediately before the end of the input stream.

eof-in-comment

This error occurs if the parser encounters the end of the input stream in a comment. The parser treats such comments as if they are closed immediately before the end of the input stream.

eof-in-doctype

This error occurs if the parser encounters the end of the input stream in a DOCTYPE. In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

eof-in-script-html-comment-like-text

This error occurs if the parser encounters the end of the input stream in text that resembles an HTML comment inside script element content (e.g., <script><!-- foo).

Syntactic structures that resemble HTML comments in script elements are parsed as text content. They can be a part of a scripting language-specific syntactic structure or be treated as an HTML-like comment, if the scripting language supports them (e.g., parsing rules for HTML-like comments can be found in Annex B of the JavaScript specification). The common reason for this error is a violation of the restrictions for contents of script elements. [JAVASCRIPT]

eof-in-tag

This error occurs if the parser encounters the end of the input stream in a start tag or an end tag (e.g., <div id=). Such a tag is ignored.

incorrectly-closed-comment

This error occurs if the parser encounters a comment that is closed by the "--!>" code point sequence. The parser treats such comments as if they are correctly closed by the "-->" code point sequence.

incorrectly-opened-comment

This error occurs if the parser encounters the "<!" code point sequence that is not immediately followed by two U+002D (-) code points and that is not the start of a DOCTYPE or a CDATA section. All content that follows the "<!" code point sequence up to a U+003E (>) code point (if present) or to the end of the input stream is treated as a comment.

One possible cause of this error is using an XML markup declaration (e.g., <!ELEMENT br EMPTY>) in HTML.

invalid-character-sequence-after-doctype-name

This error occurs if the parser encounters any code point sequence other than "PUBLIC" and "SYSTEM" keywords after a DOCTYPE name. In such a case, the parser ignores any following public or system identifiers, and if the DOCTYPE is correctly placed as a document preamble, and if the parser cannot change the mode flag is false, sets the Document to quirks mode.

invalid-first-character-of-tag-name

This error occurs if the parser encounters a code point that is not an ASCII alpha where first code point of a start tag name or an end tag name is expected. If a start tag was expected such code point and a preceding U+003C (<) is treated as text content, and all content that follows is treated as markup. Whereas, if an end tag was expected, such code point and all content that follows up to a U+003E (>) code point (if present) or to the end of the input stream is treated as a comment.

For example, consider the following markup:

<42></42>

This will be parsed into:

While the first code point of a tag name is limited to an ASCII alpha, a wide range of code points (including ASCII digits) is allowed in subsequent positions.

missing-attribute-value

This error occurs if the parser encounters a U+003E (>) code point where an attribute value is expected (e.g., <div id=>). The parser treats the attribute as having an empty value.

missing-doctype-name

This error occurs if the parser encounters a DOCTYPE that is missing a name (e.g., <!DOCTYPE>). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

missing-doctype-public-identifier

This error occurs if the parser encounters a U+003E (>) code point where start of the DOCTYPE public identifier is expected (e.g., <!DOCTYPE html PUBLIC >). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

missing-doctype-system-identifier

This error occurs if the parser encounters a U+003E (>) code point where start of the DOCTYPE system identifier is expected (e.g., <!DOCTYPE html SYSTEM >). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

missing-end-tag-name

This error occurs if the parser encounters a U+003E (>) code point where an end tag name is expected, i.e., </>. The parser ignores the whole "</>" code point sequence.

missing-quote-before-doctype-public-identifier

This error occurs if the parser encounters the DOCTYPE public identifier that is not preceded by a quote (e.g., <!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN">). In such a case, the parser ignores the public identifier, and if the DOCTYPE is correctly placed as a document preamble, sets the Document to quirks mode.

missing-quote-before-doctype-system-identifier

This error occurs if the parser encounters the DOCTYPE system identifier that is not preceded by a quote (e.g., <!DOCTYPE html SYSTEM http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">). In such a case, the parser ignores the system identifier, and if the DOCTYPE is correctly placed as a document preamble, sets the Document to quirks mode.

missing-semicolon-after-character-reference

This error occurs if the parser encounters a character reference that is not terminated by a U+003B (;) code point. Usually the parser behaves as if character reference is terminated by the U+003B (;) code point; however, there are some ambiguous cases in which the parser includes subsequent code points in the character reference.

For example, &not;in will be parsed as "¬in" whereas &notin will be parsed as "".

missing-whitespace-after-doctype-public-keyword

This error occurs if the parser encounters a DOCTYPE whose "PUBLIC" keyword and public identifier are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-after-doctype-system-keyword

This error occurs if the parser encounters a DOCTYPE whose "SYSTEM" keyword and system identifier are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-before-doctype-name

This error occurs if the parser encounters a DOCTYPE whose "DOCTYPE" keyword and name are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-between-attributes

This error occurs if the parser encounters attributes that are not separated by ASCII whitespace (e.g., <div id="foo"class="bar">). In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-between-doctype-public-and-system-identifiers

This error occurs if the parser encounters a DOCTYPE whose public and system identifiers are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

nested-comment

This error occurs if the parser encounters a nested comment (e.g., <!-- <!-- nested --> -->). Such a comment will be closed by the first occurring "-->" code point sequence and everything that follows will be treated as markup.

noncharacter-character-reference

This error occurs if the parser encounters a numeric character reference that references a noncharacter. The parser resolves such character references as-is.

noncharacter-in-input-stream

This error occurs if the input stream contains a noncharacter. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM.

non-void-html-element-start-tag-with-trailing-solidus

This error occurs if the parser encounters a start tag for an element that is not in the list of void elements or is not a part of foreign content (i.e., not an SVG or MathML element) that has a U+002F (/) code point right before the closing U+003E (>) code point. The parser behaves as if the U+002F (/) is not present.

For example, consider the following markup:

<div/><span></span><span></span>

This will be parsed into:

The trailing U+002F (/) in a start tag name can be used only in foreign content to specify self-closing tags. (Self-closing tags don't exist in HTML.) It is also allowed for void elements, but doesn't have any effect in this case.

null-character-reference

This error occurs if the parser encounters a numeric character reference that references a U+0000 NULL code point. The parser resolves such character references to a U+FFFD REPLACEMENT CHARACTER.

surrogate-character-reference

This error occurs if the parser encounters a numeric character reference that references a surrogate. The parser resolves such character references to a U+FFFD REPLACEMENT CHARACTER.

surrogate-in-input-stream

This error occurs if the input stream contains a surrogate. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM.

Surrogates can only find their way into the input stream via script APIs such as document.write().

unexpected-character-after-doctype-system-identifier

This error occurs if the parser encounters any code points other than ASCII whitespace or closing U+003E (>) after the DOCTYPE system identifier. The parser ignores these code points.

unexpected-character-in-attribute-name

This error occurs if the parser encounters a U+0022 ("), U+0027 ('), or U+003C (<) code point in an attribute name. The parser includes such code points in the attribute name.

Code points that trigger this error are usually a part of another syntactic construct and can be a sign of a typo around the attribute name.

For example, consider the following markup:

<div foo<div>

Due to a forgotten U+003E (>) code point after foo the parser treats this markup as a single div element with a "foo<div" attribute.

As another example of this error, consider the following markup:

<div id'bar'>

Due to a forgotten U+003D (=) code point between an attribute name and value the parser treats this markup as a div element with the attribute "id'bar'" that has an empty value.

unexpected-character-in-unquoted-attribute-value

This error occurs if the parser encounters a U+0022 ("), U+0027 ('), U+003C (<), U+003D (=), or U+0060 (`) code point in an unquoted attribute value. The parser includes such code points in the attribute value.

Code points that trigger this error are usually a part of another syntactic construct and can be a sign of a typo around the attribute value.

U+0060 (`) is in the list of code points that trigger this error because certain legacy user agents treat it as a quote.

For example, consider the following markup:

<div foo=b'ar'>

Due to a misplaced U+0027 (') code point the parser sets the value of the "foo" attribute to "b'ar'".

unexpected-equals-sign-before-attribute-name

This error occurs if the parser encounters a U+003D (=) code point before an attribute name. In this case the parser treats U+003D (=) as the first code point of the attribute name.

The common reason for this error is a forgotten attribute name.

For example, consider the following markup:

<div foo="bar" ="baz">

Due to a forgotten attribute name the parser treats this markup as a div element with two attributes: a "foo" attribute with a "bar" value and a "="baz"" attribute with an empty value.

unexpected-null-character

This error occurs if the parser encounters a U+0000 NULL code point in the input stream in certain positions. In general, such code points are either ignored or, for security reasons, replaced with a U+FFFD REPLACEMENT CHARACTER.

unexpected-question-mark-instead-of-tag-name

This error occurs if the parser encounters a U+003F (?) code point where first code point of a start tag name is expected. The U+003F (?) and all content that follows up to a U+003E (>) code point (if present) or to the end of the input stream is treated as a comment.

For example, consider the following markup:

<?xml-stylesheet type="text/css" href="style.css"?>

This will be parsed into:

The common reason for this error is an XML processing instruction (e.g., <?xml-stylesheet type="text/css" href="style.css"?>) or an XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) being used in HTML.

unexpected-solidus-in-tag

This error occurs if the parser encounters a U+002F (/) code point that is not a part of a quoted attribute value and not immediately followed by a U+003E (>) code point in a tag (e.g., <div / id="foo">). In this case the parser behaves as if it encountered ASCII whitespace.

unknown-named-character-reference

This error occurs if the parser encounters an ambiguous ampersand. In this case the parser doesn't resolve the character reference.

13.2.3 The input byte stream

The stream of code points that comprises the input to the tokenization stage will be initially seen by the user agent as a stream of bytes (typically coming over the network or from the local file system). The bytes encode the actual characters according to a particular character encoding, which the user agent uses to decode the bytes into characters.

For XML documents, the algorithm user agents are required to use to determine the character encoding is given by XML. This section does not apply to XML documents. [XML]

Usually, the encoding sniffing algorithm defined below is used to determine the character encoding.

Given a character encoding, the bytes in the input byte stream must be converted to characters for the tokenizer's input stream, by passing the input byte stream and character encoding to decode.

A leading Byte Order Mark (BOM) causes the character encoding argument to be ignored and will itself be skipped.

Bytes or sequences of bytes in the original byte stream that did not conform to the Encoding standard (e.g. invalid UTF-8 byte sequences in a UTF-8 input byte stream) are errors that conformance checkers are expected to report. [ENCODING]

The decoder algorithms describe how to handle invalid input; for security reasons, it is imperative that those rules be followed precisely. Differences in how invalid byte sequences are handled can result in, amongst other problems, script injection vulnerabilities ("XSS").

When the HTML parser is decoding an input byte stream, it uses a character encoding and a confidence. The confidence is either tentative, certain, or irrelevant. The encoding used, and whether the confidence in that encoding is tentative or certain, is used during the parsing to determine whether to change the encoding. If no encoding is necessary, e.g. because the parser is operating on a Unicode stream and doesn't have to use a character encoding at all, then the confidence is irrelevant.

Some algorithms feed the parser by directly adding characters to the input stream rather than adding bytes to the input byte stream.

13.2.3.1 Parsing with a known character encoding

When the HTML parser is to operate on an input byte stream that has a known definite encoding, then the character encoding is that encoding and the confidence is certain.

13.2.3.2 Determining the character encoding

In some cases, it might be impractical to unambiguously determine the encoding before parsing the document. Because of this, this specification provides for a two-pass mechanism with an optional pre-scan. Implementations are allowed, as described below, to apply a simplified parsing algorithm to whatever bytes they have available before beginning to parse the document. Then, the real parser is started, using a tentative encoding derived from this pre-parse and other out-of-band metadata. If, while the document is being loaded, the user agent discovers a character encoding declaration that conflicts with this information, then the parser can get reinvoked to perform a parse of the document with the real encoding.

User agents must use the following algorithm, called the encoding sniffing algorithm, to determine the character encoding to use when decoding a document in the first pass. This algorithm takes as input any out-of-band metadata available to the user agent (e.g. the Content-Type metadata of the document) and all the bytes available so far, and returns a character encoding and a confidence that is either tentative or certain.

  1. If the result of BOM sniffing is an encoding, return that encoding with confidence certain.

    Although the decode algorithm will itself change the encoding to use based on the presence of a byte order mark, this algorithm sniffs the BOM as well in order to set the correct document's character encoding and confidence.

  2. If the user has explicitly instructed the user agent to override the document's character encoding with a specific encoding, optionally return that encoding with the confidence certain.

    Typically, user agents remember such user requests across sessions, and in some cases apply them to documents in iframes as well.

  3. The user agent may wait for more bytes of the resource to be available, either in this step or at any later step in this algorithm. For instance, a user agent might wait 500ms or 1024 bytes, whichever came first. In general preparsing the source to find the encoding improves performance, as it reduces the need to throw away the data structures used when parsing upon finding the encoding information. However, if the user agent delays too long to obtain data to determine the encoding, then the cost of the delay could outweigh any performance improvements from the preparse.

    The authoring conformance requirements for character encoding declarations limit them to only appearing in the first 1024 bytes. User agents are therefore encouraged to use the prescan algorithm below (as invoked by these steps) on the first 1024 bytes, but not to stall beyond that.

  4. If the transport layer specifies a character encoding, and it is supported, return that encoding with the confidence certain.

  5. Optionally prescan the byte stream to determine its encoding, with the end condition being when the user agent decides that scanning further bytes would not be efficient. User agents are encouraged to only prescan the first 1024 bytes. User agents may decide that scanning any bytes is not efficient, in which case these substeps are entirely skipped.

    The aforementioned algorithm returns either a character encoding or failure. If it returns a character encoding, then return the same encoding, with confidence tentative.

  6. If the HTML parser for which this algorithm is being run is associated with a Document d whose container document is non-null, then:

    1. Let parentDocument be d's container document.

    2. If parentDocument's origin is same origin with d's origin and parentDocument's character encoding is not UTF-16BE/LE, then return parentDocument's character encoding, with the confidence tentative.

  7. Otherwise, if the user agent has information on the likely encoding for this page, e.g. based on the encoding of the page when it was last visited, then return that encoding, with the confidence tentative.

  8. The user agent may attempt to autodetect the character encoding from applying frequency analysis or other algorithms to the data stream. Such algorithms may use information about the resource other than the resource's contents, including the address of the resource. If autodetection succeeds in determining a character encoding, and that encoding is a supported encoding, then return that encoding, with the confidence tentative. [UNIVCHARDET]

    User agents are generally discouraged from attempting to autodetect encodings for resources obtained over the network, since doing so involves inherently non-interoperable heuristics. Attempting to detect encodings based on an HTML document's preamble is especially tricky since HTML markup typically uses only ASCII characters, and HTML documents tend to begin with a lot of markup rather than with text content.

    The UTF-8 encoding has a highly detectable bit pattern. Files from the local file system that contain bytes with values greater than 0x7F which match the UTF-8 pattern are very likely to be UTF-8, while documents with byte sequences that do not match it are very likely not. When a user agent can examine the whole file, rather than just the preamble, detecting for UTF-8 specifically can be especially effective. [PPUTF8] [UTF8DET]

  9. Otherwise, return an implementation-defined or user-specified default character encoding, with the confidence tentative.

    In controlled environments or in environments where the encoding of documents can be prescribed (for example, for user agents intended for dedicated use in new networks), the comprehensive UTF-8 encoding is suggested.

    In other environments, the default encoding is typically dependent on the user's locale (an approximation of the languages, and thus often encodings, of the pages that the user is likely to frequent). The following table gives suggested defaults based on the user's locale, for compatibility with legacy content. Locales are identified by BCP 47 language tags. [BCP47] [ENCODING]

    Locale language Suggested default encoding
    ar Arabic windows-1256
    az Azeri windows-1254
    ba Bashkir windows-1251
    be Belarusian windows-1251
    bg Bulgarian windows-1251
    cs Czech windows-1250
    el Greek ISO-8859-7
    et Estonian windows-1257
    fa Persian windows-1256
    he Hebrew windows-1255
    hr Croatian windows-1250
    hu Hungarian ISO-8859-2
    ja Japanese Shift_JIS
    kk Kazakh windows-1251
    ko Korean EUC-KR
    ku Kurdish windows-1254
    ky Kyrgyz windows-1251
    lt Lithuanian windows-1257
    lv Latvian windows-1257
    mk Macedonian windows-1251
    pl Polish ISO-8859-2
    ru Russian windows-1251
    sah Yakut windows-1251
    sk Slovak windows-1250
    sl Slovenian ISO-8859-2
    sr Serbian windows-1251
    tg Tajik windows-1251
    th Thai windows-874
    tr Turkish windows-1254
    tt Tatar windows-1251
    uk Ukrainian windows-1251
    vi Vietnamese windows-1258
    zh-Hans, zh-CN, zh-SG Chinese, Simplified GBK
    zh-Hant, zh-HK, zh-MO, zh-TW Chinese, Traditional Big5
    All other locales windows-1252

    The contents of this table are derived from the intersection of Windows, Chrome, and Firefox defaults.

The document's character encoding must immediately be set to the value returned from this algorithm, at the same time as the user agent uses the returned value to select the decoder to use for the input byte stream.


When an algorithm requires a user agent to prescan a byte stream to determine its encoding, given some defined end condition, then it must run the following steps. If at any point during these steps (including during instances of the get an attribute algorithm invoked by this one) the user agent either runs out of bytes (meaning the position pointer created in the first step below goes beyond the end of the byte stream obtained so far) or reaches its end condition, then abort the prescan a byte stream to determine its encoding algorithm and return the result get an XML encoding applied to the same bytes that the prescan a byte stream to determine its encoding algorithm was applied to. Otherwise, these steps will return a character encoding.

  1. Let fallback encoding be null.

  2. Let position be a pointer to a byte in the input byte stream, initially pointing at the first byte.

  3. Prescan for UTF-16 XML declarations: If position points to:

    A sequence of bytes starting with: 0x3C, 0x0, 0x3F, 0x0, 0x78, 0x0 (case-sensitive UTF-16 little-endian '<?x')

    Return UTF-16LE.

    A sequence of bytes starting with: 0x0, 0x3C, 0x0, 0x3F, 0x0, 0x78 (case-sensitive UTF-16 big-endian '<?x')

    Return UTF-16BE.

    For historical reasons, the prefix is two bytes longer than in Appendix F of XML and the encoding name is not checked.

  4. Loop: If position points to:

    A sequence of bytes starting with: 0x3C 0x21 0x2D 0x2D (`<!--`)

    Advance the position pointer so that it points at the first 0x3E byte which is preceded by two 0x2D bytes (i.e. at the end of an ASCII '-->' sequence) and comes after the 0x3C byte that was found. (The two 0x2D bytes can be the same as those in the '<!--' sequence.)

    A sequence of bytes starting with: 0x3C, 0x4D or 0x6D, 0x45 or 0x65, 0x54 or 0x74, 0x41 or 0x61, and one of 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x2F (case-insensitive ASCII '<meta' followed by a space or slash)
    1. Advance the position pointer so that it points at the next 0x09, 0x0A, 0x0C, 0x0D, 0x20, or 0x2F byte (the one in sequence of characters matched above).

    2. Let attribute list be an empty list of strings.

    3. Let got pragma be false.

    4. Let need pragma be null.

    5. Let charset be the null value (which, for the purposes of this algorithm, is distinct from an unrecognized encoding or the empty string).

    6. Attributes: Get an attribute and its value. If no attribute was sniffed, then jump to the processing step below.

    7. If the attribute's name is already in attribute list, then return to the step labeled attributes.

    8. Add the attribute's name to attribute list.

    9. Run the appropriate step from the following list, if one applies:

      If the attribute's name is "http-equiv"

      If the attribute's value is "content-type", then set got pragma to true.

      If the attribute's name is "content"

      Apply the algorithm for extracting a character encoding from a meta element, giving the attribute's value as the string to parse. If a character encoding is returned, and if charset is still set to null, let charset be the encoding returned, and set need pragma to true.

      If the attribute's name is "charset"

      Let charset be the result of getting an encoding from the attribute's value, and set need pragma to false.

    10. Return to the step labeled attributes.

    11. Processing: If need pragma is null, then jump to the step below labeled next byte.

    12. If need pragma is true but got pragma is false, then jump to the step below labeled next byte.

    13. If charset is failure, then jump to the step below labeled next byte.

    14. If charset is UTF-16BE/LE, then set charset to UTF-8.

    15. If charset is x-user-defined, then set charset to windows-1252.

    16. Return charset.

    A sequence of bytes starting with a 0x3C byte (<), optionally a 0x2F byte (/), and finally a byte in the range 0x41-0x5A or 0x61-0x7A (A-Z or a-z)
    1. Advance the position pointer so that it points at the next 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>) byte.

    2. Repeatedly get an attribute until no further attributes can be found, then jump to the step below labeled next byte.

    A sequence of bytes starting with: 0x3C 0x21 (`<!`)
    A sequence of bytes starting with: 0x3C 0x2F (`</`)
    A sequence of bytes starting with: 0x3C 0x3F (`<?`)

    Advance the position pointer so that it points at the first 0x3E byte (>) that comes after the 0x3C byte that was found.

    Any other byte

    Do nothing with that byte.

  5. Next byte: Move position so it points at the next byte in the input byte stream, and return to the step above labeled loop.

When the prescan a byte stream to determine its encoding algorithm says to get an attribute, it means doing this:

  1. If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x2F (/) then advance position to the next byte and redo this step.

  2. If the byte at position is 0x3E (>), then abort the get an attribute algorithm. There isn't one.

  3. Otherwise, the byte at position is the start of the attribute name. Let attribute name and attribute value be the empty string.

  4. Process the byte at position as follows:

    If it is 0x3D (=), and the attribute name is longer than the empty string
    Advance position to the next byte and jump to the step below labeled value.
    If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP)
    Jump to the step below labeled spaces.
    If it is 0x2F (/) or 0x3E (>)
    Abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.
    If it is in the range 0x41 (A) to 0x5A (Z)
    Append the code point b+0x20 to attribute name (where b is the value of the byte at position). (This converts the input to lowercase.)
    Anything else
    Append the code point with the same value as the byte at position to attribute name. (It doesn't actually matter how bytes outside the ASCII range are handled here, since only ASCII bytes can contribute to the detection of a character encoding.)
  5. Advance position to the next byte and return to the previous step.

  6. Spaces: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP) then advance position to the next byte, then, repeat this step.

  7. If the byte at position is not 0x3D (=), abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.

  8. Advance position past the 0x3D (=) byte.

  9. Value: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP) then advance position to the next byte, then, repeat this step.

  10. Process the byte at position as follows:

    If it is 0x22 (") or 0x27 (')
    1. Let b be the value of the byte at position.
    2. Quote loop: Advance position to the next byte.
    3. If the value of the byte at position is the value of b, then advance position to the next byte and abort the "get an attribute" algorithm. The attribute's name is the value of attribute name, and its value is the value of attribute value.
    4. Otherwise, if the value of the byte at position is in the range 0x41 (A) to 0x5A (Z), then append a code point to attribute value whose value is 0x20 more than the value of the byte at position.
    5. Otherwise, append a code point to attribute value whose value is the same as the value of the byte at position.
    6. Return to the step above labeled quote loop.
    If it is 0x3E (>)
    Abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.
    If it is in the range 0x41 (A) to 0x5A (Z)
    Append a code point b+0x20 to attribute value (where b is the value of the byte at position). Advance position to the next byte.
    Anything else
    Append a code point with the same value as the byte at position to attribute value. Advance position to the next byte.
  11. Process the byte at position as follows:

    If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>)
    Abort the get an attribute algorithm. The attribute's name is the value of attribute name and its value is the value of attribute value.
    If it is in the range 0x41 (A) to 0x5A (Z)
    Append a code point b+0x20 to attribute value (where b is the value of the byte at position).
    Anything else
    Append a code point with the same value as the byte at position to attribute value.
  12. Advance position to the next byte and return to the previous step.

When the prescan a byte stream to determine its encoding algorithm is aborted without returning an encoding, get an XML encoding means doing this.

Looking for syntax resembling an XML declaration, even in text/html, is necessary for compatibility with existing content.

  1. Let encodingPosition be a pointer to the start of the stream.

  2. If encodingPosition does not point to the start of a byte sequence 0x3C, 0x3F, 0x78, 0x6D, 0x6C (`<?xml`), then return failure.

  3. Let xmlDeclarationEnd be a pointer to the next byte in the input byte stream which is 0x3E (>). If there is no such byte, then return failure.

  4. Set encodingPosition to the position of the first occurrence of the subsequence of bytes 0x65, 0x6E, 0x63, 0x6F, 0x64, 0x69, 0x6E, 0x67 (`encoding`) at or after the current encodingPosition. If there is no such sequence, then return failure.

  5. Advance encodingPosition past the 0x67 (g) byte.

  6. While the byte at encodingPosition is less than or equal to 0x20 (i.e., it is either an ASCII space or control character), advance encodingPosition to the next byte.

  7. If the byte at encodingPosition is not 0x3D (=), then return failure.

  8. Advance encodingPosition to the next byte.

  9. While the byte at encodingPosition is less than or equal to 0x20 (i.e., it is either an ASCII space or control character), advance encodingPosition to the next byte.

  10. Let quoteMark be the byte at encodingPosition.

  11. If quoteMark is not either 0x22 (") or 0x27 ('), then return failure.

  12. Advance encodingPosition to the next byte.

  13. Let encodingEndPosition be the position of the next occurrence of quoteMark at or after encodingPosition. If quoteMark does not occur again, then return failure.

  14. Let potentialEncoding be the sequence of the bytes between encodingPosition (inclusive) and encodingEndPosition (exclusive).

  15. If potentialEncoding contains one or more bytes whose byte value is 0x20 or below, then return failure.

  16. Let encoding be the result of getting an encoding given potentialEncoding isomorphic decoded.

  17. If the encoding is UTF-16BE/LE, then change it to UTF-8.

  18. Return encoding.

For the sake of interoperability, user agents should not use a pre-scan algorithm that returns different results than the one described above. (But, if you do, please at least let us know, so that we can improve this algorithm and benefit everyone...)

13.2.3.3 Character encodings

User agents must support the encodings defined in Encoding, including, but not limited to, UTF-8, ISO-8859-2, ISO-8859-7, ISO-8859-8, windows-874, windows-1250, windows-1251, windows-1252, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, GBK, Big5, ISO-2022-JP, Shift_JIS, EUC-KR, UTF-16BE, UTF-16LE, UTF-16BE/LE, and x-user-defined. User agents must not support other encodings.

The above prohibits supporting, for example, CESU-8, UTF-7, BOCU-1, SCSU, EBCDIC, and UTF-32. This specification does not make any attempt to support prohibited encodings in its algorithms; support and use of prohibited encodings would thus lead to unexpected behavior. [CESU8] [UTF7] [BOCU1] [SCSU]

13.2.3.4 Changing the encoding while parsing

When the parser requires the user agent to change the encoding, it must run the following steps. This might happen if the encoding sniffing algorithm described above failed to find a character encoding, or if it found a character encoding that was not the actual encoding of the file.

  1. If the encoding that is already being used to interpret the input stream is UTF-16BE/LE, then set the confidence to certain and return. The new encoding is ignored; if it was anything but the same encoding, then it would be clearly incorrect.

  2. If the new encoding is UTF-16BE/LE, then change it to UTF-8.

  3. If the new encoding is x-user-defined, then change it to windows-1252.

  4. If the new encoding is identical or equivalent to the encoding that is already being used to interpret the input stream, then set the confidence to certain and return. This happens when the encoding information found in the file matches what the encoding sniffing algorithm determined to be the encoding, and in the second pass through the parser if the first pass found that the encoding sniffing algorithm described in the earlier section failed to find the right encoding.

  5. If all the bytes up to the last byte converted by the current decoder have the same Unicode interpretations in both the current encoding and the new encoding, and if the user agent supports changing the converter on the fly, then the user agent may change to the new converter for the encoding on the fly. Set the document's character encoding and the encoding used to convert the input stream to the new encoding, set the confidence to certain, and return.

  6. Otherwise, restart the navigate algorithm, with historyHandling set to "replace" and other inputs kept the same, but this time skip the encoding sniffing algorithm and instead just set the encoding to the new encoding and the confidence to certain. Whenever possible, this should be done without actually contacting the network layer (the bytes should be re-parsed from memory), even if, e.g., the document is marked as not being cacheable. If this is not possible and contacting the network layer would involve repeating a request that uses a method other than `GET`, then instead set the confidence to certain and ignore the new encoding. The resource will be misinterpreted. User agents may notify the user of the situation, to aid in application development.

This algorithm is only invoked when a new encoding is found declared on a meta element.

13.2.3.5 Preprocessing the input stream

The input stream consists of the characters pushed into it as the input byte stream is decoded or from the various APIs that directly manipulate the input stream.

Any occurrences of surrogates are surrogate-in-input-stream parse errors. Any occurrences of noncharacters are noncharacter-in-input-stream parse errors and any occurrences of controls other than ASCII whitespace and U+0000 NULL characters are control-character-in-input-stream parse errors.

The handling of U+0000 NULL characters varies based on where the characters are found and happens at the later stages of the parsing. They are either ignored or, for security reasons, replaced with a U+FFFD REPLACEMENT CHARACTER. This handling is, by necessity, spread across both the tokenization stage and the tree construction stage.

Before the tokenization stage, the input stream must be preprocessed by normalizing newlines. Thus, newlines in HTML DOMs are represented by U+000A LF characters, and there are never any U+000D CR characters in the input to the tokenization stage.

The next input character is the first character in the input stream that has not yet been consumed or explicitly ignored by the requirements in this section. Initially, the next input character is the first character in the input. The current input character is the last character to have been consumed.

The insertion point is the position (just before a character or just before the end of the input stream) where content inserted using document.write() is actually inserted. The insertion point is relative to the position of the character immediately after it, it is not an absolute offset into the input stream. Initially, the insertion point is undefined.

The "EOF" character in the tables below is a conceptual character representing the end of the input stream. If the parser is a script-created parser, then the end of the input stream is reached when an explicit "EOF" character (inserted by the document.close() method) is consumed. Otherwise, the "EOF" character is not a real character in the stream, but rather the lack of any further characters.

13.2.4 Parse state

13.2.4.1 The insertion mode

The insertion mode is a state variable that controls the primary operation of the tree construction stage.

Initially, the insertion mode is "initial". It can change to "before html", "before head", "in head", "in head noscript", "after head", "in body", "text", "in table", "in table text", "in caption", "in column group", "in table body", "in row", "in cell", "in select", "in select in table", "in template", "after body", "in frameset", "after frameset", "after after body", and "after after frameset" during the course of the parsing, as described in the tree construction stage. The insertion mode affects how tokens are processed and whether CDATA sections are supported.

Several of these modes, namely "in head", "in body", "in table", and "in select", are special, in that the other modes defer to them at various times. When the algorithm below says that the user agent is to do something "using the rules for the m insertion mode", where m is one of these modes, the user agent must use the rules described under the m insertion mode's section, but must leave the insertion mode unchanged unless the rules in m themselves switch the insertion mode to a new value.

When the insertion mode is switched to "text" or "in table text", the original insertion mode is also set. This is the insertion mode to which the tree construction stage will return.

Similarly, to parse nested template elements, a stack of template insertion modes is used. It is initially empty. The current template insertion mode is the insertion mode that was most recently added to the stack of template insertion modes. The algorithms in the sections below will push insertion modes onto this stack, meaning that the specified insertion mode is to be added to the stack, and pop insertion modes from the stack, which means that the most recently added insertion mode must be removed from the stack.


When the steps below require the UA to reset the insertion mode appropriately, it means the UA must follow these steps:

  1. Let last be false.

  2. Let node be the last node in the stack of open elements.

  3. Loop: If node is the first node in the stack of open elements, then set last to true, and, if the parser was created as part of the HTML fragment parsing algorithm (fragment case), set node to the context element passed to that algorithm.

  4. If node is a select element, run these substeps:

    1. If last is true, jump to the step below labeled done.

    2. Let ancestor be node.

    3. Loop: If ancestor is the first node in the stack of open elements, jump to the step below labeled done.

    4. Let ancestor be the node before ancestor in the stack of open elements.

    5. If ancestor is a template node, jump to the step below labeled done.

    6. If ancestor is a table node, switch the insertion mode to "in select in table" and return.

    7. Jump back to the step labeled loop.

    8. Done: Switch the insertion mode to "in select" and return.

  5. If node is a td or th element and last is false, then switch the insertion mode to "in cell" and return.

  6. If node is a tr element, then switch the insertion mode to "in row" and return.

  7. If node is a tbody, thead, or tfoot element, then switch the insertion mode to "in table body" and return.

  8. If node is a caption element, then switch the insertion mode to "in caption" and return.

  9. If node is a colgroup element, then switch the insertion mode to "in column group" and return.

  10. If node is a table element, then switch the insertion mode to "in table" and return.

  11. If node is a template element, then switch the insertion mode to the current template insertion mode and return.

  12. If node is a head element and last is false, then switch the insertion mode to "in head" and return.

  13. If node is a body element, then switch the insertion mode to "in body" and return.

  14. If node is a frameset element, then switch the insertion mode to "in frameset" and return. (fragment case)

  15. If node is an html element, run these substeps:

    1. If the head element pointer is null, switch the insertion mode to "before head" and return. (fragment case)

    2. Otherwise, the head element pointer is not null, switch the insertion mode to "after head" and return.

  16. If last is true, then switch the insertion mode to "in body" and return. (fragment case)

  17. Let node now be the node before node in the stack of open elements.

  18. Return to the step labeled loop.

13.2.4.2 The stack of open elements

Initially, the stack of open elements is empty. The stack grows downwards; the topmost node on the stack is the first one added to the stack, and the bottommost node of the stack is the most recently added node in the stack (notwithstanding when the stack is manipulated in a random access fashion as part of the handling for misnested tags).

The "before html" insertion mode creates the html document element, which is then added to the stack.

In the fragment case, the stack of open elements is initialized to contain an html element that is created as part of that algorithm. (The fragment case skips the "before html" insertion mode.)

The html node, however it is created, is the topmost node of the stack. It only gets popped off the stack when the parser finishes.

The current node is the bottommost node in this stack of open elements.

The adjusted current node is the context element if the parser was created as part of the HTML fragment parsing algorithm and the stack of open elements has only one element in it (fragment case); otherwise, the adjusted current node is the current node.

When the current node is removed from the stack of open elements, process internal resource links given the current node's node document.

Elements in the stack of open elements fall into the following categories:

Special

The following elements have varying levels of special parsing rules: HTML's address, applet, area, article, aside, base, basefont, bgsound, blockquote, body, br, button, caption, center, col, colgroup, dd, details, dir, div, dl, dt, embed, fieldset, figcaption, figure, footer, form, frame, frameset, h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html, iframe, img, input, keygen, li, link, listing, main, marquee, menu, meta, nav, noembed, noframes, noscript, object, ol, p, param, plaintext, pre, script, search, section, select, source, style, summary, table, tbody, td, template, textarea, tfoot, th, thead, title, tr, track, ul, wbr, xmp; MathML mi, MathML mo, MathML mn, MathML ms, MathML mtext, and MathML annotation-xml; and SVG foreignObject, SVG desc, and SVG title.

An image start tag token is handled by the tree builder, but it is not in this list because it is not an element; it gets turned into an img element.

Formatting

The following HTML elements are those that end up in the list of active formatting elements: a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt, and u.

Ordinary

All other elements found while parsing an HTML document.

Typically, the special elements have the start and end tag tokens handled specifically, while ordinary elements' tokens fall into "any other start tag" and "any other end tag" clauses, and some parts of the tree builder check if a particular element in the stack of open elements is in the special category. However, some elements (e.g., the option element) have their start or end tag tokens handled specifically, but are still not in the special category, so that they get the ordinary handling elsewhere.

The stack of open elements is said to have an element target node in a specific scope consisting of a list of element types list when the following algorithm terminates in a match state:

  1. Initialize node to be the current node (the bottommost node of the stack).

  2. If node is the target node, terminate in a match state.

  3. Otherwise, if node is one of the element types in list, terminate in a failure state.

  4. Otherwise, set node to the previous entry in the stack of open elements and return to step 2. (This will never fail, since the loop will always terminate in the previous step if the top of the stack — an html element — is reached.)

The stack of open elements is said to have a particular element in scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in list item scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in button scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in table scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in select scope when it has that element in the specific scope consisting of all element types except the following:

Nothing happens if at any time any of the elements in the stack of open elements are moved to a new location in, or removed from, the Document tree. In particular, the stack is not changed in this situation. This can cause, amongst other strange effects, content to be appended to nodes that are no longer in the DOM.

In some cases (namely, when closing misnested formatting elements), the stack is manipulated in a random-access fashion.

13.2.4.3 The list of active formatting elements

Initially, the list of active formatting elements is empty. It is used to handle mis-nested formatting element tags.

The list contains elements in the formatting category, and markers. The markers are inserted when entering applet, object, marquee, template, td, th, and caption elements, and are used to prevent formatting from "leaking" into applet, object, marquee, template, td, th, and caption elements.

In addition, each element in the list of active formatting elements is associated with the token for which it was created, so that further elements can be created for that token if necessary.

When the steps below require the UA to push onto the list of active formatting elements an element element, the UA must perform the following steps:

  1. If there are already three elements in the list of active formatting elements after the last marker, if any, or anywhere in the list if there are no markers, that have the same tag name, namespace, and attributes as element, then remove the earliest such element from the list of active formatting elements. For these purposes, the attributes must be compared as they were when the elements were created by the parser; two elements have the same attributes if all their parsed attributes can be paired such that the two attributes in each pair have identical names, namespaces, and values (the order of the attributes does not matter).

    This is the Noah's Ark clause. But with three per family instead of two.

  2. Add element to the list of active formatting elements.

When the steps below require the UA to reconstruct the active formatting elements, the UA must perform the following steps:

  1. If there are no entries in the list of active formatting elements, then there is nothing to reconstruct; stop this algorithm.

  2. If the last (most recently added) entry in the list of active formatting elements is a marker, or if it is an element that is in the stack of open elements, then there is nothing to reconstruct; stop this algorithm.

  3. Let entry be the last (most recently added) element in the list of active formatting elements.

  4. Rewind: If there are no entries before entry in the list of active formatting elements, then jump to the step labeled create.

  5. Let entry be the entry one earlier than entry in the list of active formatting elements.

  6. If entry is neither a marker nor an element that is also in the stack of open elements, go to the step labeled rewind.

  7. Advance: Let entry be the element one later than entry in the list of active formatting elements.

  8. Create: Insert an HTML element for the token for which the element entry was created, to obtain new element.

  9. Replace the entry for entry in the list with an entry for new element.

  10. If the entry for new element in the list of active formatting elements is not the last entry in the list, return to the step labeled advance.

This has the effect of reopening all the formatting elements that were opened in the current body, cell, or caption (whichever is youngest) that haven't been explicitly closed.

The way this specification is written, the list of active formatting elements always consists of elements in chronological order with the least recently added element first and the most recently added element last (except for while steps 7 to 10 of the above algorithm are being executed, of course).

When the steps below require the UA to clear the list of active formatting elements up to the last marker, the UA must perform the following steps:

  1. Let entry be the last (most recently added) entry in the list of active formatting elements.

  2. Remove entry from the list of active formatting elements.

  3. If entry was a marker, then stop the algorithm at this point. The list has been cleared up to the last marker.

  4. Go to step 1.

13.2.4.4 The element pointers

Initially, the head element pointer and the form element pointer are both null.

Once a head element has been parsed (whether implicitly or explicitly) the head element pointer gets set to point to this node.

The form element pointer points to the last form element that was opened and whose end tag has not yet been seen. It is used to make form controls associate with forms in the face of dramatically bad markup, for historical reasons. It is ignored inside template elements.

13.2.4.5 Other parsing state flags

The scripting flag is set to "enabled" if scripting was enabled for the Document with which the parser is associated when the parser was created, and "disabled" otherwise.

The scripting flag can be enabled even when the parser was created as part of the HTML fragment parsing algorithm, even though script elements don't execute in that case.

The frameset-ok flag is set to "ok" when the parser is created. It is set to "not ok" after certain tokens are seen.

13.2.5 Tokenization

Implementations must act as if they used the following state machine to tokenize HTML. The state machine must start in the data state. Most states consume a single character, which may have various side-effects, and either switches the state machine to a new state to reconsume the current input character, or switches it to a new state to consume the next character, or stays in the same state to consume the next character. Some states have more complicated behavior and can consume several characters before switching to another state. In some cases, the tokenizer state is also changed by the tree construction stage.

When a state says to reconsume a matched character in a specified state, that means to switch to that state, but when it attempts to consume the next input character, provide it with the current input character instead.

The exact behavior of certain states depends on the insertion mode and the stack of open elements. Certain states also use a temporary buffer to track progress, and the character reference state uses a return state to return to the state it was invoked from.

The output of the tokenization step is a series of zero or more of the following tokens: DOCTYPE, start tag, end tag, comment, character, end-of-file. DOCTYPE tokens have a name, a public identifier, a system identifier, and a force-quirks flag. When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), and the force-quirks flag must be set to off (its other state is on). Start and end tag tokens have a tag name, a self-closing flag, and a list of attributes, each of which has a name and a value. When a start or end tag token is created, its self-closing flag must be unset (its other state is that it be set), and its attributes list must be empty. Comment and character tokens have data.

When a token is emitted, it must immediately be handled by the tree construction stage. The tree construction stage can affect the state of the tokenization stage, and can insert additional characters into the stream. (For example, the script element can result in scripts executing and using the dynamic markup insertion APIs to insert characters into the stream being tokenized.)

Creating a token and emitting it are distinct actions. It is possible for a token to be created but implicitly abandoned (never emitted), e.g. if the file ends unexpectedly while processing the characters that are being parsed into a start tag token.

When a start tag token is emitted with its self-closing flag set, if the flag is not acknowledged when it is processed by the tree construction stage, that is a non-void-html-element-start-tag-with-trailing-solidus parse error.

When an end tag token is emitted with attributes, that is an end-tag-with-attributes parse error.

When an end tag token is emitted with its self-closing flag set, that is an end-tag-with-trailing-solidus parse error.

An appropriate end tag token is an end tag token whose tag name matches the tag name of the last start tag to have been emitted from this tokenizer, if any. If no start tag has been emitted from this tokenizer, then no end tag token is appropriate.

A character reference is said to be consumed as part of an attribute if the return state is either attribute value (double-quoted) state, attribute value (single-quoted) state or attribute value (unquoted) state.

When a state says to flush code points consumed as a character reference, it means that for each code point in the temporary buffer (in the order they were added to the buffer) user agent must append the code point from the buffer to the current attribute's value if the character reference was consumed as part of an attribute, or emit the code point as a character token otherwise.

Before each step of the tokenizer, the user agent must first check the parser pause flag. If it is true, then the tokenizer must abort the processing of any nested invocations of the tokenizer, yielding control back to the caller.

The tokenizer state machine consists of the states defined in the following subsections.

13.2.5.1 Data state

Consume the next input character:

U+0026 AMPERSAND (&)
Set the return state to the data state. Switch to the character reference state.
U+003C LESS-THAN SIGN (<)
Switch to the tag open state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit the current input character as a character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.2 RCDATA state

Consume the next input character:

U+0026 AMPERSAND (&)
Set the return state to the RCDATA state. Switch to the character reference state.
U+003C LESS-THAN SIGN (<)
Switch to the RCDATA less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.3 RAWTEXT state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Switch to the RAWTEXT less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.4 Script data state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Switch to the script data less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.5 PLAINTEXT state

Consume the next input character:

U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.6 Tag open state

Consume the next input character:

U+0021 EXCLAMATION MARK (!)
Switch to the markup declaration open state.
U+002F SOLIDUS (/)
Switch to the end tag open state.
ASCII alpha
Create a new start tag token, set its tag name to the empty string. Reconsume in the tag name state.
U+003F QUESTION MARK (?)
This is an unexpected-question-mark-instead-of-tag-name parse error. Create a comment token whose data is the empty string. Reconsume in the bogus comment state.
EOF
This is an eof-before-tag-name parse error. Emit a U+003C LESS-THAN SIGN character token and an end-of-file token.
Anything else
This is an invalid-first-character-of-tag-name parse error. Emit a U+003C LESS-THAN SIGN character token. Reconsume in the data state.
13.2.5.7 End tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the tag name state.
U+003E GREATER-THAN SIGN (>)
This is a missing-end-tag-name parse error. Switch to the data state.
EOF
This is an eof-before-tag-name parse error. Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token and an end-of-file token.
Anything else
This is an invalid-first-character-of-tag-name parse error. Create a comment token whose data is the empty string. Reconsume in the bogus comment state.
13.2.5.8 Tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before attribute name state.
U+002F SOLIDUS (/)
Switch to the self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current tag token's tag name.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current tag token's tag name.
13.2.5.9 RCDATA less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the RCDATA end tag open state.
Anything else
Emit a U+003C LESS-THAN SIGN character token. Reconsume in the RCDATA state.
13.2.5.10 RCDATA end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the RCDATA end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the RCDATA state.
13.2.5.11 RCDATA end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the RCDATA state.
13.2.5.12 RAWTEXT less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the RAWTEXT end tag open state.
Anything else
Emit a U+003C LESS-THAN SIGN character token. Reconsume in the RAWTEXT state.
13.2.5.13 RAWTEXT end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the RAWTEXT end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the RAWTEXT state.
13.2.5.14 RAWTEXT end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the RAWTEXT state.
13.2.5.15 Script data less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the script data end tag open state.
U+0021 EXCLAMATION MARK (!)
Switch to the script data escape start state. Emit a U+003C LESS-THAN SIGN character token and a U+0021 EXCLAMATION MARK character token.
Anything else
Emit a U+003C LESS-THAN SIGN character token. Reconsume in the script data state.
13.2.5.16 Script data end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the script data end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the script data state.
13.2.5.17 Script data end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the script data state.
13.2.5.18 Script data escape start state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data escape start dash state. Emit a U+002D HYPHEN-MINUS character token.
Anything else
Reconsume in the script data state.
13.2.5.19 Script data escape start dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data escaped dash dash state. Emit a U+002D HYPHEN-MINUS character token.
Anything else
Reconsume in the script data state.
13.2.5.20 Script data escaped state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data escaped dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data escaped less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.21 Script data escaped dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data escaped dash dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data escaped less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Switch to the script data escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Switch to the script data escaped state. Emit the current input character as a character token.
13.2.5.22 Script data escaped dash dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data escaped less-than sign state.
U+003E GREATER-THAN SIGN (>)
Switch to the script data state. Emit a U+003E GREATER-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Switch to the script data escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Switch to the script data escaped state. Emit the current input character as a character token.
13.2.5.23 Script data escaped less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the script data escaped end tag open state.
ASCII alpha
Set the temporary buffer to the empty string. Emit a U+003C LESS-THAN SIGN character token. Reconsume in the script data double escape start state.
Anything else
Emit a U+003C LESS-THAN SIGN character token. Reconsume in the script data escaped state.
13.2.5.24 Script data escaped end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the script data escaped end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the script data escaped state.
13.2.5.25 Script data escaped end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the script data escaped state.
13.2.5.26 Script data double escape start state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
If the temporary buffer is the string "script", then switch to the script data double escaped state. Otherwise, switch to the script data escaped state. Emit the current input character as a character token.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the temporary buffer. Emit the current input character as a character token.
ASCII lower alpha
Append the current input character to the temporary buffer. Emit the current input character as a character token.
Anything else
Reconsume in the script data escaped state.
13.2.5.27 Script data double escaped state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data double escaped dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.28 Script data double escaped dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data double escaped dash dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Switch to the script data double escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Switch to the script data double escaped state. Emit the current input character as a character token.
13.2.5.29 Script data double escaped dash dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+003E GREATER-THAN SIGN (>)
Switch to the script data state. Emit a U+003E GREATER-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Switch to the script data double escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Switch to the script data double escaped state. Emit the current input character as a character token.
13.2.5.30 Script data double escaped less-than sign state

Consume the next input character:

U+002F SOLIDUS (/)
Set the temporary buffer to the empty string. Switch to the script data double escape end state. Emit a U+002F SOLIDUS character token.
Anything else
Reconsume in the script data double escaped state.
13.2.5.31 Script data double escape end state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
If the temporary buffer is the string "script", then switch to the script data escaped state. Otherwise, switch to the script data double escaped state. Emit the current input character as a character token.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the temporary buffer. Emit the current input character as a character token.
ASCII lower alpha
Append the current input character to the temporary buffer. Emit the current input character as a character token.
Anything else
Reconsume in the script data double escaped state.
13.2.5.32 Before attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
EOF
Reconsume in the after attribute name state.
U+003D EQUALS SIGN (=)
This is an unexpected-equals-sign-before-attribute-name parse error. Start a new attribute in the current tag token. Set that attribute's name to the current input character, and its value to the empty string. Switch to the attribute name state.
Anything else
Start a new attribute in the current tag token. Set that attribute name and value to the empty string. Reconsume in the attribute name state.
13.2.5.33 Attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
EOF
Reconsume in the after attribute name state.
U+003D EQUALS SIGN (=)
Switch to the before attribute value state.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current attribute's name.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's name.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
This is an unexpected-character-in-attribute-name parse error. Treat it as per the "anything else" entry below.
Anything else
Append the current input character to the current attribute's name.

When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute's name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a duplicate-attribute parse error and the new attribute must be removed from the token.

If an attribute is so removed from a token, it, and the value that gets associated with it, if any, are never subsequently used by the parser, and are therefore effectively discarded. Removing the attribute in this way does not change its status as the "current attribute" for the purposes of the tokenizer, however.

13.2.5.34 After attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+002F SOLIDUS (/)
Switch to the self-closing start tag state.
U+003D EQUALS SIGN (=)
Switch to the before attribute value state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Start a new attribute in the current tag token. Set that attribute name and value to the empty string. Reconsume in the attribute name state.
13.2.5.35 Before attribute value state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Switch to the attribute value (double-quoted) state.
U+0027 APOSTROPHE (')
Switch to the attribute value (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-attribute-value parse error. Switch to the data state. Emit the current tag token.
Anything else
Reconsume in the attribute value (unquoted) state.
13.2.5.36 Attribute value (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the after attribute value (quoted) state.
U+0026 AMPERSAND (&)
Set the return state to the attribute value (double-quoted) state. Switch to the character reference state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current attribute's value.
13.2.5.37 Attribute value (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the after attribute value (quoted) state.
U+0026 AMPERSAND (&)
Set the return state to the attribute value (single-quoted) state. Switch to the character reference state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current attribute's value.
13.2.5.38 Attribute value (unquoted) state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before attribute name state.
U+0026 AMPERSAND (&)
Set the return state to the attribute value (unquoted) state. Switch to the character reference state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
U+003D EQUALS SIGN (=)
U+0060 GRAVE ACCENT (`)
This is an unexpected-character-in-unquoted-attribute-value parse error. Treat it as per the "anything else" entry below.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current attribute's value.
13.2.5.39 After attribute value (quoted) state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before attribute name state.
U+002F SOLIDUS (/)
Switch to the self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
This is a missing-whitespace-between-attributes parse error. Reconsume in the before attribute name state.
13.2.5.40 Self-closing start tag state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Set the self-closing flag of the current tag token. Switch to the data state. Emit the current tag token.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
This is an unexpected-solidus-in-tag parse error. Reconsume in the before attribute name state.
13.2.5.41 Bogus comment state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current comment token.
EOF
Emit the comment. Emit an end-of-file token.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the comment token's data.
Anything else
Append the current input character to the comment token's data.
13.2.5.42 Markup declaration open state

If the next few characters are:

Two U+002D HYPHEN-MINUS characters (-)
Consume those two characters, create a comment token whose data is the empty string, and switch to the comment start state.
ASCII case-insensitive match for the word "DOCTYPE"
Consume those characters and switch to the DOCTYPE state.
The string "[CDATA[" (the five uppercase letters "CDATA" with a U+005B LEFT SQUARE BRACKET character before and after)
Consume those characters. If there is an adjusted current node and it is not an element in the HTML namespace, then switch to the CDATA section state. Otherwise, this is a cdata-in-html-content parse error. Create a comment token whose data is the "[CDATA[" string. Switch to the bogus comment state.
Anything else
This is an incorrectly-opened-comment parse error. Create a comment token whose data is the empty string. Switch to the bogus comment state (don't consume anything in the current state).
13.2.5.43 Comment start state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment start dash state.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-closing-of-empty-comment parse error. Switch to the data state. Emit the current comment token.
Anything else
Reconsume in the comment state.
13.2.5.44 Comment start dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment end state.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-closing-of-empty-comment parse error. Switch to the data state. Emit the current comment token.
EOF
This is an eof-in-comment parse error. Emit the current comment token. Emit an end-of-file token.
Anything else
Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Reconsume in the comment state.
13.2.5.45 Comment state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Append the current input character to the comment token's data. Switch to the comment less-than sign state.
U+002D HYPHEN-MINUS (-)
Switch to the comment end dash state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the comment token's data.
EOF
This is an eof-in-comment parse error. Emit the current comment token. Emit an end-of-file token.
Anything else
Append the current input character to the comment token's data.
13.2.5.46 Comment less-than sign state

Consume the next input character:

U+0021 EXCLAMATION MARK (!)
Append the current input character to the comment token's data. Switch to the comment less-than sign bang state.
U+003C LESS-THAN SIGN (<)
Append the current input character to the comment token's data.
Anything else
Reconsume in the comment state.
13.2.5.47 Comment less-than sign bang state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment less-than sign bang dash state.
Anything else
Reconsume in the comment state.
13.2.5.48 Comment less-than sign bang dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment less-than sign bang dash dash state.
Anything else
Reconsume in the comment end dash state.
13.2.5.49 Comment less-than sign bang dash dash state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
EOF
Reconsume in the comment end state.
Anything else
This is a nested-comment parse error. Reconsume in the comment end state.
13.2.5.50 Comment end dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment end state.
EOF
This is an eof-in-comment parse error. Emit the current comment token. Emit an end-of-file token.
Anything else
Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Reconsume in the comment state.
13.2.5.51 Comment end state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current comment token.
U+0021 EXCLAMATION MARK (!)
Switch to the comment end bang state.
U+002D HYPHEN-MINUS (-)
Append a U+002D HYPHEN-MINUS character (-) to the comment token's data.
EOF
This is an eof-in-comment parse error. Emit the current comment token. Emit an end-of-file token.
Anything else
Append two U+002D HYPHEN-MINUS characters (-) to the comment token's data. Reconsume in the comment state.
13.2.5.52 Comment end bang state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Append two U+002D HYPHEN-MINUS characters (-) and a U+0021 EXCLAMATION MARK character (!) to the comment token's data. Switch to the comment end dash state.
U+003E GREATER-THAN SIGN (>)
This is an incorrectly-closed-comment parse error. Switch to the data state. Emit the current comment token.
EOF
This is an eof-in-comment parse error. Emit the current comment token. Emit an end-of-file token.
Anything else
Append two U+002D HYPHEN-MINUS characters (-) and a U+0021 EXCLAMATION MARK character (!) to the comment token's data. Reconsume in the comment state.
13.2.5.53 DOCTYPE state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
Reconsume in the before DOCTYPE name state.
EOF
This is an eof-in-doctype parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Emit the current token. Emit an end-of-file token.
Anything else
This is a missing-whitespace-before-doctype-name parse error. Reconsume in the before DOCTYPE name state.
13.2.5.54 Before DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
ASCII upper alpha
Create a new DOCTYPE token. Set the token's name to the lowercase version of the current input character (add 0x0020 to the character's code point). Switch to the DOCTYPE name state.
U+0000 NULL
This is an unexpected-null-character parse error. Create a new DOCTYPE token. Set the token's name to a U+FFFD REPLACEMENT CHARACTER character. Switch to the DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-name parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Switch to the data state. Emit the current token.
EOF
This is an eof-in-doctype parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Emit the current token. Emit an end-of-file token.
Anything else
Create a new DOCTYPE token. Set the token's name to the current input character. Switch to the DOCTYPE name state.
13.2.5.55 DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the after DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current DOCTYPE token's name.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's name.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's name.
13.2.5.56 After DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else

If the six characters starting from the current input character are an ASCII case-insensitive match for the word "PUBLIC", then consume those characters and switch to the after DOCTYPE public keyword state.

Otherwise, if the six characters starting from the current input character are an ASCII case-insensitive match for the word "SYSTEM", then consume those characters and switch to the after DOCTYPE system keyword state.

Otherwise, this is an invalid-character-sequence-after-doctype-name parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.

13.2.5.57 After DOCTYPE public keyword state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before DOCTYPE public identifier state.
U+0022 QUOTATION MARK (")
This is a missing-whitespace-after-doctype-public-keyword parse error. Set the current DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (double-quoted) state.
U+0027 APOSTROPHE (')
This is a missing-whitespace-after-doctype-public-keyword parse error. Set the current DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-public-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-public-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.58 Before DOCTYPE public identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Set the current DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the current DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-public-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-public-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.59 DOCTYPE public identifier (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the after DOCTYPE public identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's public identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-public-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's public identifier.
13.2.5.60 DOCTYPE public identifier (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the after DOCTYPE public identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's public identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-public-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's public identifier.
13.2.5.61 After DOCTYPE public identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the between DOCTYPE public and system identifiers state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
U+0022 QUOTATION MARK (")
This is a missing-whitespace-between-doctype-public-and-system-identifiers parse error. Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
This is a missing-whitespace-between-doctype-public-and-system-identifiers parse error. Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.62 Between DOCTYPE public and system identifiers state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
U+0022 QUOTATION MARK (")
Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.63 After DOCTYPE system keyword state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before DOCTYPE system identifier state.
U+0022 QUOTATION MARK (")
This is a missing-whitespace-after-doctype-system-keyword parse error. Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
This is a missing-whitespace-after-doctype-system-keyword parse error. Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.64 Before DOCTYPE system identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the current DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.65 DOCTYPE system identifier (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the after DOCTYPE system identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's system identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's system identifier.
13.2.5.66 DOCTYPE system identifier (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the after DOCTYPE system identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's system identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-system-identifier parse error. Set the current DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's system identifier.
13.2.5.67 After DOCTYPE system identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the current DOCTYPE token's force-quirks flag to on. Emit the current DOCTYPE token. Emit an end-of-file token.
Anything else
This is an unexpected-character-after-doctype-system-identifier parse error. Reconsume in the bogus DOCTYPE state. (This does not set the current DOCTYPE token's force-quirks flag to on.)
13.2.5.68 Bogus DOCTYPE state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the DOCTYPE token.
U+0000 NULL
This is an unexpected-null-character parse error. Ignore the character.
EOF
Emit the DOCTYPE token. Emit an end-of-file token.
Anything else
Ignore the character.
13.2.5.69 CDATA section state

Consume the next input character:

U+005D RIGHT SQUARE BRACKET (])
Switch to the CDATA section bracket state.
EOF
This is an eof-in-cdata parse error. Emit an end-of-file token.
Anything else
Emit the current input character as a character token.

U+0000 NULL characters are handled in the tree construction stage, as part of the in foreign content insertion mode, which is the only place where CDATA sections can appear.

13.2.5.70 CDATA section bracket state

Consume the next input character:

U+005D RIGHT SQUARE BRACKET (])
Switch to the CDATA section end state.
Anything else
Emit a U+005D RIGHT SQUARE BRACKET character token. Reconsume in the CDATA section state.
13.2.5.71 CDATA section end state

Consume the next input character:

U+005D RIGHT SQUARE BRACKET (])
Emit a U+005D RIGHT SQUARE BRACKET character token.
U+003E GREATER-THAN SIGN character
Switch to the data state.
Anything else
Emit two U+005D RIGHT SQUARE BRACKET character tokens. Reconsume in the CDATA section state.
13.2.5.72 Character reference state

Set the temporary buffer to the empty string. Append a U+0026 AMPERSAND (&) character to the temporary buffer. Consume the next input character:

ASCII alphanumeric
Reconsume in the named character reference state.
U+0023 NUMBER SIGN (#)
Append the current input character to the temporary buffer. Switch to the numeric character reference state.
Anything else
Flush code points consumed as a character reference. Reconsume in the return state.
13.2.5.73 Named character reference state

Consume the maximum number of characters possible, where the consumed characters are one of the identifiers in the first column of the named character references table. Append each character to the temporary buffer when it's consumed.

If there is a match

If the character reference was consumed as part of an attribute, and the last character matched is not a U+003B SEMICOLON character (;), and the next input character is either a U+003D EQUALS SIGN character (=) or an ASCII alphanumeric, then, for historical reasons, flush code points consumed as a character reference and switch to the return state.

Otherwise:

  1. If the last character matched is not a U+003B SEMICOLON character (;), then this is a missing-semicolon-after-character-reference parse error.

  2. Set the temporary buffer to the empty string. Append one or two characters corresponding to the character reference name (as given by the second column of the named character references table) to the temporary buffer.

  3. Flush code points consumed as a character reference. Switch to the return state.
Otherwise
Flush code points consumed as a character reference. Switch to the ambiguous ampersand state.

If the markup contains (not in an attribute) the string I'm &notit; I tell you, the character reference is parsed as "not", as in, I'm ¬it; I tell you (and this is a parse error). But if the markup was I'm &notin; I tell you, the character reference would be parsed as "notin;", resulting in I'm ∉ I tell you (and no parse error).

However, if the markup contains the string I'm &notit; I tell you in an attribute, no character reference is parsed and string remains intact (and there is no parse error).

13.2.5.74 Ambiguous ampersand state

Consume the next input character:

ASCII alphanumeric
If the character reference was consumed as part of an attribute, then append the current input character to the current attribute's value. Otherwise, emit the current input character as a character token.
U+003B SEMICOLON (;)
This is an unknown-named-character-reference parse error. Reconsume in the return state.
Anything else
Reconsume in the return state.
13.2.5.75 Numeric character reference state

Set the character reference code to zero (0).

Consume the next input character:

U+0078 LATIN SMALL LETTER X
U+0058 LATIN CAPITAL LETTER X
Append the current input character to the temporary buffer. Switch to the hexadecimal character reference start state.
Anything else
Reconsume in the decimal character reference start state.
13.2.5.76 Hexadecimal character reference start state

Consume the next input character:

ASCII hex digit
Reconsume in the hexadecimal character reference state.
Anything else
This is an absence-of-digits-in-numeric-character-reference parse error. Flush code points consumed as a character reference. Reconsume in the return state.
13.2.5.77 Decimal character reference start state

Consume the next input character:

ASCII digit
Reconsume in the decimal character reference state.
Anything else
This is an absence-of-digits-in-numeric-character-reference parse error. Flush code points consumed as a character reference. Reconsume in the return state.
13.2.5.78 Hexadecimal character reference state

Consume the next input character:

ASCII digit
Multiply the character reference code by 16. Add a numeric version of the current input character (subtract 0x0030 from the character's code point) to the character reference code.
ASCII upper hex digit
Multiply the character reference code by 16. Add a numeric version of the current input character as a hexadecimal digit (subtract 0x0037 from the character's code point) to the character reference code.
ASCII lower hex digit
Multiply the character reference code by 16. Add a numeric version of the current input character as a hexadecimal digit (subtract 0x0057 from the character's code point) to the character reference code.
U+003B SEMICOLON
Switch to the numeric character reference end state.
Anything else
This is a missing-semicolon-after-character-reference parse error. Reconsume in the numeric character reference end state.
13.2.5.79 Decimal character reference state

Consume the next input character:

ASCII digit
Multiply the character reference code by 10. Add a numeric version of the current input character (subtract 0x0030 from the character's code point) to the character reference code.
U+003B SEMICOLON
Switch to the numeric character reference end state.
Anything else
This is a missing-semicolon-after-character-reference parse error. Reconsume in the numeric character reference end state.
13.2.5.80 Numeric character reference end state

Check the character reference code:

Set the temporary buffer to the empty string. Append a code point equal to the character reference code to the temporary buffer. Flush code points consumed as a character reference. Switch to the return state.

13.2.6 Tree construction

The input to the tree construction stage is a sequence of tokens from the tokenization stage. The tree construction stage is associated with a DOM Document object when a parser is created. The "output" of this stage consists of dynamically modifying or extending that document's DOM tree.

This specification does not define when an interactive user agent has to render the Document so that it is available to the user, or when it has to begin accepting user input.


As each token is emitted from the tokenizer, the user agent must follow the appropriate steps from the following list, known as the tree construction dispatcher:

If the stack of open elements is empty
If the adjusted current node is an element in the HTML namespace
If the adjusted current node is a MathML text integration point and the token is a start tag whose tag name is neither "mglyph" nor "malignmark"
If the adjusted current node is a MathML text integration point and the token is a character token
If the adjusted current node is a MathML annotation-xml element and the token is a start tag whose tag name is "svg"
If the adjusted current node is an HTML integration point and the token is a start tag
If the adjusted current node is an HTML integration point and the token is a character token
If the token is an end-of-file token
Process the token according to the rules given in the section corresponding to the current insertion mode in HTML content.
Otherwise
Process the token according to the rules given in the section for parsing tokens in foreign content.

The next token is the token that is about to be processed by the tree construction dispatcher (even if the token is subsequently just ignored).

A node is a MathML text integration point if it is one of the following elements:

A node is an HTML integration point if it is one of the following elements:

If the node in question is the context element passed to the HTML fragment parsing algorithm, then the start tag token for that element is the "fake" token created during by that HTML fragment parsing algorithm.


Not all of the tag names mentioned below are conformant tag names in this specification; many are included to handle legacy content. They still form part of the algorithm that implementations are required to implement to claim conformance.

The algorithm described below places no limit on the depth of the DOM tree generated, or on the length of tag names, attribute names, attribute values, Text nodes, etc. While implementers are encouraged to avoid arbitrary limits, it is recognized that practical concerns will likely force user agents to impose nesting depth constraints.

13.2.6.1 Creating and inserting nodes

While the parser is processing a token, it can enable or disable foster parenting. This affects the following algorithm.

The appropriate place for inserting a node, optionally using a particular override target, is the position in an element returned by running the following steps:

  1. If there was an override target specified, then let target be the override target.

    Otherwise, let target be the current node.

  2. Determine the adjusted insertion location using the first matching steps from the following list:

    If foster parenting is enabled and target is a table, tbody, tfoot, thead, or tr element

    Foster parenting happens when content is misnested in tables.

    Run these substeps:

    1. Let last template be the last template element in the stack of open elements, if any.

    2. Let last table be the last table element in the stack of open elements, if any.

    3. If there is a last template and either there is no last table, or there is one, but last template is lower (more recently added) than last table in the stack of open elements, then: let adjusted insertion location be inside last template's template contents, after its last child (if any), and abort these steps.

    4. If there is no last table, then let adjusted insertion location be inside the first element in the stack of open elements (the html element), after its last child (if any), and abort these steps. (fragment case)

    5. If last table has a parent node, then let adjusted insertion location be inside last table's parent node, immediately before last table, and abort these steps.

    6. Let previous element be the element immediately above last table in the stack of open elements.

    7. Let adjusted insertion location be inside previous element, after its last child (if any).

    These steps are involved in part because it's possible for elements, the table element in this case in particular, to have been moved by a script around in the DOM, or indeed removed from the DOM entirely, after the element was inserted by the parser.

    Otherwise

    Let adjusted insertion location be inside target, after its last child (if any).

  3. If the adjusted insertion location is inside a template element, let it instead be inside the template element's template contents, after its last child (if any).

  4. Return the adjusted insertion location.


When the steps below require the UA to create an element for a token in a particular given namespace and with a particular intended parent, the UA must run the following steps:

  1. If the active speculative HTML parser is not null, then return the result of creating a speculative mock element given given namespace, the tag name of the given token, and the attributes of the given token.

  2. Otherwise, optionally create a speculative mock element given given namespace, the tag name of the given token, and the attributes of the given token.

    The result is not used. This step allows for a speculative fetch to be initiated from non-speculative parsing. The fetch is still speculative at this point, because, for example, by the time the element is inserted, intended parent might have been removed from the document.

  3. Let document be intended parent's node document.

  4. Let local name be the tag name of the token.

  5. Let is be the value of the "is" attribute in the given token, if such an attribute exists, or null otherwise.

  6. Let definition be the result of looking up a custom element definition given document, given namespace, local name, and is.

  7. If definition is non-null and the parser was not created as part of the HTML fragment parsing algorithm, then let will execute script be true. Otherwise, let it be false.

  8. If will execute script is true, then:

    1. Increment document's throw-on-dynamic-markup-insertion counter.

    2. If the JavaScript execution context stack is empty, then perform a microtask checkpoint.

    3. Push a new element queue onto document's relevant agent's custom element reactions stack.

  9. Let element be the result of creating an element given document, localName, given namespace, null, and is. If will execute script is true, set the synchronous custom elements flag; otherwise, leave it unset.

    This will cause custom element constructors to run, if will execute script is true. However, since we incremented the throw-on-dynamic-markup-insertion counter, this cannot cause new characters to be inserted into the tokenizer, or the document to be blown away.

  10. Append each attribute in the given token to element.

    This can enqueue a custom element callback reaction for the attributeChangedCallback, which might run immediately (in the next step).

    Even though the is attribute governs the creation of a customized built-in element, it is not present during the execution of the relevant custom element constructor; it is appended in this step, along with all other attributes.

  11. If will execute script is true, then:

    1. Let queue be the result of popping from document's relevant agent's custom element reactions stack. (This will be the same element queue as was pushed above.)

    2. Invoke custom element reactions in queue.

    3. Decrement document's throw-on-dynamic-markup-insertion counter.

  12. If element has an xmlns attribute in the XMLNS namespace whose value is not exactly the same as the element's namespace, that is a parse error. Similarly, if element has an xmlns:xlink attribute in the XMLNS namespace whose value is not the XLink Namespace, that is a parse error.

  13. If element is a resettable element, invoke its reset algorithm. (This initializes the element's value and checkedness based on the element's attributes.)

  14. If element is a form-associated element and not a form-associated custom element, the form element pointer is not null, there is no template element on the stack of open elements, element is either not listed or doesn't have a form attribute, and the intended parent is in the same tree as the element pointed to by the form element pointer, then associate element with the form element pointed to by the form element pointer and set element's parser inserted flag.

  15. Return element.


To insert an element at the adjusted insertion location with an element element:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.

  2. If it is not possible to insert element at the adjusted insertion location, abort these steps.

  3. If the parser was not created as part of the HTML fragment parsing algorithm, then push a new element queue onto element's relevant agent's custom element reactions stack.

  4. Insert element at the adjusted insertion location.

  5. If the parser was not created as part of the HTML fragment parsing algorithm, then pop the element queue from element's relevant agent's custom element reactions stack, and invoke custom element reactions in that queue.

If the adjusted insertion location cannot accept more elements, e.g., because it's a Document that already has an element child, then element is dropped on the floor.

When the steps below require the user agent to insert a foreign element for a token in a given namespace and with a boolean onlyAddToElementStack, the user agent must run these steps:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.

  2. Let element be the result of creating an element for the token in the given namespace, with the intended parent being the element in which the adjusted insertion location finds itself.

  3. If onlyAddToElementStack is false, then run insert an element at the adjusted insertion location with element.

  4. Push element onto the stack of open elements so that it is the new current node.

  5. Return element.

When the steps below require the user agent to insert an HTML element for a token, the user agent must insert a foreign element for the token, with the HTML namespace and false.


When the steps below require the user agent to adjust MathML attributes for a token, then, if the token has an attribute named definitionurl, change its name to definitionURL (note the case difference).

When the steps below require the user agent to adjust SVG attributes for a token, then, for each attribute on the token whose attribute name is one of the ones in the first column of the following table, change the attribute's name to the name given in the corresponding cell in the second column. (This fixes the case of SVG attributes that are not all lowercase.)

Attribute name on token Attribute name on element
attributename attributeName
attributetype attributeType
basefrequency baseFrequency
baseprofile baseProfile
calcmode calcMode
clippathunits clipPathUnits
diffuseconstant diffuseConstant
edgemode edgeMode
filterunits filterUnits
glyphref glyphRef
gradienttransform gradientTransform
gradientunits gradientUnits
kernelmatrix kernelMatrix
kernelunitlength kernelUnitLength
keypoints keyPoints
keysplines keySplines
keytimes keyTimes
lengthadjust lengthAdjust
limitingconeangle limitingConeAngle
markerheight markerHeight
markerunits markerUnits
markerwidth markerWidth
maskcontentunits maskContentUnits
maskunits maskUnits
numoctaves numOctaves
pathlength pathLength
patterncontentunits patternContentUnits
patterntransform patternTransform
patternunits patternUnits
pointsatx pointsAtX
pointsaty pointsAtY
pointsatz pointsAtZ
preservealpha preserveAlpha
preserveaspectratio preserveAspectRatio
primitiveunits primitiveUnits
refx refX
refy refY
repeatcount repeatCount
repeatdur repeatDur
requiredextensions requiredExtensions
requiredfeatures requiredFeatures
specularconstant specularConstant
specularexponent specularExponent
spreadmethod spreadMethod
startoffset startOffset
stddeviation stdDeviation
stitchtiles stitchTiles
surfacescale surfaceScale
systemlanguage systemLanguage
tablevalues tableValues
targetx targetX
targety targetY
textlength textLength
viewbox viewBox
viewtarget viewTarget
xchannelselector xChannelSelector
ychannelselector yChannelSelector
zoomandpan zoomAndPan

When the steps below require the user agent to adjust foreign attributes for a token, then, if any of the attributes on the token match the strings given in the first column of the following table, let the attribute be a namespaced attribute, with the prefix being the string given in the corresponding cell in the second column, the local name being the string given in the corresponding cell in the third column, and the namespace being the namespace given in the corresponding cell in the fourth column. (This fixes the use of namespaced attributes, in particular lang attributes in the XML namespace.)

Attribute name Prefix Local name Namespace
xlink:actuate xlink actuate XLink namespace
xlink:arcrole xlink arcrole XLink namespace
xlink:href xlink href XLink namespace
xlink:role xlink role XLink namespace
xlink:show xlink show XLink namespace
xlink:title xlink title XLink namespace
xlink:type xlink type XLink namespace
xml:lang xml lang XML namespace
xml:space xml space XML namespace
xmlns (none) xmlns XMLNS namespace
xmlns:xlink xmlns xlink XMLNS namespace

When the steps below require the user agent to insert a character while processing a token, the user agent must run the following steps:

  1. Let data be the characters passed to the algorithm, or, if no characters were explicitly specified, the character of the character token being processed.

  2. Let the adjusted insertion location be the appropriate place for inserting a node.

  3. If the adjusted insertion location is in a Document node, then return.

    The DOM will not let Document nodes have Text node children, so they are dropped on the floor.

  4. If there is a Text node immediately before the adjusted insertion location, then append data to that Text node's data.

    Otherwise, create a new Text node whose data is data and whose node document is the same as that of the element in which the adjusted insertion location finds itself, and insert the newly created node at the adjusted insertion location.

Here are some sample inputs to the parser and the corresponding number of Text nodes that they result in, assuming a user agent that executes scripts.

Input Number of Text nodes
A<script>
var script = document.getElementsByTagName('script')[0];
document.body.removeChild(script);
</script>B
One Text node in the document, containing "AB".
A<script>
var text = document.createTextNode('B');
document.body.appendChild(text);
</script>C
Three Text nodes; "A" before the script, the script's contents, and "BC" after the script (the parser appends to the Text node created by the script).
A<script>
var text = document.getElementsByTagName('script')[0].firstChild;
text.data = 'B';
document.body.appendChild(text);
</script>C
Two adjacent Text nodes in the document, containing "A" and "BC".
A<table>B<tr>C</tr>D</table>
One Text node before the table, containing "ABCD". (This is caused by foster parenting.)
A<table><tr> B</tr> C</table>
One Text node before the table, containing "A B C" (A-space-B-space-C). (This is caused by foster parenting.)
A<table><tr> B</tr> </em>C</table>
One Text node before the table, containing "A BC" (A-space-B-C), and one Text node inside the table (as a child of a tbody) with a single space character. (Space characters separated from non-space characters by non-character tokens are not affected by foster parenting, even if those other tokens then get ignored.)

When the steps below require the user agent to insert a comment while processing a comment token, optionally with an explicitly insertion position position, the user agent must run the following steps:

  1. Let data be the data given in the comment token being processed.

  2. If position was specified, then let the adjusted insertion location be position. Otherwise, let adjusted insertion location be the appropriate place for inserting a node.

  3. Create a Comment node whose data attribute is set to data and whose node document is the same as that of the node in which the adjusted insertion location finds itself.

  4. Insert the newly created node at the adjusted insertion location.


DOM mutation events must not fire for changes caused by the UA parsing the document. This includes the parsing of any content inserted using document.write() and document.writeln() calls. [UIEVENTS]

However, mutation observers do fire, as required by DOM .

13.2.6.2 Parsing elements that contain only text

The generic raw text element parsing algorithm and the generic RCDATA element parsing algorithm consist of the following steps. These algorithms are always invoked in response to a start tag token.

  1. Insert an HTML element for the token.

  2. If the algorithm that was invoked is the generic raw text element parsing algorithm, switch the tokenizer to the RAWTEXT state; otherwise the algorithm invoked was the generic RCDATA element parsing algorithm, switch the tokenizer to the RCDATA state.

  3. Let the original insertion mode be the current insertion mode.

  4. Then, switch the insertion mode to "text".

13.2.6.3 Closing elements that have implied end tags

When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, or an rtc element, the UA must pop the current node off the stack of open elements.

If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must perform the above steps as if that element was not in the above list.

When the steps below require the UA to generate all implied end tags thoroughly, then, while the current node is a caption element, a colgroup element, a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, or a tr element, the UA must pop the current node off the stack of open elements.

13.2.6.4 The rules for parsing tokens in HTML content
13.2.6.4.1 The "initial" insertion mode

A Document object has an associated parser cannot change the mode flag (a boolean). It is initially false.

When the user agent is to apply the rules for the "initial" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Ignore the token.

A comment token

Insert a comment as the last child of the Document object.

A DOCTYPE token

If the DOCTYPE token's name is not "html", or the token's public identifier is not missing, or the token's system identifier is neither missing nor "about:legacy-compat", then there is a parse error.

Append a DocumentType node to the Document node, with its name set to the name given in the DOCTYPE token, or the empty string if the name was missing; its public ID set to the public identifier given in the DOCTYPE token, or the empty string if the public identifier was missing; and its system ID set to the system identifier given in the DOCTYPE token, or the empty string if the system identifier was missing.

This also ensures that the DocumentType node is returned as the value of the doctype attribute of the Document object.

Then, if the document is not an iframe srcdoc document, and the parser cannot change the mode flag is false, and the DOCTYPE token matches one of the conditions in the following list, then set the Document to quirks mode:

Otherwise, if the document is not an iframe srcdoc document, and the parser cannot change the mode flag is false, and the DOCTYPE token matches one of the conditions in the following list, then set the Document to limited-quirks mode:

The system identifier and public identifier strings must be compared to the values given in the lists above in an ASCII case-insensitive manner. A system identifier whose value is the empty string is not considered missing for the purposes of the conditions above.

Then, switch the insertion mode to "before html".

Anything else

If the document is not an iframe srcdoc document, then this is a parse error; if the parser cannot change the mode flag is false, set the Document to quirks mode.

In any case, switch the insertion mode to "before html", then reprocess the token.

13.2.6.4.2 The "before html" insertion mode

When the user agent is to apply the rules for the "before html" insertion mode, the user agent must handle the token as follows:

A DOCTYPE token

Parse error. Ignore the token.

A comment token

Insert a comment as the last child of the Document object.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Ignore the token.

A start tag whose tag name is "html"

Create an element for the token in the HTML namespace, with the Document as the intended parent. Append it to the Document object. Put this element in the stack of open elements.

Switch the insertion mode to "before head".

An end tag whose tag name is one of: "head", "body", "html", "br"

Act as described in the "anything else" entry below.

Any other end tag

Parse error. Ignore the token.

Anything else

Create an html element whose node document is the Document object. Append it to the Document object. Put this element in the stack of open elements.

Switch the insertion mode to "before head", then reprocess the token.

The document element can end up being removed from the Document object, e.g. by scripts; nothing in particular happens in such cases, content continues being appended to the nodes as described in the next section.

13.2.6.4.3 The "before head" insertion mode

When the user agent is to apply the rules for the "before head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Ignore the token.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "head"

Insert an HTML element for the token.

Set the head element pointer to the newly created head element.

Switch the insertion mode to "in head".

An end tag whose tag name is one of: "head", "body", "html", "br"

Act as described in the "anything else" entry below.

Any other end tag

Parse error. Ignore the token.

Anything else

Insert an HTML element for a "head" start tag token with no attributes.

Set the head element pointer to the newly created head element.

Switch the insertion mode to "in head".

Reprocess the current token.

13.2.6.4.4 The "in head" insertion mode

When the user agent is to apply the rules for the "in head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

A start tag whose tag name is "meta"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

If the active speculative HTML parser is null, then:

  1. If the element has a charset attribute, and getting an encoding from its value results in an encoding, and the confidence is currently tentative, then change the encoding to the resulting encoding.

  2. Otherwise, if the element has an http-equiv attribute whose value is an ASCII case-insensitive match for the string "Content-Type", and the element has a content attribute, and applying the algorithm for extracting a character encoding from a meta element to that attribute's value returns an encoding, and the confidence is currently tentative, then change the encoding to the extracted encoding.

The speculative HTML parser doesn't speculatively apply character encoding declarations in order to reduce implementation complexity.

A start tag whose tag name is "title"

Follow the generic RCDATA element parsing algorithm.

A start tag whose tag name is "noscript", if the scripting flag is enabled
A start tag whose tag name is one of: "noframes", "style"

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "noscript", if the scripting flag is disabled

Insert an HTML element for the token.

Switch the insertion mode to "in head noscript".

A start tag whose tag name is "script"

Run these steps:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.

  2. Create an element for the token in the HTML namespace, with the intended parent being the element in which the adjusted insertion location finds itself.

  3. Set the element's parser document to the Document, and set the element's force async to false.

    This ensures that, if the script is external, any document.write() calls in the script will execute in-line, instead of blowing the document away, as would happen in most other cases. It also prevents the script from executing until the end tag is seen.

  4. If the parser was created as part of the HTML fragment parsing algorithm, then set the script element's already started to true. (fragment case)

  5. If the parser was invoked via the document.write() or document.writeln() methods, then optionally set the script element's already started to true. (For example, the user agent might use this clause to prevent execution of cross-origin scripts inserted via document.write() under slow network conditions, or when the page has already taken a long time to load.)

  6. Insert the newly created element at the adjusted insertion location.

  7. Push the element onto the stack of open elements so that it is the new current node.

  8. Switch the tokenizer to the script data state.

  9. Let the original insertion mode be the current insertion mode.

  10. Switch the insertion mode to "text".

An end tag whose tag name is "head"

Pop the current node (which will be the head element) off the stack of open elements.

Switch the insertion mode to "after head".

An end tag whose tag name is one of: "body", "html", "br"

Act as described in the "anything else" entry below.

A start tag whose tag name is "template"

Let template start tag be the start tag.

Insert a marker at the end of the list of active formatting elements.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in template".

Push "in template" onto the stack of template insertion modes so that it is the new current template insertion mode.

Let the adjusted insertion location be the appropriate place for inserting a node.

Let intended parent be the element in which the adjusted insertion location finds itself.

Let document be intended parent's node document.

If any of the following are false:

then insert an HTML element for the token.

Otherwise:

  1. Let declarative shadow host element be adjusted current node.

  2. Let template be the result of insert a foreign element for template start tag, with HTML namespace and true.

  3. Let mode be template start tag's shadowrootmode attribute's value.

  4. Let clonable be true if template start tag has a shadowrootclonable attribute; otherwise false.

  5. Let serializable be true if template start tag has a shadowrootserializable attribute; otherwise false.

  6. Let delegatesFocus be true if template start tag has a shadowrootdelegatesfocus attribute; otherwise false.

  7. If declarative shadow host element is a shadow host, then insert an element at the adjusted insertion location with template.

  8. Otherwise:

    1. Attach a shadow root with declarative shadow host element, mode, clonable, serializable, delegatesFocus, and "named".

      If an exception is thrown, then catch it and:

      1. Insert an element at the adjusted insertion location with template.

      2. The user agent may report an error to the developer console.

      3. Return.

    2. Let shadow be declarative shadow host element's shadow root.

    3. Set shadow's declarative to true.

    4. Set template's template contents property to shadow.

    5. Set shadow's available to element internals to true.

An end tag whose tag name is "template"

If there is no template element on the stack of open elements, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate all implied end tags thoroughly.

  2. If the current node is not a template element, then this is a parse error.

  3. Pop elements from the stack of open elements until a template element has been popped from the stack.

  4. Clear the list of active formatting elements up to the last marker.
  5. Pop the current template insertion mode off the stack of template insertion modes.

  6. Reset the insertion mode appropriately.

A start tag whose tag name is "head"
Any other end tag

Parse error. Ignore the token.

Anything else

Pop the current node (which will be the head element) off the stack of open elements.

Switch the insertion mode to "after head".

Reprocess the token.

13.2.6.4.5 The "in head noscript" insertion mode

When the user agent is to apply the rules for the "in head noscript" insertion mode, the user agent must handle the token as follows:

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end tag whose tag name is "noscript"

Pop the current node (which will be a noscript element) from the stack of open elements; the new current node will be a head element.

Switch the insertion mode to "in head".

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
A comment token
A start tag whose tag name is one of: "basefont", "bgsound", "link", "meta", "noframes", "style"

Process the token using the rules for the "in head" insertion mode.

An end tag whose tag name is "br"

Act as described in the "anything else" entry below.

A start tag whose tag name is one of: "head", "noscript"
Any other end tag

Parse error. Ignore the token.

Anything else

Parse error.

Pop the current node (which will be a noscript element) from the stack of open elements; the new current node will be a head element.

Switch the insertion mode to "in head".

Reprocess the token.

13.2.6.4.6 The "after head" insertion mode

When the user agent is to apply the rules for the "after head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "body"

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in body".

A start tag whose tag name is "frameset"

Insert an HTML element for the token.

Switch the insertion mode to "in frameset".

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"

Parse error.

Push the node pointed to by the head element pointer onto the stack of open elements.

Process the token using the rules for the "in head" insertion mode.

Remove the node pointed to by the head element pointer from the stack of open elements. (It might not be the current node at this point.)

The head element pointer cannot be null at this point.

An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

An end tag whose tag name is one of: "body", "html", "br"

Act as described in the "anything else" entry below.

A start tag whose tag name is "head"
Any other end tag

Parse error. Ignore the token.

Anything else

Insert an HTML element for a "body" start tag token with no attributes.

Switch the insertion mode to "in body".

Reprocess the current token.

13.2.6.4.7 The "in body" insertion mode

When the user agent is to apply the rules for the "in body" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Ignore the token.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Reconstruct the active formatting elements, if any.

Insert the token's character.

Any other character token

Reconstruct the active formatting elements, if any.

Insert the token's character.

Set the frameset-ok flag to "not ok".

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Parse error.

If there is a template element on the stack of open elements, then ignore the token.

Otherwise, for each attribute on the token, check to see if the attribute is already present on the top element of the stack of open elements. If it is not, add the attribute and its corresponding value to that element.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

A start tag whose tag name is "body"

Parse error.

If the stack of open elements has only one node on it, if the second element on the stack of open elements is not a body element, or if there is a template element on the stack of open elements, then ignore the token. (fragment case or there is a template element on the stack)

Otherwise, set the frameset-ok flag to "not ok"; then, for each attribute on the token, check to see if the attribute is already present on the body element (the second element) on the stack of open elements, and if it is not, add the attribute and its corresponding value to that element.

A start tag whose tag name is "frameset"

Parse error.

If the stack of open elements has only one node on it, or if the second element on the stack of open elements is not a body element, then ignore the token. (fragment case or there is a template element on the stack)

If the frameset-ok flag is set to "not ok", ignore the token.

Otherwise, run the following steps:

  1. Remove the second element on the stack of open elements from its parent node, if it has one.

  2. Pop all the nodes from the bottom of the stack of open elements, from the current node up to, but not including, the root html element.

  3. Insert an HTML element for the token.

  4. Switch the insertion mode to "in frameset".

An end-of-file token

If the stack of template insertion modes is not empty, then process the token using the rules for the "in template" insertion mode.

Otherwise, follow these steps:

  1. If there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

  2. Stop parsing.

An end tag whose tag name is "body"

If the stack of open elements does not have a body element in scope, this is a parse error; ignore the token.

Otherwise, if there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

Switch the insertion mode to "after body".

An end tag whose tag name is "html"

If the stack of open elements does not have a body element in scope, this is a parse error; ignore the token.

Otherwise, if there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

Switch the insertion mode to "after body".

Reprocess the token.

A start tag whose tag name is one of: "address", "article", "aside", "blockquote", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "search", "section", "summary", "ul"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

A start tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"

If the stack of open elements has a p element in button scope, then close a p element.

If the current node is an HTML element whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this is a parse error; pop the current node off the stack of open elements.

Insert an HTML element for the token.

A start tag whose tag name is one of: "pre", "listing"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "form"

If the form element pointer is not null, and there is no template element on the stack of open elements, then this is a parse error; ignore the token.

Otherwise:

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token, and, if there is no template element on the stack of open elements, set the form element pointer to point to the element created.

A start tag whose tag name is "li"

Run these steps:

  1. Set the frameset-ok flag to "not ok".

  2. Initialize node to be the current node (the bottommost node of the stack).

  3. Loop: If node is an li element, then run these substeps:

    1. Generate implied end tags, except for li elements.

    2. If the current node is not an li element, then this is a parse error.

    3. Pop elements from the stack of open elements until an li element has been popped from the stack.

    4. Jump to the step labeled done below.

  4. If node is in the special category, but is not an address, div, or p element, then jump to the step labeled done below.

  5. Otherwise, set node to the previous entry in the stack of open elements and return to the step labeled loop.

  6. Done: If the stack of open elements has a p element in button scope, then close a p element.

  7. Finally, insert an HTML element for the token.

A start tag whose tag name is one of: "dd", "dt"

Run these steps:

  1. Set the frameset-ok flag to "not ok".

  2. Initialize node to be the current node (the bottommost node of the stack).

  3. Loop: If node is a dd element, then run these substeps:

    1. Generate implied end tags, except for dd elements.

    2. If the current node is not a dd element, then this is a parse error.

    3. Pop elements from the stack of open elements until a dd element has been popped from the stack.

    4. Jump to the step labeled done below.

  4. If node is a dt element, then run these substeps:

    1. Generate implied end tags, except for dt elements.

    2. If the current node is not a dt element, then this is a parse error.

    3. Pop elements from the stack of open elements until a dt element has been popped from the stack.

    4. Jump to the step labeled done below.

  5. If node is in the special category, but is not an address, div, or p element, then jump to the step labeled done below.

  6. Otherwise, set node to the previous entry in the stack of open elements and return to the step labeled loop.

  7. Done: If the stack of open elements has a p element in button scope, then close a p element.

  8. Finally, insert an HTML element for the token.

A start tag whose tag name is "plaintext"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

Switch the tokenizer to the PLAINTEXT state.

Once a start tag with the tag name "plaintext" has been seen, all remaining tokens will be character tokens (and a final end-of-file token) because there is no way to switch the tokenizer out of the PLAINTEXT state. However, as the tree builder remains in its existing insertion mode, it might reconstruct the active formatting elements while processing those character tokens. This means that the parser can insert other elements into the plaintext element.

A start tag whose tag name is "button"
  1. If the stack of open elements has a button element in scope, then run these substeps:

    1. Parse error.

    2. Generate implied end tags.

    3. Pop elements from the stack of open elements until a button element has been popped from the stack.

  2. Reconstruct the active formatting elements, if any.

  3. Insert an HTML element for the token.

  4. Set the frameset-ok flag to "not ok".

An end tag whose tag name is one of: "address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre", "search", "section", "summary", "ul"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

An end tag whose tag name is "form"

If there is no template element on the stack of open elements, then run these substeps:

  1. Let node be the element that the form element pointer is set to, or null if it is not set to an element.

  2. Set the form element pointer to null.

  3. If node is null or if the stack of open elements does not have node in scope, then this is a parse error; return and ignore the token.

  4. Generate implied end tags.

  5. If the current node is not node, then this is a parse error.

  6. Remove node from the stack of open elements.

If there is a template element on the stack of open elements, then run these substeps instead:

  1. If the stack of open elements does not have a form element in scope, then this is a parse error; return and ignore the token.

  2. Generate implied end tags.

  3. If the current node is not a form element, then this is a parse error.

  4. Pop elements from the stack of open elements until a form element has been popped from the stack.

An end tag whose tag name is "p"

If the stack of open elements does not have a p element in button scope, then this is a parse error; insert an HTML element for a "p" start tag token with no attributes.

Close a p element.

An end tag whose tag name is "li"

If the stack of open elements does not have an li element in list item scope, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags, except for li elements.

  2. If the current node is not an li element, then this is a parse error.

  3. Pop elements from the stack of open elements until an li element has been popped from the stack.

An end tag whose tag name is one of: "dd", "dt"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags, except for HTML elements with the same tag name as the token.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

An end tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"

If the stack of open elements does not have an element in scope that is an HTML element and whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6" has been popped from the stack.

An end tag whose tag name is "sarcasm"

Take a deep breath, then act as described in the "any other end tag" entry below.

A start tag whose tag name is "a"

If the list of active formatting elements contains an a element between the end of the list and the last marker on the list (or the start of the list if there is no marker on the list), then this is a parse error; run the adoption agency algorithm for the token, then remove that element from the list of active formatting elements and the stack of open elements if the adoption agency algorithm didn't already remove it (it might not have if the element is not in table scope).

In the non-conforming stream <a href="a">a<table><a href="b">b</table>x, the first a element would be closed upon seeing the second one, and the "x" character would be inside a link to "b", not to "a". This is despite the fact that the outer a element is not in table scope (meaning that a regular </a> end tag at the start of the table wouldn't close the outer a element). The result is that the two a elements are indirectly nested inside each other — non-conforming markup will often result in non-conforming DOMs when parsed.

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

A start tag whose tag name is one of: "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

A start tag whose tag name is "nobr"

Reconstruct the active formatting elements, if any.

If the stack of open elements has a nobr element in scope, then this is a parse error; run the adoption agency algorithm for the token, then once again reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

An end tag whose tag name is one of: "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"

Run the adoption agency algorithm for the token.

A start tag whose tag name is one of: "applet", "marquee", "object"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

Insert a marker at the end of the list of active formatting elements.

Set the frameset-ok flag to "not ok".

An end tag token whose tag name is one of: "applet", "marquee", "object"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

  4. Clear the list of active formatting elements up to the last marker.
A start tag whose tag name is "table"

If the Document is not set to quirks mode, and the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in table".

An end tag whose tag name is "br"

Parse error. Drop the attributes from the token, and act as described in the next entry; i.e. act as if this was a "br" start tag token with no attributes, rather than the end tag token that it actually is.

A start tag whose tag name is one of: "area", "br", "embed", "img", "keygen", "wbr"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "input"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

If the token does not have an attribute with the name "type", or if it does, but that attribute's value is not an ASCII case-insensitive match for the string "hidden", then: set the frameset-ok flag to "not ok".

A start tag whose tag name is one of: "param", "source", "track"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

A start tag whose tag name is "hr"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "image"

Parse error. Change the token's tag name to "img" and reprocess it. (Don't ask.)

A start tag whose tag name is "textarea"

Run these steps:

  1. Insert an HTML element for the token.

  2. If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)

  3. Switch the tokenizer to the RCDATA state.

  4. Let the original insertion mode be the current insertion mode.

  5. Set the frameset-ok flag to "not ok".

  6. Switch the insertion mode to "text".

A start tag whose tag name is "xmp"

If the stack of open elements has a p element in button scope, then close a p element.

Reconstruct the active formatting elements, if any.

Set the frameset-ok flag to "not ok".

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "iframe"

Set the frameset-ok flag to "not ok".

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "noembed"
A start tag whose tag name is "noscript", if the scripting flag is enabled

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "select"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

If the insertion mode is one of "in table", "in caption", "in table body", "in row", or "in cell", then switch the insertion mode to "in select in table". Otherwise, switch the insertion mode to "in select".

A start tag whose tag name is one of: "optgroup", "option"

If the current node is an option element, then pop the current node off the stack of open elements.

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

A start tag whose tag name is one of: "rb", "rtc"

If the stack of open elements has a ruby element in scope, then generate implied end tags. If the current node is not now a ruby element, this is a parse error.

Insert an HTML element for the token.

A start tag whose tag name is one of: "rp", "rt"

If the stack of open elements has a ruby element in scope, then generate implied end tags, except for rtc elements. If the current node is not now a rtc element or a ruby element, this is a parse error.

Insert an HTML element for the token.

A start tag whose tag name is "math"

Reconstruct the active formatting elements, if any.

Adjust MathML attributes for the token. (This fixes the case of MathML attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink.)

Insert a foreign element for the token, with MathML namespace and false.

If the token has its self-closing flag set, pop the current node off the stack of open elements and acknowledge the token's self-closing flag.

A start tag whose tag name is "svg"

Reconstruct the active formatting elements, if any.

Adjust SVG attributes for the token. (This fixes the case of SVG attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink in SVG.)

Insert a foreign element for the token, with SVG namespace and false.

If the token has its self-closing flag set, pop the current node off the stack of open elements and acknowledge the token's self-closing flag.

A start tag whose tag name is one of: "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"

Parse error. Ignore the token.

Any other start tag

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

This element will be an ordinary element. With one exception: if the scripting flag is disabled, it can also be a noscript element.

Any other end tag

Run these steps:

  1. Initialize node to be the current node (the bottommost node of the stack).

  2. Loop: If node is an HTML element with the same tag name as the token, then:

    1. Generate implied end tags, except for HTML elements with the same tag name as the token.

    2. If node is not the current node, then this is a parse error.

    3. Pop all the nodes from the current node up to node, including node, then stop these steps.

  3. Otherwise, if node is in the special category, then this is a parse error; ignore the token, and return.

  4. Set node to the previous entry in the stack of open elements.

  5. Return to the step labeled loop.

When the steps above say the user agent is to close a p element, it means that the user agent must run the following steps:

  1. Generate implied end tags, except for p elements.

  2. If the current node is not a p element, then this is a parse error.

  3. Pop elements from the stack of open elements until a p element has been popped from the stack.

The adoption agency algorithm, which takes as its only argument a token token for which the algorithm is being run, consists of the following steps:

  1. Let subject be token's tag name.

  2. If the current node is an HTML element whose tag name is subject, and the current node is not in the list of active formatting elements, then pop the current node off the stack of open elements and return.

  3. Let outerLoopCounter be 0.

  4. While true:

    1. If outerLoopCounter is greater than or equal to 8, then return.

    2. Increment outerLoopCounter by 1.

    3. Let formattingElement be the last element in the list of active formatting elements that:

      • is between the end of the list and the last marker in the list, if any, or the start of the list otherwise, and
      • has the tag name subject.

      If there is no such element, then return and instead act as described in the "any other end tag" entry above.

    4. If formattingElement is not in the stack of open elements, then this is a parse error; remove the element from the list, and return.

    5. If formattingElement is in the stack of open elements, but the element is not in scope, then this is a parse error; return.

    6. If formattingElement is not the current node, this is a parse error. (But do not return.)

    7. Let furthestBlock be the topmost node in the stack of open elements that is lower in the stack than formattingElement, and is an element in the special category. There might not be one.

    8. If there is no furthestBlock, then the UA must first pop all the nodes from the bottom of the stack of open elements, from the current node up to and including formattingElement, then remove formattingElement from the list of active formatting elements, and finally return.

    9. Let commonAncestor be the element immediately above formattingElement in the stack of open elements.

    10. Let a bookmark note the position of formattingElement in the list of active formatting elements relative to the elements on either side of it in the list.

    11. Let node and lastNode be furthestBlock.

    12. Let innerLoopCounter be 0.

    13. While true:

      1. Increment innerLoopCounter by 1.

      2. Let node be the element immediately above node in the stack of open elements, or if node is no longer in the stack of open elements (e.g. because it got removed by this algorithm), the element that was immediately above node in the stack of open elements before node was removed.

      3. If node is formattingElement, then break.

      4. If innerLoopCounter is greater than 3 and node is in the list of active formatting elements, then remove node from the list of active formatting elements.

      5. If node is not in the list of active formatting elements, then remove node from the stack of open elements and continue.

      6. Create an element for the token for which the element node was created, in the HTML namespace, with commonAncestor as the intended parent; replace the entry for node in the list of active formatting elements with an entry for the new element, replace the entry for node in the stack of open elements with an entry for the new element, and let node be the new element.

      7. If last node is furthestBlock, then move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.

      8. Append lastNode to node.

      9. Set lastNode to node.

    14. Insert whatever lastNode ended up being in the previous step at the appropriate place for inserting a node, but using commonAncestor as the override target.

    15. Create an element for the token for which formattingElement was created, in the HTML namespace, with furthestBlock as the intended parent.

    16. Take all of the child nodes of furthestBlock and append them to the element created in the last step.

    17. Append that new element to furthestBlock.

    18. Remove formattingElement from the list of active formatting elements, and insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.

    19. Remove formattingElement from the stack of open elements, and insert the new element into the stack of open elements immediately below the position of furthestBlock in that stack.

This algorithm's name, the "adoption agency algorithm", comes from the way it causes elements to change parents, and is in contrast with other possible algorithms for dealing with misnested content.

13.2.6.4.8 The "text" insertion mode

When the user agent is to apply the rules for the "text" insertion mode, the user agent must handle the token as follows:

A character token

Insert the token's character.

This can never be a U+0000 NULL character; the tokenizer converts those to U+FFFD REPLACEMENT CHARACTER characters.

An end-of-file token

Parse error.

If the current node is a script element, then set its already started to true.

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode and reprocess the token.

An end tag whose tag name is "script"

If the active speculative HTML parser is null and the JavaScript execution context stack is empty, then perform a microtask checkpoint.

Let script be the current node (which will be a script element).

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode.

Let the old insertion point have the same value as the current insertion point. Let the insertion point be just before the next input character.

Increment the parser's script nesting level by one.

If the active speculative HTML parser is null, then prepare the script element script. This might cause some script to execute, which might cause new characters to be inserted into the tokenizer, and might cause the tokenizer to output more tokens, resulting in a reentrant invocation of the parser.

Decrement the parser's script nesting level by one. If the parser's script nesting level is zero, then set the parser pause flag to false.

Let the insertion point have the value of the old insertion point. (In other words, restore the insertion point to its previous value. This value might be the "undefined" value.)

At this stage, if the pending parsing-blocking script is not null, then:

If the script nesting level is not zero:

Set the parser pause flag to true, and abort the processing of any nested invocations of the tokenizer, yielding control back to the caller. (Tokenization will resume when the caller returns to the "outer" tree construction stage.)

The tree construction stage of this particular parser is being called reentrantly, say from a call to document.write().

Otherwise:

While the pending parsing-blocking script is not null:

  1. Let the script be the pending parsing-blocking script.

  2. Set the pending parsing-blocking script to null.

  3. Start the speculative HTML parser for this instance of the HTML parser.

  4. Block the tokenizer for this instance of the HTML parser, such that the event loop will not run tasks that invoke the tokenizer.

  5. If the parser's Document has a style sheet that is blocking scripts or the script's ready to be parser-executed is false: spin the event loop until the parser's Document has no style sheet that is blocking scripts and the script's ready to be parser-executed becomes true.

  6. If this parser has been aborted in the meantime, return.

    This could happen if, e.g., while the spin the event loop algorithm is running, the Document gets destroyed, or the document.open() method gets invoked on the Document.

  7. Stop the speculative HTML parser for this instance of the HTML parser.

  8. Unblock the tokenizer for this instance of the HTML parser, such that tasks that invoke the tokenizer can again be run.

  9. Let the insertion point be just before the next input character.

  10. Increment the parser's script nesting level by one (it should be zero before this step, so this sets it to one).

  11. Execute the script element the script.

  12. Decrement the parser's script nesting level by one. If the parser's script nesting level is zero (which it always should be at this point), then set the parser pause flag to false.

  13. Let the insertion point be undefined again.

Any other end tag

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode.

13.2.6.4.9 The "in table" insertion mode

When the user agent is to apply the rules for the "in table" insertion mode, the user agent must handle the token as follows:

A character token, if the current node is table, tbody, template, tfoot, thead, or tr element

Let the pending table character tokens be an empty list of tokens.

Let the original insertion mode be the current insertion mode.

Switch the insertion mode to "in table text" and reprocess the token.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "caption"

Clear the stack back to a table context. (See below.)

Insert a marker at the end of the list of active formatting elements.

Insert an HTML element for the token, then switch the insertion mode to "in caption".

A start tag whose tag name is "colgroup"

Clear the stack back to a table context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in column group".

A start tag whose tag name is "col"

Clear the stack back to a table context. (See below.)

Insert an HTML element for a "colgroup" start tag token with no attributes, then switch the insertion mode to "in column group".

Reprocess the current token.

A start tag whose tag name is one of: "tbody", "tfoot", "thead"

Clear the stack back to a table context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in table body".

A start tag whose tag name is one of: "td", "th", "tr"

Clear the stack back to a table context. (See below.)

Insert an HTML element for a "tbody" start tag token with no attributes, then switch the insertion mode to "in table body".

Reprocess the current token.

A start tag whose tag name is "table"

Parse error.

If the stack of open elements does not have a table element in table scope, ignore the token.

Otherwise:

Pop elements from this stack until a table element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

An end tag whose tag name is "table"

If the stack of open elements does not have a table element in table scope, this is a parse error; ignore the token.

Otherwise:

Pop elements from this stack until a table element has been popped from the stack.

Reset the insertion mode appropriately.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"

Parse error. Ignore the token.

A start tag whose tag name is one of: "style", "script", "template"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

A start tag whose tag name is "input"

If the token does not have an attribute with the name "type", or if it does, but that attribute's value is not an ASCII case-insensitive match for the string "hidden", then: act as described in the "anything else" entry below.

Otherwise:

Parse error.

Insert an HTML element for the token.

Pop that input element off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

A start tag whose tag name is "form"

Parse error.

If there is a template element on the stack of open elements, or if the form element pointer is not null, ignore the token.

Otherwise:

Insert an HTML element for the token, and set the form element pointer to point to the element created.

Pop that form element off the stack of open elements.

An end-of-file token

Process the token using the rules for the "in body" insertion mode.

Anything else

Parse error. Enable foster parenting, process the token using the rules for the "in body" insertion mode, and then disable foster parenting.

When the steps above require the UA to clear the stack back to a table context, it means that the UA must, while the current node is not a table, template, or html element, pop elements from the stack of open elements.

This is the same list of elements as used in the has an element in table scope steps.

The current node being an html element after this process is a fragment case.

13.2.6.4.10 The "in table text" insertion mode

When the user agent is to apply the rules for the "in table text" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Ignore the token.

Any other character token

Append the character token to the pending table character tokens list.

Anything else

If any of the tokens in the pending table character tokens list are character tokens that are not ASCII whitespace, then this is a parse error: reprocess the character tokens in the pending table character tokens list using the rules given in the "anything else" entry in the "in table" insertion mode.

Otherwise, insert the characters given by the pending table character tokens list.

Switch the insertion mode to the original insertion mode and reprocess the token.

13.2.6.4.11 The "in caption" insertion mode

When the user agent is to apply the rules for the "in caption" insertion mode, the user agent must handle the token as follows:

An end tag whose tag name is "caption"

If the stack of open elements does not have a caption element in table scope, this is a parse error; ignore the token. (fragment case)

Otherwise:

Generate implied end tags.

Now, if the current node is not a caption element, then this is a parse error.

Pop elements from this stack until a caption element has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Switch the insertion mode to "in table".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"
An end tag whose tag name is "table"

If the stack of open elements does not have a caption element in table scope, this is a parse error; ignore the token. (fragment case)

Otherwise:

Generate implied end tags.

Now, if the current node is not a caption element, then this is a parse error.

Pop elements from this stack until a caption element has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Switch the insertion mode to "in table".

Reprocess the token.

An end tag whose tag name is one of: "body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"

Parse error. Ignore the token.

Anything else

Process the token using the rules for the "in body" insertion mode.

13.2.6.4.12 The "in column group" insertion mode

When the user agent is to apply the rules for the "in column group" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "col"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

An end tag whose tag name is "colgroup"

If the current node is not a colgroup element, then this is a parse error; ignore the token.

Otherwise, pop the current node from the stack of open elements. Switch the insertion mode to "in table".

An end tag whose tag name is "col"

Parse error. Ignore the token.

A start tag whose tag name is "template"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

Process the token using the rules for the "in body" insertion mode.

Anything else

If the current node is not a colgroup element, then this is a parse error; ignore the token.

Otherwise, pop the current node from the stack of open elements.

Switch the insertion mode to "in table".

Reprocess the token.

13.2.6.4.13 The "in table body" insertion mode

When the user agent is to apply the rules for the "in table body" insertion mode, the user agent must handle the token as follows:

A start tag whose tag name is "tr"

Clear the stack back to a table body context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in row".

A start tag whose tag name is one of: "th", "td"

Parse error.

Clear the stack back to a table body context. (See below.)

Insert an HTML element for a "tr" start tag token with no attributes, then switch the insertion mode to "in row".

Reprocess the current token.

An end tag whose tag name is one of: "tbody", "tfoot", "thead"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as the token, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table body context. (See below.)

Pop the current node from the stack of open elements. Switch the insertion mode to "in table".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "tfoot", "thead"
An end tag whose tag name is "table"

If the stack of open elements does not have a tbody, thead, or tfoot element in table scope, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table body context. (See below.)

Pop the current node from the stack of open elements. Switch the insertion mode to "in table".

Reprocess the token.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html", "td", "th", "tr"

Parse error. Ignore the token.

Anything else

Process the token using the rules for the "in table" insertion mode.

When the steps above require the UA to clear the stack back to a table body context, it means that the UA must, while the current node is not a tbody, tfoot, thead, template, or html element, pop elements from the stack of open elements.

The current node being an html element after this process is a fragment case.

13.2.6.4.14 The "in row" insertion mode

When the user agent is to apply the rules for the "in row" insertion mode, the user agent must handle the token as follows:

A start tag whose tag name is one of: "th", "td"

Clear the stack back to a table row context. (See below.)

Insert an HTML element for the token, then switch the insertion mode to "in cell".

Insert a marker at the end of the list of active formatting elements.

An end tag whose tag name is "tr"

If the stack of open elements does not have a tr element in table scope, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table row context. (See below.)

Pop the current node (which will be a tr element) from the stack of open elements. Switch the insertion mode to "in table body".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr"
An end tag whose tag name is "table"

If the stack of open elements does not have a tr element in table scope, this is a parse error; ignore the token.

Otherwise:

Clear the stack back to a table row context. (See below.)

Pop the current node (which will be a tr element) from the stack of open elements. Switch the insertion mode to "in table body".

Reprocess the token.

An end tag whose tag name is one of: "tbody", "tfoot", "thead"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as the token, this is a parse error; ignore the token.

If the stack of open elements does not have a tr element in table scope, ignore the token.

Otherwise:

Clear the stack back to a table row context. (See below.)

Pop the current node (which will be a tr element) from the stack of open elements. Switch the insertion mode to "in table body".

Reprocess the token.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html", "td", "th"

Parse error. Ignore the token.

Anything else

Process the token using the rules for the "in table" insertion mode.

When the steps above require the UA to clear the stack back to a table row context, it means that the UA must, while the current node is not a tr, template, or html element, pop elements from the stack of open elements.

The current node being an html element after this process is a fragment case.

13.2.6.4.15 The "in cell" insertion mode

When the user agent is to apply the rules for the "in cell" insertion mode, the user agent must handle the token as follows:

An end tag whose tag name is one of: "td", "th"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise:

Generate implied end tags.

Now, if the current node is not an HTML element with the same tag name as the token, then this is a parse error.

Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Switch the insertion mode to "in row".

A start tag whose tag name is one of: "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"

Assert: The stack of open elements has a td or th element in table scope.

Close the cell (see below) and reprocess the token.

An end tag whose tag name is one of: "body", "caption", "col", "colgroup", "html"

Parse error. Ignore the token.

An end tag whose tag name is one of: "table", "tbody", "tfoot", "thead", "tr"

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, close the cell (see below) and reprocess the token.

Anything else

Process the token using the rules for the "in body" insertion mode.

Where the steps above say to close the cell, they mean to run the following algorithm:

  1. Generate implied end tags.

  2. If the current node is not now a td element or a th element, then this is a parse error.

  3. Pop elements from the stack of open elements until a td element or a th element has been popped from the stack.

  4. Clear the list of active formatting elements up to the last marker.

  5. Switch the insertion mode to "in row".

The stack of open elements cannot have both a td and a th element in table scope at the same time, nor can it have neither when the close the cell algorithm is invoked.

13.2.6.4.16 The "in select" insertion mode

When the user agent is to apply the rules for the "in select" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Ignore the token.

Any other character token

Insert the token's character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "option"

If the current node is an option element, pop that node from the stack of open elements.

Insert an HTML element for the token.

A start tag whose tag name is "optgroup"

If the current node is an option element, pop that node from the stack of open elements.

If the current node is an optgroup element, pop that node from the stack of open elements.

Insert an HTML element for the token.

A start tag whose tag name is "hr"

If the current node is an option element, pop that node from the stack of open elements.

If the current node is an optgroup element, pop that node from the stack of open elements.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

An end tag whose tag name is "optgroup"

First, if the current node is an option element, and the node immediately before it in the stack of open elements is an optgroup element, then pop the current node from the stack of open elements.

If the current node is an optgroup element, then pop that node from the stack of open elements. Otherwise, this is a parse error; ignore the token.

An end tag whose tag name is "option"

If the current node is an option element, then pop that node from the stack of open elements. Otherwise, this is a parse error; ignore the token.

An end tag whose tag name is "select"

If the stack of open elements does not have a select element in select scope, this is a parse error; ignore the token. (fragment case)

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

A start tag whose tag name is "select"

Parse error.

If the stack of open elements does not have a select element in select scope, ignore the token. (fragment case)

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

It just gets treated like an end tag.

A start tag whose tag name is one of: "input", "keygen", "textarea"

Parse error.

If the stack of open elements does not have a select element in select scope, ignore the token. (fragment case)

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

A start tag whose tag name is one of: "script", "template"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

Process the token using the rules for the "in body" insertion mode.

Anything else

Parse error. Ignore the token.

13.2.6.4.17 The "in select in table" insertion mode

When the user agent is to apply the rules for the "in select in table" insertion mode, the user agent must handle the token as follows:

A start tag whose tag name is one of: "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"

Parse error.

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

An end tag whose tag name is one of: "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"

Parse error.

If the stack of open elements does not have an element in table scope that is an HTML element with the same tag name as that of the token, then ignore the token.

Otherwise:

Pop elements from the stack of open elements until a select element has been popped from the stack.

Reset the insertion mode appropriately.

Reprocess the token.

Anything else

Process the token using the rules for the "in select" insertion mode.

13.2.6.4.18 The "in template" insertion mode

When the user agent is to apply the rules for the "in template" insertion mode, the user agent must handle the token as follows:

A character token
A comment token
A DOCTYPE token

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

A start tag whose tag name is one of: "caption", "colgroup", "tbody", "tfoot", "thead"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in table" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in table", and reprocess the token.

A start tag whose tag name is "col"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in column group" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in column group", and reprocess the token.

A start tag whose tag name is "tr"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in table body" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in table body", and reprocess the token.

A start tag whose tag name is one of: "td", "th"

Pop the current template insertion mode off the stack of template insertion modes.

Push "in row" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in row", and reprocess the token.

Any other start tag

Pop the current template insertion mode off the stack of template insertion modes.

Push "in body" onto the stack of template insertion modes so that it is the new current template insertion mode.

Switch the insertion mode to "in body", and reprocess the token.

Any other end tag

Parse error. Ignore the token.

An end-of-file token

If there is no template element on the stack of open elements, then stop parsing. (fragment case)

Otherwise, this is a parse error.

Pop elements from the stack of open elements until a template element has been popped from the stack.

Clear the list of active formatting elements up to the last marker.

Pop the current template insertion mode off the stack of template insertion modes.

Reset the insertion mode appropriately.

Reprocess the token.

13.2.6.4.19 The "after body" insertion mode

When the user agent is to apply the rules for the "after body" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Process the token using the rules for the "in body" insertion mode.

A comment token

Insert a comment as the last child of the first element in the stack of open elements (the html element).

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end tag whose tag name is "html"

If the parser was created as part of the HTML fragment parsing algorithm, this is a parse error; ignore the token. (fragment case)

Otherwise, switch the insertion mode to "after after body".

An end-of-file token

Stop parsing.

Anything else

Parse error. Switch the insertion mode to "in body" and reprocess the token.

13.2.6.4.20 The "in frameset" insertion mode

When the user agent is to apply the rules for the "in frameset" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is "frameset"

Insert an HTML element for the token.

An end tag whose tag name is "frameset"

If the current node is the root html element, then this is a parse error; ignore the token. (fragment case)

Otherwise, pop the current node from the stack of open elements.

If the parser was not created as part of the HTML fragment parsing algorithm (fragment case), and the current node is no longer a frameset element, then switch the insertion mode to "after frameset".

A start tag whose tag name is "frame"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

A start tag whose tag name is "noframes"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

If the current node is not the root html element, then this is a parse error.

The current node can only be the root html element in the fragment case.

Stop parsing.

Anything else

Parse error. Ignore the token.

13.2.6.4.21 The "after frameset" insertion mode

When the user agent is to apply the rules for the "after frameset" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end tag whose tag name is "html"

Switch the insertion mode to "after after frameset".

A start tag whose tag name is "noframes"

Process the token using the rules for the "in head" insertion mode.

An end-of-file token

Stop parsing.

Anything else

Parse error. Ignore the token.

13.2.6.4.22 The "after after body" insertion mode

When the user agent is to apply the rules for the "after after body" insertion mode, the user agent must handle the token as follows:

A comment token

Insert a comment as the last child of the Document object.

A DOCTYPE token
A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end-of-file token

Stop parsing.

Anything else

Parse error. Switch the insertion mode to "in body" and reprocess the token.

13.2.6.4.23 The "after after frameset" insertion mode

When the user agent is to apply the rules for the "after after frameset" insertion mode, the user agent must handle the token as follows:

A comment token

Insert a comment as the last child of the Document object.

A DOCTYPE token
A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

An end-of-file token

Stop parsing.

A start tag whose tag name is "noframes"

Process the token using the rules for the "in head" insertion mode.

Anything else

Parse error. Ignore the token.

13.2.6.5 The rules for parsing tokens in foreign content

When the user agent is to apply the rules for parsing tokens in foreign content, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Insert a U+FFFD REPLACEMENT CHARACTER character.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the token's character.

Any other character token

Insert the token's character.

Set the frameset-ok flag to "not ok".

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is one of: "b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr", "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u", "ul", "var"
A start tag whose tag name is "font", if the token has any attributes named "color", "face", or "size"
An end tag whose tag name is "br", "p"

Parse error.

While the current node is not a MathML text integration point, an HTML integration point, or an element in the HTML namespace, pop elements from the stack of open elements.

Reprocess the token according to the rules given in the section corresponding to the current insertion mode in HTML content.

Any other start tag

If the adjusted current node is an element in the MathML namespace, adjust MathML attributes for the token. (This fixes the case of MathML attributes that are not all lowercase.)

If the adjusted current node is an element in the SVG namespace, and the token's tag name is one of the ones in the first column of the following table, change the tag name to the name given in the corresponding cell in the second column. (This fixes the case of SVG elements that are not all lowercase.)

Tag name Element name
altglyph altGlyph
altglyphdef altGlyphDef
altglyphitem altGlyphItem
animatecolor animateColor
animatemotion animateMotion
animatetransform animateTransform
clippath clipPath
feblend feBlend
fecolormatrix feColorMatrix
fecomponenttransfer feComponentTransfer
fecomposite feComposite
feconvolvematrix feConvolveMatrix
fediffuselighting feDiffuseLighting
fedisplacementmap feDisplacementMap
fedistantlight feDistantLight
fedropshadow feDropShadow
feflood feFlood
fefunca feFuncA
fefuncb feFuncB
fefuncg feFuncG
fefuncr feFuncR
fegaussianblur feGaussianBlur
feimage feImage
femerge feMerge
femergenode feMergeNode
femorphology feMorphology
feoffset feOffset
fepointlight fePointLight
fespecularlighting feSpecularLighting
fespotlight feSpotLight
fetile feTile
feturbulence feTurbulence
foreignobject foreignObject
glyphref glyphRef
lineargradient linearGradient
radialgradient radialGradient
textpath textPath

If the adjusted current node is an element in the SVG namespace, adjust SVG attributes for the token. (This fixes the case of SVG attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink in SVG.)

Insert a foreign element for the token, with adjusted current node's namespace and false.

If the token has its self-closing flag set, then run the appropriate steps from the following list:

If the token's tag name is "script", and the new current node is in the SVG namespace

Acknowledge the token's self-closing flag, and then act as described in the steps for a "script" end tag below.

Otherwise

Pop the current node off the stack of open elements and acknowledge the token's self-closing flag.

An end tag whose tag name is "script", if the current node is an SVG script element

Pop the current node off the stack of open elements.

Let the old insertion point have the same value as the current insertion point. Let the insertion point be just before the next input character.

Increment the parser's script nesting level by one. Set the parser pause flag to true.

If the active speculative HTML parser is null and the user agent supports SVG, then Process the SVG script element according to the SVG rules. [SVG]

Even if this causes new characters to be inserted into the tokenizer, the parser will not be executed reentrantly, since the parser pause flag is true.

Decrement the parser's script nesting level by one. If the parser's script nesting level is zero, then set the parser pause flag to false.

Let the insertion point have the value of the old insertion point. (In other words, restore the insertion point to its previous value. This value might be the "undefined" value.)

Any other end tag

Run these steps:

  1. Initialize node to be the current node (the bottommost node of the stack).

  2. If node's tag name, converted to ASCII lowercase, is not the same as the tag name of the token, then this is a parse error.

  3. Loop: If node is the topmost element in the stack of open elements, then return. (fragment case)

  4. If node's tag name, converted to ASCII lowercase, is the same as the tag name of the token, pop elements from the stack of open elements until node has been popped from the stack, and then return.

  5. Set node to the previous entry in the stack of open elements.

  6. If node is not an element in the HTML namespace, return to the step labeled loop.

  7. Otherwise, process the token according to the rules given in the section corresponding to the current insertion mode in HTML content.

13.2.7 The end

Document/DOMContentLoaded_event

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Once the user agent stops parsing the document, the user agent must run the following steps:

Window/load_event

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
  1. If the active speculative HTML parser is not null, then stop the speculative HTML parser and return.

  2. Set the insertion point to undefined.

  3. Update the current document readiness to "interactive".

  4. Pop all the nodes off the stack of open elements.

  5. While the list of scripts that will execute when the document has finished parsing is not empty:

    1. Spin the event loop until the first script in the list of scripts that will execute when the document has finished parsing has its ready to be parser-executed set to true and the parser's Document has no style sheet that is blocking scripts.

    2. Execute the script element given by the first script in the list of scripts that will execute when the document has finished parsing.

    3. Remove the first script element from the list of scripts that will execute when the document has finished parsing (i.e. shift out the first entry in the list).

  6. Queue a global task on the DOM manipulation task source given the Document's relevant global object to run the following substeps:

    1. Set the Document's load timing info's DOM content loaded event start time to the current high resolution time given the Document's relevant global object.

    2. Fire an event named DOMContentLoaded at the Document object, with its bubbles attribute initialized to true.

    3. Set the Document's load timing info's DOM content loaded event end time to the current high resolution time given the Document's relevant global object.

    4. Enable the client message queue of the ServiceWorkerContainer object whose associated service worker client is the Document object's relevant settings object.

    5. Invoke WebDriver BiDi DOM content loaded with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID for WebDriver BiDi, status is "pending", and url is the Document object's URL.

  7. Spin the event loop until the set of scripts that will execute as soon as possible and the list of scripts that will execute in order as soon as possible are empty.

  8. Spin the event loop until there is nothing that delays the load event in the Document.

  9. Queue a global task on the DOM manipulation task source given the Document's relevant global object to run the following steps:

    1. Update the current document readiness to "complete".

    2. If the Document object's browsing context is null, then abort these steps.

    3. Let window be the Document's relevant global object.

    4. Set the Document's load timing info's load event start time to the current high resolution time given window.

    5. Fire an event named load at window, with legacy target override flag set.

    6. Invoke WebDriver BiDi load complete with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID for WebDriver BiDi, status is "complete", and url is the Document object's URL.

    7. Set the Document object's during-loading navigation ID for WebDriver BiDi to null.

    8. Set the Document's load timing info's load event end time to the current high resolution time given window.

    9. Assert: Document's page showing is false.

    10. Set the Document's page showing flag to true.

    11. Fire a page transition event named pageshow at window with false.

    12. Completely finish loading the Document.

    13. Queue the navigation timing entry for the Document.

  10. If the Document's print when loaded flag is set, then run the printing steps.

  11. The Document is now ready for post-load tasks.

When the user agent is to abort a parser, it must run the following steps:

  1. Throw away any pending content in the input stream, and discard any future content that would have been added to it.

  2. Stop the speculative HTML parser for this HTML parser.

  3. Update the current document readiness to "interactive".

  4. Pop all the nodes off the stack of open elements.

  5. Update the current document readiness to "complete".

13.2.8 Speculative HTML parsing

User agents may implement an optimization, as described in this section, to speculatively fetch resources that are declared in the HTML markup while the HTML parser is waiting for a pending parsing-blocking script to be fetched and executed, or during normal parsing, at the time an element is created for a token. While this optimization is not defined in precise detail, there are some rules to consider for interoperability.

Each HTML parser can have an active speculative HTML parser. It is initially null.

The speculative HTML parser must act like the normal HTML parser (e.g., the tree builder rules apply), with some exceptions:

A speculative fetch for a speculative mock element element must follow these rules:

Should some of these things be applied to the document "for real", even though they are found speculatively?

Each Document has a list of speculative fetch URLs, which is a list of URLs, initially empty.

To start the speculative HTML parser for an instance of an HTML parser parser:

  1. Optionally, return.

    This step allows user agents to opt out of speculative HTML parsing.

  2. If parser's active speculative HTML parser is not null, then stop the speculative HTML parser for parser.

    This can happen when document.write() writes another parser-blocking script. For simplicity, this specification always restarts speculative parsing, but user agents can implement a more efficient strategy, so long as the end result is equivalent.

  3. Let speculativeParser be a new speculative HTML parser, with the same state as parser.

  4. Let speculativeDoc be a new isomorphic representation of parser's Document, where all elements are instead speculative mock elements. Let speculativeParser parse into speculativeDoc.

  5. Set parser's active speculative HTML parser to speculativeParser.

  6. In parallel, run speculativeParser until it is stopped or until it reaches the end of its input stream.

To stop the speculative HTML parser for an instance of an HTML parser parser:

  1. Let speculativeParser be parser's active speculative HTML parser.

  2. If speculativeParser is null, then return.

  3. Throw away any pending content in speculativeParser's input stream, and discard any future content that would have been added to it.

  4. Set parser's active speculative HTML parser to null.

The speculative HTML parser will create speculative mock elements instead of normal elements. DOM operations that the tree builder normally does on elements are expected to work appropriately on speculative mock elements.

A speculative mock element is a struct with the following items:

To create a speculative mock element given a namespace, tagName, and attributes:

  1. Let element be a new speculative mock element.

  2. Set element's namespace to namespace.

  3. Set element's local name to tagName.

  4. Set element's attribute list to attributes.

  5. Set element's children to a new empty list.

  6. Optionally, perform a speculative fetch for element.

  7. Return element.

When the tree builder says to insert an element into a template element's template contents, if that is a speculative mock element, and the template element's template contents is not a ShadowRoot node, instead do nothing. URLs found speculatively inside non-declarative-shadow-root template elements might themselves be templates, and must not be speculatively fetched.

13.2.9 Coercing an HTML DOM into an infoset

When an application uses an HTML parser in conjunction with an XML pipeline, it is possible that the constructed DOM is not compatible with the XML tool chain in certain subtle ways. For example, an XML toolchain might not be able to represent attributes with the name xmlns, since they conflict with the Namespaces in XML syntax. There is also some data that the HTML parser generates that isn't included in the DOM itself. This section specifies some rules for handling these issues.

If the XML API being used doesn't support DOCTYPEs, the tool may drop DOCTYPEs altogether.

If the XML API doesn't support attributes in no namespace that are named "xmlns", attributes whose names start with "xmlns:", or attributes in the XMLNS namespace, then the tool may drop such attributes.

The tool may annotate the output with any namespace declarations required for proper operation.

If the XML API being used restricts the allowable characters in the local names of elements and attributes, then the tool may map all element and attribute local names that the API wouldn't support to a set of names that are allowed, by replacing any character that isn't supported with the uppercase letter U and the six digits of the character's code point when expressed in hexadecimal, using digits 0-9 and capital letters A-F as the symbols, in increasing numeric order.

For example, the element name foo<bar, which can be output by the HTML parser, though it is neither a legal HTML element name nor a well-formed XML element name, would be converted into fooU00003Cbar, which is a well-formed XML element name (though it's still not legal in HTML by any means).

As another example, consider the attribute xlink:href. Used on a MathML element, it becomes, after being adjusted, an attribute with a prefix "xlink" and a local name "href". However, used on an HTML element, it becomes an attribute with no prefix and the local name "xlink:href", which is not a valid NCName, and thus might not be accepted by an XML API. It could thus get converted, becoming "xlinkU00003Ahref".

The resulting names from this conversion conveniently can't clash with any attribute generated by the HTML parser, since those are all either lowercase or those listed in the adjust foreign attributes algorithm's table.

If the XML API restricts comments from having two consecutive U+002D HYPHEN-MINUS characters (--), the tool may insert a single U+0020 SPACE character between any such offending characters.

If the XML API restricts comments from ending in a U+002D HYPHEN-MINUS character (-), the tool may insert a single U+0020 SPACE character at the end of such comments.

If the XML API restricts allowed characters in character data, attribute values, or comments, the tool may replace any U+000C FORM FEED (FF) character with a U+0020 SPACE character, and any other literal non-XML character with a U+FFFD REPLACEMENT CHARACTER.

If the tool has no way to convey out-of-band information, then the tool may drop the following information:

The mutations allowed by this section apply after the HTML parser's rules have been applied. For example, a <a::> start tag will be closed by a </a::> end tag, and never by a </aU00003AU00003A> end tag, even if the user agent is using the rules above to then generate an actual element in the DOM with the name aU00003AU00003A for that start tag.

13.2.10 An introduction to error handling and strange cases in the parser

This section is non-normative.

This section examines some erroneous markup and discusses how the HTML parser handles these cases.

13.2.10.1 Misnested tags: <b><i></b></i>

This section is non-normative.

The most-often discussed example of erroneous markup is as follows:

<p>1<b>2<i>3</b>4</i>5</p>

The parsing of this markup is straightforward up to the "3". At this point, the DOM looks like this:

Here, the stack of open elements has five elements on it: html, body, p, b, and i. The list of active formatting elements just has two: b and i. The insertion mode is "in body".

Upon receiving the end tag token with the tag name "b", the "adoption agency algorithm" is invoked. This is a simple case, in that the formattingElement is the b element, and there is no furthest block. Thus, the stack of open elements ends up with just three elements: html, body, and p, while the list of active formatting elements has just one: i. The DOM tree is unmodified at this point.

The next token is a character ("4"), triggers the reconstruction of the active formatting elements, in this case just the i element. A new i element is thus created for the "4" Text node. After the end tag token for the "i" is also received, and the "5" Text node is inserted, the DOM looks as follows:

13.2.10.2 Misnested tags: <b><p></b></p>

This section is non-normative.

A case similar to the previous one is the following:

<b>1<p>2</b>3</p>

Up to the "2" the parsing here is straightforward:

The interesting part is when the end tag token with the tag name "b" is parsed.

Before that token is seen, the stack of open elements has four elements on it: html, body, b, and p. The list of active formatting elements just has the one: b. The insertion mode is "in body".

Upon receiving the end tag token with the tag name "b", the "adoption agency algorithm" is invoked, as in the previous example. However, in this case, there is a furthest block, namely the p element. Thus, this time the adoption agency algorithm isn't skipped over.

The common ancestor is the body element. A conceptual "bookmark" marks the position of the b in the list of active formatting elements, but since that list has only one element in it, the bookmark won't have much effect.

As the algorithm progresses, node ends up set to the formatting element (b), and last node ends up set to the furthest block (p).

The last node gets appended (moved) to the common ancestor, so that the DOM looks like:

A new b element is created, and the children of the p element are moved to it:

Finally, the new b element is appended to the p element, so that the DOM looks like:

The b element is removed from the list of active formatting elements and the stack of open elements, so that when the "3" is parsed, it is appended to the p element:

13.2.10.3 Unexpected markup in tables

This section is non-normative.

Error handling in tables is, for historical reasons, especially strange. For example, consider the following markup:

<table><b><tr><td>aaa</td></tr>bbb</table>ccc

The highlighted b element start tag is not allowed directly inside a table like that, and the parser handles this case by placing the element before the table. (This is called foster parenting.) This can be seen by examining the DOM tree as it stands just after the table element's start tag has been seen:

...and then immediately after the b element start tag has been seen:

At this point, the stack of open elements has on it the elements html, body, table, and b (in that order, despite the resulting DOM tree); the list of active formatting elements just has the b element in it; and the insertion mode is "in table".

The tr start tag causes the b element to be popped off the stack and a tbody start tag to be implied; the tbody and tr elements are then handled in a rather straight-forward manner, taking the parser through the "in table body" and "in row" insertion modes, after which the DOM looks as follows:

Here, the stack of open elements has on it the elements html, body, table, tbody, and tr; the list of active formatting elements still has the b element in it; and the insertion mode is "in row".

The td element start tag token, after putting a td element on the tree, puts a marker on the list of active formatting elements (it also switches to the "in cell" insertion mode).

The marker means that when the "aaa" character tokens are seen, no b element is created to hold the resulting Text node:

The end tags are handled in a straight-forward manner; after handling them, the stack of open elements has on it the elements html, body, table, and tbody; the list of active formatting elements still has the b element in it (the marker having been removed by the "td" end tag token); and the insertion mode is "in table body".

Thus it is that the "bbb" character tokens are found. These trigger the "in table text" insertion mode to be used (with the original insertion mode set to "in table body"). The character tokens are collected, and when the next token (the table element end tag) is seen, they are processed as a group. Since they are not all spaces, they are handled as per the "anything else" rules in the "in table" insertion mode, which defer to the "in body" insertion mode but with foster parenting.

When the active formatting elements are reconstructed, a b element is created and foster parented, and then the "bbb" Text node is appended to it:

The stack of open elements has on it the elements html, body, table, tbody, and the new b (again, note that this doesn't match the resulting tree!); the list of active formatting elements has the new b element in it; and the insertion mode is still "in table body".

Had the character tokens been only ASCII whitespace instead of "bbb", then that ASCII whitespace would just be appended to the tbody element.

Finally, the table is closed by a "table" end tag. This pops all the nodes from the stack of open elements up to and including the table element, but it doesn't affect the list of active formatting elements, so the "ccc" character tokens after the table result in yet another b element being created, this time after the table:

13.2.10.4 Scripts that modify the page as it is being parsed

This section is non-normative.

Consider the following markup, which for this example we will assume is the document with URL https://example.com/inner, being rendered as the content of an iframe in another document with the URL https://example.com/outer:

<div id=a>
 <script>
  var div = document.getElementById('a');
  parent.document.body.appendChild(div);
 </script>
 <script>
  alert(document.URL);
 </script>
</div>
<script>
 alert(document.URL);
</script>

Up to the first "script" end tag, before the script is parsed, the result is relatively straightforward:

After the script is parsed, though, the div element and its child script element are gone:

They are, at this point, in the Document of the aforementioned outer browsing context. However, the stack of open elements still contains the div element.

Thus, when the second script element is parsed, it is inserted into the outer Document object.

Those parsed into different Documents than the one the parser was created for do not execute, so the first alert does not show.

Once the div element's end tag is parsed, the div element is popped off the stack, and so the next script element is in the inner Document:

This script does execute, resulting in an alert that says "https://example.com/inner".

13.2.10.5 The execution of scripts that are moving across multiple documents

This section is non-normative.

Elaborating on the example in the previous section, consider the case where the second script element is an external script (i.e. one with a src attribute). Since the element was not in the parser's Document when it was created, that external script is not even downloaded.

In a case where a script element with a src attribute is parsed normally into its parser's Document, but while the external script is being downloaded, the element is moved to another document, the script continues to download, but does not execute.

In general, moving script elements between Documents is considered a bad practice.

13.2.10.6 Unclosed formatting elements

This section is non-normative.

The following markup shows how nested formatting elements (such as b) get collected and continue to be applied even as the elements they are contained in are closed, but that excessive duplicates are thrown away.

<!DOCTYPE html>
<p><b class=x><b class=x><b><b class=x><b class=x><b>X
<p>X
<p><b><b class=x><b>X
<p></b></b></b></b></b></b>X

The resulting DOM tree is as follows:

Note how the second p element in the markup has no explicit b elements, but in the resulting DOM, up to three of each kind of formatting element (in this case three b elements with the class attribute, and two unadorned b elements) get reconstructed before the element's "X".

Also note how this means that in the final paragraph only six b end tags are needed to completely clear the list of active formatting elements, even though nine b start tags have been seen up to this point.

13.3 Serializing HTML fragments

For the purposes of the following algorithm, an element serializes as void if its element type is one of the void elements, or is basefont, bgsound, frame, keygen, or param.

The following steps form the HTML fragment serialization algorithm. The algorithm takes as input a DOM Element, Document, or DocumentFragment referred to as the node, a boolean serializableShadowRoots, and a sequence<ShadowRoot> shadowRoots, and returns a string.

This algorithm serializes the children of the node being serialized, not the node itself.

  1. If the node serializes as void, then return the empty string.

  2. Let s be a string, and initialize it to the empty string.

  3. If the node is a template element, then let the node instead be the template element's template contents (a DocumentFragment node).

  4. If current node is a shadow host, then:

    1. Let shadow be current node's shadow root.

    2. If one of the following is true:

      • serializableShadowRoots is true and shadow's serializable is true; or

      • shadowRoots contains shadow,

      then:

      1. Append "<template shadowrootmode="".

      2. If shadow's mode is "open", then append "open". Otherwise, append "closed".

      3. Append """.

      4. If shadow's delegates focus is set, then append " shadowrootdelegatesfocus=""".

      5. If shadow's serializable is set, then append " shadowrootserializable=""".

      6. If shadow's clonable is set, then append " shadowrootclonable=""".

      7. Append ">".

      8. Append the value of running the HTML fragment serialization algorithm with shadow, serializableShadowRoots, and shadowRoots (thus recursing into this algorithm for that element).

      9. Append "</template>".

  5. For each child node of the node, in tree order, run the following steps:

    1. Let current node be the child node being processed.

    2. Append the appropriate string from the following list to s:

      If current node is an Element

      If current node is an element in the HTML namespace, the MathML namespace, or the SVG namespace, then let tagname be current node's local name. Otherwise, let tagname be current node's qualified name.

      Append a U+003C LESS-THAN SIGN character (<), followed by tagname.

      For HTML elements created by the HTML parser or createElement(), tagname will be lowercase.

      If current node's is value is not null, and the element does not have an is attribute in its attribute list, then append the string " is="", followed by current node's is value escaped as described below in attribute mode, followed by a U+0022 QUOTATION MARK character (").

      For each attribute that the element has, append a U+0020 SPACE character, the attribute's serialized name as described below, a U+003D EQUALS SIGN character (=), a U+0022 QUOTATION MARK character ("), the attribute's value, escaped as described below in attribute mode, and a second U+0022 QUOTATION MARK character (").

      An attribute's serialized name for the purposes of the previous paragraph must be determined as follows:

      If the attribute has no namespace

      The attribute's serialized name is the attribute's local name.

      For attributes on HTML elements set by the HTML parser or by setAttribute(), the local name will be lowercase.

      If the attribute is in the XML namespace

      The attribute's serialized name is the string "xml:" followed by the attribute's local name.

      If the attribute is in the XMLNS namespace and the attribute's local name is xmlns

      The attribute's serialized name is the string "xmlns".

      If the attribute is in the XMLNS namespace and the attribute's local name is not xmlns

      The attribute's serialized name is the string "xmlns:" followed by the attribute's local name.

      If the attribute is in the XLink namespace

      The attribute's serialized name is the string "xlink:" followed by the attribute's local name.

      If the attribute is in some other namespace

      The attribute's serialized name is the attribute's qualified name.

      While the exact order of attributes is implementation-defined, and may depend on factors such as the order that the attributes were given in the original markup, the sort order must be stable, such that consecutive invocations of this algorithm serialize an element's attributes in the same order.

      Append a U+003E GREATER-THAN SIGN character (>).

      If current node serializes as void, then continue on to the next child node at this point.

      Append the value of running the HTML fragment serialization algorithm with current node, serializableShadowRoots, and shadowRoots (thus recursing into this algorithm for that node), followed by a U+003C LESS-THAN SIGN character (<), a U+002F SOLIDUS character (/), tagname again, and finally a U+003E GREATER-THAN SIGN character (>).

      If current node is a Text node

      If the parent of current node is a style, script, xmp, iframe, noembed, noframes, or plaintext element, or if the parent of current node is a noscript element and scripting is enabled for the node, then append the value of current node's data literally.

      Otherwise, append the value of current node's data, escaped as described below.

      If current node is a Comment

      Append "<!--" (U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS), followed by the value of current node's data, followed by the literal string "-->" (U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN).

      If current node is a ProcessingInstruction

      Append "<?" (U+003C LESS-THAN SIGN, U+003F QUESTION MARK), followed by the value of current node's target IDL attribute, followed by a single U+0020 SPACE character, followed by the value of current node's data, followed by a single U+003E GREATER-THAN SIGN character (>).

      If current node is a DocumentType

      Append "<!DOCTYPE" (U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+0044 LATIN CAPITAL LETTER D, U+004F LATIN CAPITAL LETTER O, U+0043 LATIN CAPITAL LETTER C, U+0054 LATIN CAPITAL LETTER T, U+0059 LATIN CAPITAL LETTER Y, U+0050 LATIN CAPITAL LETTER P, U+0045 LATIN CAPITAL LETTER E), followed by a space (U+0020 SPACE), followed by the value of current node's name, followed by ">" (U+003E GREATER-THAN SIGN).

  6. Return s.

It is possible that the output of this algorithm, if parsed with an HTML parser, will not return the original tree structure. Tree structures that do not roundtrip a serialize and reparse step can also be produced by the HTML parser itself, although such cases are typically non-conforming.

For instance, if a textarea element to which a Comment node has been appended is serialized and the output is then reparsed, the comment will end up being displayed in the text control. Similarly, if, as a result of DOM manipulation, an element contains a comment that contains "-->", then when the result of serializing the element is parsed, the comment will be truncated at that point and the rest of the comment will be interpreted as markup. More examples would be making a script element contain a Text node with the text string "</script>", or having a p element that contains a ul element (as the ul element's start tag would imply the end tag for the p).

This can enable cross-site scripting attacks. An example of this would be a page that lets the user enter some font family names that are then inserted into a CSS style block via the DOM and which then uses the innerHTML IDL attribute to get the HTML serialization of that style element: if the user enters "</style><script>attack</script>" as a font family name, innerHTML will return markup that, if parsed in a different context, would contain a script node, even though no script node existed in the original DOM.

For example, consider the following markup:

<form id="outer"><div></form><form id="inner"><input>

This will be parsed into:

The input element will be associated with the inner form element. Now, if this tree structure is serialized and reparsed, the <form id="inner"> start tag will be ignored, and so the input element will be associated with the outer form element instead.

<html><head></head><body><form id="outer"><div><form id="inner"><input></form></div></form></body></html>

As another example, consider the following markup:

<a><table><a>

This will be parsed into:

That is, the a elements are nested, because the second a element is foster parented. After a serialize-reparse roundtrip, the a elements and the table element would all be siblings, because the second <a> start tag implicitly closes the first a element.

<html><head></head><body><a><a></a><table></table></a></body></html>

For historical reasons, this algorithm does not round-trip an initial U+000A LINE FEED (LF) character in pre, textarea, or listing elements, even though (in the first two cases) the markup being round-tripped can be conforming. The HTML parser will drop such a character during parsing, but this algorithm does not serialize an extra U+000A LINE FEED (LF) character.

For example, consider the following markup:

<pre>

Hello.</pre>

When this document is first parsed, the pre element's child text content starts with a single newline character. After a serialize-reparse roundtrip, the pre element's child text content is simply "Hello.".

Because of the special role of the is attribute in signaling the creation of customized built-in elements, in that it provides a mechanism for parsed HTML to set the element's is value, we special-case its handling during serialization. This ensures that an element's is value is preserved through serialize-parse roundtrips.

When creating a customized built-in element via the parser, a developer uses the is attribute directly; in such cases serialize-parse roundtrips work fine.

<script>
window.SuperP = class extends HTMLParagraphElement {};
customElements.define("super-p", SuperP, { extends: "p" });
</script>

<div id="container"><p is="super-p">Superb!</p></div>

<script>
console.log(container.innerHTML); // <p is="super-p">
container.innerHTML = container.innerHTML;
console.log(container.innerHTML); // <p is="super-p">
console.assert(container.firstChild instanceof SuperP);
</script>

But when creating a customized built-in element via its constructor or via createElement(), the is attribute is not added. Instead, the is value (which is what the custom elements machinery uses) is set without intermediating through an attribute.

<script>
container.innerHTML = "";
const p = document.createElement("p", { is: "super-p" });
container.appendChild(p);

// The is attribute is not present in the DOM:
console.assert(!p.hasAttribute("is"));

// But the element is still a super-p:
console.assert(p instanceof SuperP);
</script>

To ensure that serialize-parse roundtrips still work, the serialization process explicitly writes out the element's is value as an is attribute:

<script>
console.log(container.innerHTML); // <p is="super-p">
container.innerHTML = container.innerHTML;
console.log(container.innerHTML); // <p is="super-p">
console.assert(container.firstChild instanceof SuperP);
</script>

Escaping a string (for the purposes of the algorithm above) consists of running the following steps:

  1. Replace any occurrence of the "&" character by the string "&amp;".

  2. Replace any occurrences of the U+00A0 NO-BREAK SPACE character by the string "&nbsp;".

  3. If the algorithm was invoked in the attribute mode, replace any occurrences of the """ character by the string "&quot;".

  4. If the algorithm was not invoked in the attribute mode, replace any occurrences of the "<" character by the string "&lt;", and any occurrences of the ">" character by the string "&gt;".

13.4 Parsing HTML fragments

The following steps form the HTML fragment parsing algorithm. The algorithm takes as input an Element node, referred to as the context element, which gives the context for the parser, input, a string to parse, and an optional boolean allowDeclarativeShadowRoots (default false). It returns a list of zero or more nodes.

Parts marked fragment case in algorithms in the parser section are parts that only occur if the parser was created for the purposes of this algorithm. The algorithms have been annotated with such markings for informational purposes only; such markings have no normative weight. If it is possible for a condition described as a fragment case to occur even when the parser wasn't created for the purposes of handling this algorithm, then that is an error in the specification.

  1. Create a new Document node, and mark it as being an HTML document.

  2. If the node document of the context element is in quirks mode, then let the Document be in quirks mode. Otherwise, if the node document of the context element is in limited-quirks mode, then let the Document be in limited-quirks mode. Otherwise, leave the Document in no-quirks mode.

  3. If allowDeclarativeShadowRoots is true, then set the Document's allow declarative shadow roots to true.

  4. Create a new HTML parser, and associate it with the just created Document node.

  5. Set the state of the HTML parser's tokenization stage as follows, switching on the context element:

    title
    textarea
    Switch the tokenizer to the RCDATA state.
    style
    xmp
    iframe
    noembed
    noframes
    Switch the tokenizer to the RAWTEXT state.
    script
    Switch the tokenizer to the script data state.
    noscript
    If the scripting flag is enabled, switch the tokenizer to the RAWTEXT state. Otherwise, leave the tokenizer in the data state.
    plaintext
    Switch the tokenizer to the PLAINTEXT state.
    Any other element
    Leave the tokenizer in the data state.

    For performance reasons, an implementation that does not report errors and that uses the actual state machine described in this specification directly could use the PLAINTEXT state instead of the RAWTEXT and script data states where those are mentioned in the list above. Except for rules regarding parse errors, they are equivalent, since there is no appropriate end tag token in the fragment case, yet they involve far fewer state transitions.

  6. Let root be a new html element with no attributes.

  7. Append the element root to the Document node created above.

  8. Set up the parser's stack of open elements so that it contains just the single element root.

  9. If the context element is a template element, push "in template" onto the stack of template insertion modes so that it is the new current template insertion mode.

  10. Create a start tag token whose name is the local name of context and whose attributes are the attributes of context.

    Let this start tag token be the start tag token of the context node, e.g. for the purposes of determining if it is an HTML integration point.

  11. Reset the parser's insertion mode appropriately.

    The parser will reference the context element as part of that algorithm.

  12. Set the parser's form element pointer to the nearest node to the context element that is a form element (going straight up the ancestor chain, and including the element itself, if it is a form element), if any. (If there is no such form element, the form element pointer keeps its initial value, null.)

  13. Place the input into the input stream for the HTML parser just created. The encoding confidence is irrelevant.

  14. Start the parser and let it run until it has consumed all the characters just inserted into the input stream.

  15. Return the child nodes of root, in tree order.

13.5 Named character references

This table lists the character reference names that are supported by HTML, and the code points to which they refer. It is referenced by the previous sections.

It is intentional, for legacy compatibility, that many code points have multiple character reference names. For example, some appear both with and without the trailing semicolon, or with different capitalizations.

Name Character(s) Glyph
Aacute; U+000C1 Á
Aacute U+000C1 Á
aacute; U+000E1 á
aacute U+000E1 á
Abreve; U+00102 Ă
abreve; U+00103 ă
ac; U+0223E
acd; U+0223F
acE; U+0223E U+00333 ∾̳
Acirc; U+000C2 Â
Acirc U+000C2 Â
acirc; U+000E2 â
acirc U+000E2 â
acute; U+000B4 ´
acute U+000B4 ´
Acy; U+00410 А
acy; U+00430 а
AElig; U+000C6 Æ
AElig U+000C6 Æ
aelig; U+000E6 æ
aelig U+000E6 æ
af; U+02061
Afr; U+1D504 𝔄
afr; U+1D51E 𝔞
Agrave; U+000C0 À
Agrave U+000C0 À
agrave; U+000E0 à
agrave U+000E0 à
alefsym; U+02135
aleph; U+02135
Alpha; U+00391 Α
alpha; U+003B1 α
Amacr; U+00100 Ā
amacr; U+00101 ā
amalg; U+02A3F ⨿
AMP; U+00026 &
AMP U+00026 &
amp; U+00026 &
amp U+00026 &
And; U+02A53
and; U+02227
andand; U+02A55
andd; U+02A5C
andslope; U+02A58
andv; U+02A5A
ang; U+02220
ange; U+029A4
angle; U+02220
angmsd; U+02221
angmsdaa; U+029A8
angmsdab; U+029A9
angmsdac; U+029AA
angmsdad; U+029AB
angmsdae; U+029AC
angmsdaf; U+029AD
angmsdag; U+029AE
angmsdah; U+029AF
angrt; U+0221F
angrtvb; U+022BE
angrtvbd; U+0299D
angsph; U+02222
angst; U+000C5 Å
angzarr; U+0237C
Aogon; U+00104 Ą
aogon; U+00105 ą
Aopf; U+1D538 𝔸
aopf; U+1D552 𝕒
ap; U+02248
apacir; U+02A6F
apE; U+02A70
ape; U+0224A
apid; U+0224B
apos; U+00027 '
ApplyFunction; U+02061
approx; U+02248
approxeq; U+0224A
Aring; U+000C5 Å
Aring U+000C5 Å
aring; U+000E5 å
aring U+000E5 å
Ascr; U+1D49C 𝒜
ascr; U+1D4B6 𝒶
Assign; U+02254
ast; U+0002A *
asymp; U+02248
asympeq; U+0224D
Atilde; U+000C3 Ã
Atilde U+000C3 Ã
atilde; U+000E3 ã
atilde U+000E3 ã
Auml; U+000C4 Ä
Auml U+000C4 Ä
auml; U+000E4 ä
auml U+000E4 ä
awconint; U+02233
awint; U+02A11
backcong; U+0224C
backepsilon; U+003F6 ϶
backprime; U+02035
backsim; U+0223D
backsimeq; U+022CD
Backslash; U+02216
Barv; U+02AE7
barvee; U+022BD
Barwed; U+02306
barwed; U+02305
barwedge; U+02305
bbrk; U+023B5
bbrktbrk; U+023B6
bcong; U+0224C
Bcy; U+00411 Б
bcy; U+00431 б
bdquo; U+0201E
becaus; U+02235
Because; U+02235
because; U+02235
bemptyv; U+029B0
bepsi; U+003F6 ϶
bernou; U+0212C
Bernoullis; U+0212C
Beta; U+00392 Β
beta; U+003B2 β
beth; U+02136
between; U+0226C
Bfr; U+1D505 𝔅
bfr; U+1D51F 𝔟
bigcap; U+022C2
bigcirc; U+025EF
bigcup; U+022C3
bigodot; U+02A00
bigoplus; U+02A01
bigotimes; U+02A02
bigsqcup; U+02A06
bigstar; U+02605
bigtriangledown; U+025BD
bigtriangleup; U+025B3
biguplus; U+02A04
bigvee; U+022C1
bigwedge; U+022C0
bkarow; U+0290D
blacklozenge; U+029EB
blacksquare; U+025AA
blacktriangle; U+025B4
blacktriangledown; U+025BE
blacktriangleleft; U+025C2
blacktriangleright; U+025B8
blank; U+02423
blk12; U+02592
blk14; U+02591
blk34; U+02593
block; U+02588
bne; U+0003D U+020E5 =⃥
bnequiv; U+02261 U+020E5 ≡⃥
bNot; U+02AED
bnot; U+02310
Bopf; U+1D539 𝔹
bopf; U+1D553 𝕓
bot; U+022A5
bottom; U+022A5
bowtie; U+022C8
boxbox; U+029C9
boxDL; U+02557
boxDl; U+02556
boxdL; U+02555
boxdl; U+02510
boxDR; U+02554
boxDr; U+02553
boxdR; U+02552
boxdr; U+0250C
boxH; U+02550
boxh; U+02500
boxHD; U+02566
boxHd; U+02564
boxhD; U+02565
boxhd; U+0252C
boxHU; U+02569
boxHu; U+02567
boxhU; U+02568
boxhu; U+02534
boxminus; U+0229F
boxplus; U+0229E
boxtimes; U+022A0
boxUL; U+0255D
boxUl; U+0255C
boxuL; U+0255B
boxul; U+02518
boxUR; U+0255A
boxUr; U+02559
boxuR; U+02558
boxur; U+02514
boxV; U+02551
boxv; U+02502
boxVH; U+0256C
boxVh; U+0256B
boxvH; U+0256A
boxvh; U+0253C
boxVL; U+02563
boxVl; U+02562
boxvL; U+02561
boxvl; U+02524
boxVR; U+02560
boxVr; U+0255F
boxvR; U+0255E
boxvr; U+0251C
bprime; U+02035
Breve; U+002D8 ˘
breve; U+002D8 ˘
brvbar; U+000A6 ¦
brvbar U+000A6 ¦
Bscr; U+0212C
bscr; U+1D4B7 𝒷
bsemi; U+0204F
bsim; U+0223D
bsime; U+022CD
bsol; U+0005C \
bsolb; U+029C5
bsolhsub; U+027C8
bull; U+02022
bullet; U+02022
bump; U+0224E
bumpE; U+02AAE
bumpe; U+0224F
Bumpeq; U+0224E
bumpeq; U+0224F
Cacute; U+00106 Ć
cacute; U+00107 ć
Cap; U+022D2
cap; U+02229
capand; U+02A44
capbrcup; U+02A49
capcap; U+02A4B
capcup; U+02A47
capdot; U+02A40
CapitalDifferentialD; U+02145
caps; U+02229 U+0FE00 ∩︀
caret; U+02041
caron; U+002C7 ˇ
Cayleys; U+0212D
ccaps; U+02A4D
Ccaron; U+0010C Č
ccaron; U+0010D č
Ccedil; U+000C7 Ç
Ccedil U+000C7 Ç
ccedil; U+000E7 ç
ccedil U+000E7 ç
Ccirc; U+00108 Ĉ
ccirc; U+00109 ĉ
Cconint; U+02230
ccups; U+02A4C
ccupssm; U+02A50
Cdot; U+0010A Ċ
cdot; U+0010B ċ
cedil; U+000B8 ¸
cedil U+000B8 ¸
Cedilla; U+000B8 ¸
cemptyv; U+029B2
cent; U+000A2 ¢
cent U+000A2 ¢
CenterDot; U+000B7 ·
centerdot; U+000B7 ·
Cfr; U+0212D
cfr; U+1D520 𝔠
CHcy; U+00427 Ч
chcy; U+00447 ч
check; U+02713
checkmark; U+02713
Chi; U+003A7 Χ
chi; U+003C7 χ
cir; U+025CB
circ; U+002C6 ˆ
circeq; U+02257
circlearrowleft; U+021BA
circlearrowright; U+021BB
circledast; U+0229B
circledcirc; U+0229A
circleddash; U+0229D
CircleDot; U+02299
circledR; U+000AE ®
circledS; U+024C8
CircleMinus; U+02296
CirclePlus; U+02295
CircleTimes; U+02297
cirE; U+029C3
cire; U+02257
cirfnint; U+02A10
cirmid; U+02AEF
cirscir; U+029C2
ClockwiseContourIntegral; U+02232
CloseCurlyDoubleQuote; U+0201D
CloseCurlyQuote; U+02019
clubs; U+02663
clubsuit; U+02663
Colon; U+02237
colon; U+0003A :
Colone; U+02A74
colone; U+02254
coloneq; U+02254
comma; U+0002C ,
commat; U+00040 @
comp; U+02201
compfn; U+02218
complement; U+02201
complexes; U+02102
cong; U+02245
congdot; U+02A6D
Congruent; U+02261
Conint; U+0222F
conint; U+0222E
ContourIntegral; U+0222E
Copf; U+02102
copf; U+1D554 𝕔
coprod; U+02210
Coproduct; U+02210
COPY; U+000A9 ©
COPY U+000A9 ©
copy; U+000A9 ©
copy U+000A9 ©
copysr; U+02117
CounterClockwiseContourIntegral; U+02233
crarr; U+021B5
Cross; U+02A2F
cross; U+02717
Cscr; U+1D49E 𝒞
cscr; U+1D4B8 𝒸
csub; U+02ACF
csube; U+02AD1
csup; U+02AD0
csupe; U+02AD2
ctdot; U+022EF
cudarrl; U+02938
cudarrr; U+02935
cuepr; U+022DE
cuesc; U+022DF
cularr; U+021B6
cularrp; U+0293D
Cup; U+022D3
cup; U+0222A
cupbrcap; U+02A48
CupCap; U+0224D
cupcap; U+02A46
cupcup; U+02A4A
cupdot; U+0228D
cupor; U+02A45
cups; U+0222A U+0FE00 ∪︀
curarr; U+021B7
curarrm; U+0293C
curlyeqprec; U+022DE
curlyeqsucc; U+022DF
curlyvee; U+022CE
curlywedge; U+022CF
curren; U+000A4 ¤
curren U+000A4 ¤
curvearrowleft; U+021B6
curvearrowright; U+021B7
cuvee; U+022CE
cuwed; U+022CF
cwconint; U+02232
cwint; U+02231
cylcty; U+0232D
Dagger; U+02021
dagger; U+02020
daleth; U+02138
Darr; U+021A1
dArr; U+021D3
darr; U+02193
dash; U+02010
Dashv; U+02AE4
dashv; U+022A3
dbkarow; U+0290F
dblac; U+002DD ˝
Dcaron; U+0010E Ď
dcaron; U+0010F ď
Dcy; U+00414 Д
dcy; U+00434 д
DD; U+02145
dd; U+02146
ddagger; U+02021
ddarr; U+021CA
DDotrahd; U+02911
ddotseq; U+02A77
deg; U+000B0 °
deg U+000B0 °
Del; U+02207
Delta; U+00394 Δ
delta; U+003B4 δ
demptyv; U+029B1
dfisht; U+0297F ⥿
Dfr; U+1D507 𝔇
dfr; U+1D521 𝔡
dHar; U+02965
dharl; U+021C3
dharr; U+021C2
DiacriticalAcute; U+000B4 ´
DiacriticalDot; U+002D9 ˙
DiacriticalDoubleAcute; U+002DD ˝
DiacriticalGrave; U+00060 `
DiacriticalTilde; U+002DC ˜
diam; U+022C4
Diamond; U+022C4
diamond; U+022C4
diamondsuit; U+02666
diams; U+02666
die; U+000A8 ¨
DifferentialD; U+02146
digamma; U+003DD ϝ
disin; U+022F2
div; U+000F7 ÷
divide; U+000F7 ÷
divide U+000F7 ÷
divideontimes; U+022C7
divonx; U+022C7
DJcy; U+00402 Ђ
djcy; U+00452 ђ
dlcorn; U+0231E
dlcrop; U+0230D
dollar; U+00024 $
Dopf; U+1D53B 𝔻
dopf; U+1D555 𝕕
Dot; U+000A8 ¨
dot; U+002D9 ˙
DotDot; U+020DC ◌⃜
doteq; U+02250
doteqdot; U+02251
DotEqual; U+02250
dotminus; U+02238
dotplus; U+02214
dotsquare; U+022A1
doublebarwedge; U+02306
DoubleContourIntegral; U+0222F
DoubleDot; U+000A8 ¨
DoubleDownArrow; U+021D3
DoubleLeftArrow; U+021D0
DoubleLeftRightArrow; U+021D4
DoubleLeftTee; U+02AE4
DoubleLongLeftArrow; U+027F8
DoubleLongLeftRightArrow; U+027FA
DoubleLongRightArrow; U+027F9
DoubleRightArrow; U+021D2
DoubleRightTee; U+022A8
DoubleUpArrow; U+021D1
DoubleUpDownArrow; U+021D5
DoubleVerticalBar; U+02225
DownArrow; U+02193
Downarrow; U+021D3
downarrow; U+02193
DownArrowBar; U+02913
DownArrowUpArrow; U+021F5
DownBreve; U+00311 ◌̑
downdownarrows; U+021CA
downharpoonleft; U+021C3
downharpoonright; U+021C2
DownLeftRightVector; U+02950
DownLeftTeeVector; U+0295E
DownLeftVector; U+021BD
DownLeftVectorBar; U+02956
DownRightTeeVector; U+0295F
DownRightVector; U+021C1
DownRightVectorBar; U+02957
DownTee; U+022A4
DownTeeArrow; U+021A7
drbkarow; U+02910
drcorn; U+0231F
drcrop; U+0230C
Dscr; U+1D49F 𝒟
dscr; U+1D4B9 𝒹
DScy; U+00405 Ѕ
dscy; U+00455 ѕ
dsol; U+029F6
Dstrok; U+00110 Đ
dstrok; U+00111 đ
dtdot; U+022F1
dtri; U+025BF
dtrif; U+025BE
duarr; U+021F5
duhar; U+0296F
dwangle; U+029A6
DZcy; U+0040F Џ
dzcy; U+0045F џ
dzigrarr; U+027FF
Eacute; U+000C9 É
Eacute U+000C9 É
eacute; U+000E9 é
eacute U+000E9 é
easter; U+02A6E
Ecaron; U+0011A Ě
ecaron; U+0011B ě
ecir; U+02256
Ecirc; U+000CA Ê
Ecirc U+000CA Ê
ecirc; U+000EA ê
ecirc U+000EA ê
ecolon; U+02255
Ecy; U+0042D Э
ecy; U+0044D э
eDDot; U+02A77
Edot; U+00116 Ė
eDot; U+02251
edot; U+00117 ė
ee; U+02147
efDot; U+02252
Efr; U+1D508 𝔈
efr; U+1D522 𝔢
eg; U+02A9A
Egrave; U+000C8 È
Egrave U+000C8 È
egrave; U+000E8 è
egrave U+000E8 è
egs; U+02A96
egsdot; U+02A98
el; U+02A99
Element; U+02208
elinters; U+023E7
ell; U+02113
els; U+02A95
elsdot; U+02A97
Emacr; U+00112 Ē
emacr; U+00113 ē
empty; U+02205
emptyset; U+02205
EmptySmallSquare; U+025FB
emptyv; U+02205
EmptyVerySmallSquare; U+025AB
emsp; U+02003
emsp13; U+02004
emsp14; U+02005
ENG; U+0014A Ŋ
eng; U+0014B ŋ
ensp; U+02002
Eogon; U+00118 Ę
eogon; U+00119 ę
Eopf; U+1D53C 𝔼
eopf; U+1D556 𝕖
epar; U+022D5
eparsl; U+029E3
eplus; U+02A71
epsi; U+003B5 ε
Epsilon; U+00395 Ε
epsilon; U+003B5 ε
epsiv; U+003F5 ϵ
eqcirc; U+02256
eqcolon; U+02255
eqsim; U+02242
eqslantgtr; U+02A96
eqslantless; U+02A95
Equal; U+02A75
equals; U+0003D =
EqualTilde; U+02242
equest; U+0225F
Equilibrium; U+021CC
equiv; U+02261
equivDD; U+02A78
eqvparsl; U+029E5
erarr; U+02971
erDot; U+02253
Escr; U+02130
escr; U+0212F
esdot; U+02250
Esim; U+02A73
esim; U+02242
Eta; U+00397 Η
eta; U+003B7 η
ETH; U+000D0 Ð
ETH U+000D0 Ð
eth; U+000F0 ð
eth U+000F0 ð
Euml; U+000CB Ë
Euml U+000CB Ë
euml; U+000EB ë
euml U+000EB ë
euro; U+020AC
excl; U+00021 !
exist; U+02203
Exists; U+02203
expectation; U+02130
ExponentialE; U+02147
exponentiale; U+02147
fallingdotseq; U+02252
Fcy; U+00424 Ф
fcy; U+00444 ф
female; U+02640
ffilig; U+0FB03
fflig; U+0FB00
ffllig; U+0FB04
Ffr; U+1D509 𝔉
ffr; U+1D523 𝔣
filig; U+0FB01
FilledSmallSquare; U+025FC
FilledVerySmallSquare; U+025AA
fjlig; U+00066 U+0006A fj
flat; U+0266D
fllig; U+0FB02
fltns; U+025B1
fnof; U+00192 ƒ
Fopf; U+1D53D 𝔽
fopf; U+1D557 𝕗
ForAll; U+02200
forall; U+02200
fork; U+022D4
forkv; U+02AD9
Fouriertrf; U+02131
fpartint; U+02A0D
frac12; U+000BD ½
frac12 U+000BD ½
frac13; U+02153
frac14; U+000BC ¼
frac14 U+000BC ¼
frac15; U+02155
frac16; U+02159
frac18; U+0215B
frac23; U+02154
frac25; U+02156
frac34; U+000BE ¾
frac34 U+000BE ¾
frac35; U+02157
frac38; U+0215C
frac45; U+02158
frac56; U+0215A
frac58; U+0215D
frac78; U+0215E
frasl; U+02044
frown; U+02322
Fscr; U+02131
fscr; U+1D4BB 𝒻
gacute; U+001F5 ǵ
Gamma; U+00393 Γ
gamma; U+003B3 γ
Gammad; U+003DC Ϝ
gammad; U+003DD ϝ
gap; U+02A86
Gbreve; U+0011E Ğ
gbreve; U+0011F ğ
Gcedil; U+00122 Ģ
Gcirc; U+0011C Ĝ
gcirc; U+0011D ĝ
Gcy; U+00413 Г
gcy; U+00433 г
Gdot; U+00120 Ġ
gdot; U+00121 ġ
gE; U+02267
ge; U+02265
gEl; U+02A8C
gel; U+022DB
geq; U+02265
geqq; U+02267
geqslant; U+02A7E
ges; U+02A7E
gescc; U+02AA9
gesdot; U+02A80
gesdoto; U+02A82
gesdotol; U+02A84
gesl; U+022DB U+0FE00 ⋛︀
gesles; U+02A94
Gfr; U+1D50A 𝔊
gfr; U+1D524 𝔤
Gg; U+022D9
gg; U+0226B
ggg; U+022D9
gimel; U+02137
GJcy; U+00403 Ѓ
gjcy; U+00453 ѓ
gl; U+02277
gla; U+02AA5
glE; U+02A92
glj; U+02AA4
gnap; U+02A8A
gnapprox; U+02A8A
gnE; U+02269
gne; U+02A88
gneq; U+02A88
gneqq; U+02269
gnsim; U+022E7
Gopf; U+1D53E 𝔾
gopf; U+1D558 𝕘
grave; U+00060 `
GreaterEqual; U+02265
GreaterEqualLess; U+022DB
GreaterFullEqual; U+02267
GreaterGreater; U+02AA2
GreaterLess; U+02277
GreaterSlantEqual; U+02A7E
GreaterTilde; U+02273
Gscr; U+1D4A2 𝒢
gscr; U+0210A
gsim; U+02273
gsime; U+02A8E
gsiml; U+02A90
GT; U+0003E >
GT U+0003E >
Gt; U+0226B
gt; U+0003E >
gt U+0003E >
gtcc; U+02AA7
gtcir; U+02A7A
gtdot; U+022D7
gtlPar; U+02995
gtquest; U+02A7C
gtrapprox; U+02A86
gtrarr; U+02978
gtrdot; U+022D7
gtreqless; U+022DB
gtreqqless; U+02A8C
gtrless; U+02277
gtrsim; U+02273
gvertneqq; U+02269 U+0FE00 ≩︀
gvnE; U+02269 U+0FE00 ≩︀
Hacek; U+002C7 ˇ
hairsp; U+0200A
half; U+000BD ½
hamilt; U+0210B
HARDcy; U+0042A Ъ
hardcy; U+0044A ъ
hArr; U+021D4
harr; U+02194
harrcir; U+02948
harrw; U+021AD
Hat; U+0005E ^
hbar; U+0210F
Hcirc; U+00124 Ĥ
hcirc; U+00125 ĥ
hearts; U+02665
heartsuit; U+02665
hellip; U+02026
hercon; U+022B9
Hfr; U+0210C
hfr; U+1D525 𝔥
HilbertSpace; U+0210B
hksearow; U+02925
hkswarow; U+02926
hoarr; U+021FF
homtht; U+0223B
hookleftarrow; U+021A9
hookrightarrow; U+021AA
Hopf; U+0210D
hopf; U+1D559 𝕙
horbar; U+02015
HorizontalLine; U+02500
Hscr; U+0210B
hscr; U+1D4BD 𝒽
hslash; U+0210F
Hstrok; U+00126 Ħ
hstrok; U+00127 ħ
HumpDownHump; U+0224E
HumpEqual; U+0224F
hybull; U+02043
hyphen; U+02010
Iacute; U+000CD Í
Iacute U+000CD Í
iacute; U+000ED í
iacute U+000ED í
ic; U+02063
Icirc; U+000CE Î
Icirc U+000CE Î
icirc; U+000EE î
icirc U+000EE î
Icy; U+00418 И
icy; U+00438 и
Idot; U+00130 İ
IEcy; U+00415 Е
iecy; U+00435 е
iexcl; U+000A1 ¡
iexcl U+000A1 ¡
iff; U+021D4
Ifr; U+02111
ifr; U+1D526 𝔦
Igrave; U+000CC Ì
Igrave U+000CC Ì
igrave; U+000EC ì
igrave U+000EC ì
ii; U+02148
iiiint; U+02A0C
iiint; U+0222D
iinfin; U+029DC
iiota; U+02129
IJlig; U+00132 IJ
ijlig; U+00133 ij
Im; U+02111
Imacr; U+0012A Ī
imacr; U+0012B ī
image; U+02111
ImaginaryI; U+02148
imagline; U+02110
imagpart; U+02111
imath; U+00131 ı
imof; U+022B7
imped; U+001B5 Ƶ
Implies; U+021D2
in; U+02208
incare; U+02105
infin; U+0221E
infintie; U+029DD
inodot; U+00131 ı
Int; U+0222C
int; U+0222B
intcal; U+022BA
integers; U+02124
Integral; U+0222B
intercal; U+022BA
Intersection; U+022C2
intlarhk; U+02A17
intprod; U+02A3C
InvisibleComma; U+02063
InvisibleTimes; U+02062
IOcy; U+00401 Ё
iocy; U+00451 ё
Iogon; U+0012E Į
iogon; U+0012F į
Iopf; U+1D540 𝕀
iopf; U+1D55A 𝕚
Iota; U+00399 Ι
iota; U+003B9 ι
iprod; U+02A3C
iquest; U+000BF ¿
iquest U+000BF ¿
Iscr; U+02110
iscr; U+1D4BE 𝒾
isin; U+02208
isindot; U+022F5
isinE; U+022F9
isins; U+022F4
isinsv; U+022F3
isinv; U+02208
it; U+02062
Itilde; U+00128 Ĩ
itilde; U+00129 ĩ
Iukcy; U+00406 І
iukcy; U+00456 і
Iuml; U+000CF Ï
Iuml U+000CF Ï
iuml; U+000EF ï
iuml U+000EF ï
Jcirc; U+00134 Ĵ
jcirc; U+00135 ĵ
Jcy; U+00419 Й
jcy; U+00439 й
Jfr; U+1D50D 𝔍
jfr; U+1D527 𝔧
jmath; U+00237 ȷ
Jopf; U+1D541 𝕁
jopf; U+1D55B 𝕛
Jscr; U+1D4A5 𝒥
jscr; U+1D4BF 𝒿
Jsercy; U+00408 Ј
jsercy; U+00458 ј
Jukcy; U+00404 Є
jukcy; U+00454 є
Kappa; U+0039A Κ
kappa; U+003BA κ
kappav; U+003F0 ϰ
Kcedil; U+00136 Ķ
kcedil; U+00137 ķ
Kcy; U+0041A К
kcy; U+0043A к
Kfr; U+1D50E 𝔎
kfr; U+1D528 𝔨
kgreen; U+00138 ĸ
KHcy; U+00425 Х
khcy; U+00445 х
KJcy; U+0040C Ќ
kjcy; U+0045C ќ
Kopf; U+1D542 𝕂
kopf; U+1D55C 𝕜
Kscr; U+1D4A6 𝒦
kscr; U+1D4C0 𝓀
lAarr; U+021DA
Lacute; U+00139 Ĺ
lacute; U+0013A ĺ
laemptyv; U+029B4
lagran; U+02112
Lambda; U+0039B Λ
lambda; U+003BB λ
Lang; U+027EA
lang; U+027E8
langd; U+02991
langle; U+027E8
lap; U+02A85
Laplacetrf; U+02112
laquo; U+000AB «
laquo U+000AB «
Larr; U+0219E
lArr; U+021D0
larr; U+02190
larrb; U+021E4
larrbfs; U+0291F
larrfs; U+0291D
larrhk; U+021A9
larrlp; U+021AB
larrpl; U+02939
larrsim; U+02973
larrtl; U+021A2
lat; U+02AAB
lAtail; U+0291B
latail; U+02919
late; U+02AAD
lates; U+02AAD U+0FE00 ⪭︀
lBarr; U+0290E
lbarr; U+0290C
lbbrk; U+02772
lbrace; U+0007B {
lbrack; U+0005B [
lbrke; U+0298B
lbrksld; U+0298F
lbrkslu; U+0298D
Lcaron; U+0013D Ľ
lcaron; U+0013E ľ
Lcedil; U+0013B Ļ
lcedil; U+0013C ļ
lceil; U+02308
lcub; U+0007B {
Lcy; U+0041B Л
lcy; U+0043B л
ldca; U+02936
ldquo; U+0201C
ldquor; U+0201E
ldrdhar; U+02967
ldrushar; U+0294B
ldsh; U+021B2
lE; U+02266
le; U+02264
LeftAngleBracket; U+027E8
LeftArrow; U+02190
Leftarrow; U+021D0
leftarrow; U+02190
LeftArrowBar; U+021E4
LeftArrowRightArrow; U+021C6
leftarrowtail; U+021A2
LeftCeiling; U+02308
LeftDoubleBracket; U+027E6
LeftDownTeeVector; U+02961
LeftDownVector; U+021C3
LeftDownVectorBar; U+02959
LeftFloor; U+0230A
leftharpoondown; U+021BD
leftharpoonup; U+021BC
leftleftarrows; U+021C7
LeftRightArrow; U+02194
Leftrightarrow; U+021D4
leftrightarrow; U+02194
leftrightarrows; U+021C6
leftrightharpoons; U+021CB
leftrightsquigarrow; U+021AD
LeftRightVector; U+0294E
LeftTee; U+022A3
LeftTeeArrow; U+021A4
LeftTeeVector; U+0295A
leftthreetimes; U+022CB
LeftTriangle; U+022B2
LeftTriangleBar; U+029CF
LeftTriangleEqual; U+022B4
LeftUpDownVector; U+02951
LeftUpTeeVector; U+02960
LeftUpVector; U+021BF
LeftUpVectorBar; U+02958
LeftVector; U+021BC
LeftVectorBar; U+02952
lEg; U+02A8B
leg; U+022DA
leq; U+02264
leqq; U+02266
leqslant; U+02A7D
les; U+02A7D
lescc; U+02AA8
lesdot; U+02A7F ⩿
lesdoto; U+02A81
lesdotor; U+02A83
lesg; U+022DA U+0FE00 ⋚︀
lesges; U+02A93
lessapprox; U+02A85
lessdot; U+022D6
lesseqgtr; U+022DA
lesseqqgtr; U+02A8B
LessEqualGreater; U+022DA
LessFullEqual; U+02266
LessGreater; U+02276
lessgtr; U+02276
LessLess; U+02AA1
lesssim; U+02272
LessSlantEqual; U+02A7D
LessTilde; U+02272
lfisht; U+0297C
lfloor; U+0230A
Lfr; U+1D50F 𝔏
lfr; U+1D529 𝔩
lg; U+02276
lgE; U+02A91
lHar; U+02962
lhard; U+021BD
lharu; U+021BC
lharul; U+0296A
lhblk; U+02584
LJcy; U+00409 Љ
ljcy; U+00459 љ
Ll; U+022D8
ll; U+0226A
llarr; U+021C7
llcorner; U+0231E
Lleftarrow; U+021DA
llhard; U+0296B
lltri; U+025FA
Lmidot; U+0013F Ŀ
lmidot; U+00140 ŀ
lmoust; U+023B0
lmoustache; U+023B0
lnap; U+02A89
lnapprox; U+02A89
lnE; U+02268
lne; U+02A87
lneq; U+02A87
lneqq; U+02268
lnsim; U+022E6
loang; U+027EC
loarr; U+021FD
lobrk; U+027E6
LongLeftArrow; U+027F5
Longleftarrow; U+027F8
longleftarrow; U+027F5
LongLeftRightArrow; U+027F7
Longleftrightarrow; U+027FA
longleftrightarrow; U+027F7
longmapsto; U+027FC
LongRightArrow; U+027F6
Longrightarrow; U+027F9
longrightarrow; U+027F6
looparrowleft; U+021AB
looparrowright; U+021AC
lopar; U+02985
Lopf; U+1D543 𝕃
lopf; U+1D55D 𝕝
loplus; U+02A2D
lotimes; U+02A34
lowast; U+02217
lowbar; U+0005F _
LowerLeftArrow; U+02199
LowerRightArrow; U+02198
loz; U+025CA
lozenge; U+025CA
lozf; U+029EB
lpar; U+00028 (
lparlt; U+02993
lrarr; U+021C6
lrcorner; U+0231F
lrhar; U+021CB
lrhard; U+0296D
lrm; U+0200E
lrtri; U+022BF
lsaquo; U+02039
Lscr; U+02112
lscr; U+1D4C1 𝓁
Lsh; U+021B0
lsh; U+021B0
lsim; U+02272
lsime; U+02A8D
lsimg; U+02A8F
lsqb; U+0005B [
lsquo; U+02018
lsquor; U+0201A
Lstrok; U+00141 Ł
lstrok; U+00142 ł
LT; U+0003C <
LT U+0003C <
Lt; U+0226A
lt; U+0003C <
lt U+0003C <
ltcc; U+02AA6
ltcir; U+02A79
ltdot; U+022D6
lthree; U+022CB
ltimes; U+022C9
ltlarr; U+02976
ltquest; U+02A7B
ltri; U+025C3
ltrie; U+022B4
ltrif; U+025C2
ltrPar; U+02996
lurdshar; U+0294A
luruhar; U+02966
lvertneqq; U+02268 U+0FE00 ≨︀
lvnE; U+02268 U+0FE00 ≨︀
macr; U+000AF ¯
macr U+000AF ¯
male; U+02642
malt; U+02720
maltese; U+02720
Map; U+02905
map; U+021A6
mapsto; U+021A6
mapstodown; U+021A7
mapstoleft; U+021A4
mapstoup; U+021A5
marker; U+025AE
mcomma; U+02A29
Mcy; U+0041C М
mcy; U+0043C м
mdash; U+02014
mDDot; U+0223A
measuredangle; U+02221
MediumSpace; U+0205F
Mellintrf; U+02133
Mfr; U+1D510 𝔐
mfr; U+1D52A 𝔪
mho; U+02127
micro; U+000B5 µ
micro U+000B5 µ
mid; U+02223
midast; U+0002A *
midcir; U+02AF0
middot; U+000B7 ·
middot U+000B7 ·
minus; U+02212
minusb; U+0229F
minusd; U+02238
minusdu; U+02A2A
MinusPlus; U+02213
mlcp; U+02ADB
mldr; U+02026
mnplus; U+02213
models; U+022A7
Mopf; U+1D544 𝕄
mopf; U+1D55E 𝕞
mp; U+02213
Mscr; U+02133
mscr; U+1D4C2 𝓂
mstpos; U+0223E
Mu; U+0039C Μ
mu; U+003BC μ
multimap; U+022B8
mumap; U+022B8
nabla; U+02207
Nacute; U+00143 Ń
nacute; U+00144 ń
nang; U+02220 U+020D2 ∠⃒
nap; U+02249
napE; U+02A70 U+00338 ⩰̸
napid; U+0224B U+00338 ≋̸
napos; U+00149 ʼn
napprox; U+02249
natur; U+0266E
natural; U+0266E
naturals; U+02115
nbsp; U+000A0
nbsp U+000A0
nbump; U+0224E U+00338 ≎̸
nbumpe; U+0224F U+00338 ≏̸
ncap; U+02A43
Ncaron; U+00147 Ň
ncaron; U+00148 ň
Ncedil; U+00145 Ņ
ncedil; U+00146 ņ
ncong; U+02247
ncongdot; U+02A6D U+00338 ⩭̸
ncup; U+02A42
Ncy; U+0041D Н
ncy; U+0043D н
ndash; U+02013
ne; U+02260
nearhk; U+02924
neArr; U+021D7
nearr; U+02197
nearrow; U+02197
nedot; U+02250 U+00338 ≐̸
NegativeMediumSpace; U+0200B
NegativeThickSpace; U+0200B
NegativeThinSpace; U+0200B
NegativeVeryThinSpace; U+0200B
nequiv; U+02262
nesear; U+02928
nesim; U+02242 U+00338 ≂̸
NestedGreaterGreater; U+0226B
NestedLessLess; U+0226A
NewLine; U+0000A
nexist; U+02204
nexists; U+02204
Nfr; U+1D511 𝔑
nfr; U+1D52B 𝔫
ngE; U+02267 U+00338 ≧̸
nge; U+02271
ngeq; U+02271
ngeqq; U+02267 U+00338 ≧̸
ngeqslant; U+02A7E U+00338 ⩾̸
nges; U+02A7E U+00338 ⩾̸
nGg; U+022D9 U+00338 ⋙̸
ngsim; U+02275
nGt; U+0226B U+020D2 ≫⃒
ngt; U+0226F
ngtr; U+0226F
nGtv; U+0226B U+00338 ≫̸
nhArr; U+021CE
nharr; U+021AE
nhpar; U+02AF2
ni; U+0220B
nis; U+022FC
nisd; U+022FA
niv; U+0220B
NJcy; U+0040A Њ
njcy; U+0045A њ
nlArr; U+021CD
nlarr; U+0219A
nldr; U+02025
nlE; U+02266 U+00338 ≦̸
nle; U+02270
nLeftarrow; U+021CD
nleftarrow; U+0219A
nLeftrightarrow; U+021CE
nleftrightarrow; U+021AE
nleq; U+02270
nleqq; U+02266 U+00338 ≦̸
nleqslant; U+02A7D U+00338 ⩽̸
nles; U+02A7D U+00338 ⩽̸
nless; U+0226E
nLl; U+022D8 U+00338 ⋘̸
nlsim; U+02274
nLt; U+0226A U+020D2 ≪⃒
nlt; U+0226E
nltri; U+022EA
nltrie; U+022EC
nLtv; U+0226A U+00338 ≪̸
nmid; U+02224
NoBreak; U+02060
NonBreakingSpace; U+000A0
Nopf; U+02115
nopf; U+1D55F 𝕟
Not; U+02AEC
not; U+000AC ¬
not U+000AC ¬
NotCongruent; U+02262
NotCupCap; U+0226D
NotDoubleVerticalBar; U+02226
NotElement; U+02209
NotEqual; U+02260
NotEqualTilde; U+02242 U+00338 ≂̸
NotExists; U+02204
NotGreater; U+0226F
NotGreaterEqual; U+02271
NotGreaterFullEqual; U+02267 U+00338 ≧̸
NotGreaterGreater; U+0226B U+00338 ≫̸
NotGreaterLess; U+02279
NotGreaterSlantEqual; U+02A7E U+00338 ⩾̸
NotGreaterTilde; U+02275
NotHumpDownHump; U+0224E U+00338 ≎̸
NotHumpEqual; U+0224F U+00338 ≏̸
notin; U+02209
notindot; U+022F5 U+00338 ⋵̸
notinE; U+022F9 U+00338 ⋹̸
notinva; U+02209
notinvb; U+022F7
notinvc; U+022F6
NotLeftTriangle; U+022EA
NotLeftTriangleBar; U+029CF U+00338 ⧏̸
NotLeftTriangleEqual; U+022EC
NotLess; U+0226E
NotLessEqual; U+02270
NotLessGreater; U+02278
NotLessLess; U+0226A U+00338 ≪̸
NotLessSlantEqual; U+02A7D U+00338 ⩽̸
NotLessTilde; U+02274
NotNestedGreaterGreater; U+02AA2 U+00338 ⪢̸
NotNestedLessLess; U+02AA1 U+00338 ⪡̸
notni; U+0220C
notniva; U+0220C
notnivb; U+022FE
notnivc; U+022FD
NotPrecedes; U+02280
NotPrecedesEqual; U+02AAF U+00338 ⪯̸
NotPrecedesSlantEqual; U+022E0
NotReverseElement; U+0220C
NotRightTriangle; U+022EB
NotRightTriangleBar; U+029D0 U+00338 ⧐̸
NotRightTriangleEqual; U+022ED
NotSquareSubset; U+0228F U+00338 ⊏̸
NotSquareSubsetEqual; U+022E2
NotSquareSuperset; U+02290 U+00338 ⊐̸
NotSquareSupersetEqual; U+022E3
NotSubset; U+02282 U+020D2 ⊂⃒
NotSubsetEqual; U+02288
NotSucceeds; U+02281
NotSucceedsEqual; U+02AB0 U+00338 ⪰̸
NotSucceedsSlantEqual; U+022E1
NotSucceedsTilde; U+0227F U+00338 ≿̸
NotSuperset; U+02283 U+020D2 ⊃⃒
NotSupersetEqual; U+02289
NotTilde; U+02241
NotTildeEqual; U+02244
NotTildeFullEqual; U+02247
NotTildeTilde; U+02249
NotVerticalBar; U+02224
npar; U+02226
nparallel; U+02226
nparsl; U+02AFD U+020E5 ⫽⃥
npart; U+02202 U+00338 ∂̸
npolint; U+02A14
npr; U+02280
nprcue; U+022E0
npre; U+02AAF U+00338 ⪯̸
nprec; U+02280
npreceq; U+02AAF U+00338 ⪯̸
nrArr; U+021CF
nrarr; U+0219B
nrarrc; U+02933 U+00338 ⤳̸
nrarrw; U+0219D U+00338 ↝̸
nRightarrow; U+021CF
nrightarrow; U+0219B
nrtri; U+022EB
nrtrie; U+022ED
nsc; U+02281
nsccue; U+022E1
nsce; U+02AB0 U+00338 ⪰̸
Nscr; U+1D4A9 𝒩
nscr; U+1D4C3 𝓃
nshortmid; U+02224
nshortparallel; U+02226
nsim; U+02241
nsime; U+02244
nsimeq; U+02244
nsmid; U+02224
nspar; U+02226
nsqsube; U+022E2
nsqsupe; U+022E3
nsub; U+02284
nsubE; U+02AC5 U+00338 ⫅̸
nsube; U+02288
nsubset; U+02282 U+020D2 ⊂⃒
nsubseteq; U+02288
nsubseteqq; U+02AC5 U+00338 ⫅̸
nsucc; U+02281
nsucceq; U+02AB0 U+00338 ⪰̸
nsup; U+02285
nsupE; U+02AC6 U+00338 ⫆̸
nsupe; U+02289
nsupset; U+02283 U+020D2 ⊃⃒
nsupseteq; U+02289
nsupseteqq; U+02AC6 U+00338 ⫆̸
ntgl; U+02279
Ntilde; U+000D1 Ñ
Ntilde U+000D1 Ñ
ntilde; U+000F1 ñ
ntilde U+000F1 ñ
ntlg; U+02278
ntriangleleft; U+022EA
ntrianglelefteq; U+022EC
ntriangleright; U+022EB
ntrianglerighteq; U+022ED
Nu; U+0039D Ν
nu; U+003BD ν
num; U+00023 #
numero; U+02116
numsp; U+02007
nvap; U+0224D U+020D2 ≍⃒
nVDash; U+022AF
nVdash; U+022AE
nvDash; U+022AD
nvdash; U+022AC
nvge; U+02265 U+020D2 ≥⃒
nvgt; U+0003E U+020D2 >⃒
nvHarr; U+02904
nvinfin; U+029DE
nvlArr; U+02902
nvle; U+02264 U+020D2 ≤⃒
nvlt; U+0003C U+020D2 <⃒
nvltrie; U+022B4 U+020D2 ⊴⃒
nvrArr; U+02903
nvrtrie; U+022B5 U+020D2 ⊵⃒
nvsim; U+0223C U+020D2 ∼⃒
nwarhk; U+02923
nwArr; U+021D6
nwarr; U+02196
nwarrow; U+02196
nwnear; U+02927
Oacute; U+000D3 Ó
Oacute U+000D3 Ó
oacute; U+000F3 ó
oacute U+000F3 ó
oast; U+0229B
ocir; U+0229A
Ocirc; U+000D4 Ô
Ocirc U+000D4 Ô
ocirc; U+000F4 ô
ocirc U+000F4 ô
Ocy; U+0041E О
ocy; U+0043E о
odash; U+0229D
Odblac; U+00150 Ő
odblac; U+00151 ő
odiv; U+02A38
odot; U+02299
odsold; U+029BC
OElig; U+00152 Œ
oelig; U+00153 œ
ofcir; U+029BF ⦿
Ofr; U+1D512 𝔒
ofr; U+1D52C 𝔬
ogon; U+002DB ˛
Ograve; U+000D2 Ò
Ograve U+000D2 Ò
ograve; U+000F2 ò
ograve U+000F2 ò
ogt; U+029C1
ohbar; U+029B5
ohm; U+003A9 Ω
oint; U+0222E
olarr; U+021BA
olcir; U+029BE
olcross; U+029BB
oline; U+0203E
olt; U+029C0
Omacr; U+0014C Ō
omacr; U+0014D ō
Omega; U+003A9 Ω
omega; U+003C9 ω
Omicron; U+0039F Ο
omicron; U+003BF ο
omid; U+029B6
ominus; U+02296
Oopf; U+1D546 𝕆
oopf; U+1D560 𝕠
opar; U+029B7
OpenCurlyDoubleQuote; U+0201C
OpenCurlyQuote; U+02018
operp; U+029B9
oplus; U+02295
Or; U+02A54
or; U+02228
orarr; U+021BB
ord; U+02A5D
order; U+02134
orderof; U+02134
ordf; U+000AA ª
ordf U+000AA ª
ordm; U+000BA º
ordm U+000BA º
origof; U+022B6
oror; U+02A56
orslope; U+02A57
orv; U+02A5B
oS; U+024C8
Oscr; U+1D4AA 𝒪
oscr; U+02134
Oslash; U+000D8 Ø
Oslash U+000D8 Ø
oslash; U+000F8 ø
oslash U+000F8 ø
osol; U+02298
Otilde; U+000D5 Õ
Otilde U+000D5 Õ
otilde; U+000F5 õ
otilde U+000F5 õ
Otimes; U+02A37
otimes; U+02297
otimesas; U+02A36
Ouml; U+000D6 Ö
Ouml U+000D6 Ö
ouml; U+000F6 ö
ouml U+000F6 ö
ovbar; U+0233D
OverBar; U+0203E
OverBrace; U+023DE
OverBracket; U+023B4
OverParenthesis; U+023DC
par; U+02225
para; U+000B6
para U+000B6
parallel; U+02225
parsim; U+02AF3
parsl; U+02AFD
part; U+02202
PartialD; U+02202
Pcy; U+0041F П
pcy; U+0043F п
percnt; U+00025 %
period; U+0002E .
permil; U+02030
perp; U+022A5
pertenk; U+02031
Pfr; U+1D513 𝔓
pfr; U+1D52D 𝔭
Phi; U+003A6 Φ
phi; U+003C6 φ
phiv; U+003D5 ϕ
phmmat; U+02133
phone; U+0260E
Pi; U+003A0 Π
pi; U+003C0 π
pitchfork; U+022D4
piv; U+003D6 ϖ
planck; U+0210F
planckh; U+0210E
plankv; U+0210F
plus; U+0002B +
plusacir; U+02A23
plusb; U+0229E
pluscir; U+02A22
plusdo; U+02214
plusdu; U+02A25
pluse; U+02A72
PlusMinus; U+000B1 ±
plusmn; U+000B1 ±
plusmn U+000B1 ±
plussim; U+02A26
plustwo; U+02A27
pm; U+000B1 ±
Poincareplane; U+0210C
pointint; U+02A15
Popf; U+02119
popf; U+1D561 𝕡
pound; U+000A3 £
pound U+000A3 £
Pr; U+02ABB
pr; U+0227A
prap; U+02AB7
prcue; U+0227C
prE; U+02AB3
pre; U+02AAF
prec; U+0227A
precapprox; U+02AB7
preccurlyeq; U+0227C
Precedes; U+0227A
PrecedesEqual; U+02AAF
PrecedesSlantEqual; U+0227C
PrecedesTilde; U+0227E
preceq; U+02AAF
precnapprox; U+02AB9
precneqq; U+02AB5
precnsim; U+022E8
precsim; U+0227E
Prime; U+02033
prime; U+02032
primes; U+02119
prnap; U+02AB9
prnE; U+02AB5
prnsim; U+022E8
prod; U+0220F
Product; U+0220F
profalar; U+0232E
profline; U+02312
profsurf; U+02313
prop; U+0221D
Proportion; U+02237
Proportional; U+0221D
propto; U+0221D
prsim; U+0227E
prurel; U+022B0
Pscr; U+1D4AB 𝒫
pscr; U+1D4C5 𝓅
Psi; U+003A8 Ψ
psi; U+003C8 ψ
puncsp; U+02008
Qfr; U+1D514 𝔔
qfr; U+1D52E 𝔮
qint; U+02A0C
Qopf; U+0211A
qopf; U+1D562 𝕢
qprime; U+02057
Qscr; U+1D4AC 𝒬
qscr; U+1D4C6 𝓆
quaternions; U+0210D
quatint; U+02A16
quest; U+0003F ?
questeq; U+0225F
QUOT; U+00022 "
QUOT U+00022 "
quot; U+00022 "
quot U+00022 "
rAarr; U+021DB
race; U+0223D U+00331 ∽̱
Racute; U+00154 Ŕ
racute; U+00155 ŕ
radic; U+0221A
raemptyv; U+029B3
Rang; U+027EB
rang; U+027E9
rangd; U+02992
range; U+029A5
rangle; U+027E9
raquo; U+000BB »
raquo U+000BB »
Rarr; U+021A0
rArr; U+021D2
rarr; U+02192
rarrap; U+02975
rarrb; U+021E5
rarrbfs; U+02920
rarrc; U+02933
rarrfs; U+0291E
rarrhk; U+021AA
rarrlp; U+021AC
rarrpl; U+02945
rarrsim; U+02974
Rarrtl; U+02916
rarrtl; U+021A3
rarrw; U+0219D
rAtail; U+0291C
ratail; U+0291A
ratio; U+02236
rationals; U+0211A
RBarr; U+02910
rBarr; U+0290F
rbarr; U+0290D
rbbrk; U+02773
rbrace; U+0007D }
rbrack; U+0005D ]
rbrke; U+0298C
rbrksld; U+0298E
rbrkslu; U+02990
Rcaron; U+00158 Ř
rcaron; U+00159 ř
Rcedil; U+00156 Ŗ
rcedil; U+00157 ŗ
rceil; U+02309
rcub; U+0007D }
Rcy; U+00420 Р
rcy; U+00440 р
rdca; U+02937
rdldhar; U+02969
rdquo; U+0201D
rdquor; U+0201D
rdsh; U+021B3
Re; U+0211C
real; U+0211C
realine; U+0211B
realpart; U+0211C
reals; U+0211D
rect; U+025AD
REG; U+000AE ®
REG U+000AE ®
reg; U+000AE ®
reg U+000AE ®
ReverseElement; U+0220B
ReverseEquilibrium; U+021CB
ReverseUpEquilibrium; U+0296F
rfisht; U+0297D
rfloor; U+0230B
Rfr; U+0211C
rfr; U+1D52F 𝔯
rHar; U+02964
rhard; U+021C1
rharu; U+021C0
rharul; U+0296C
Rho; U+003A1 Ρ
rho; U+003C1 ρ
rhov; U+003F1 ϱ
RightAngleBracket; U+027E9
RightArrow; U+02192
Rightarrow; U+021D2
rightarrow; U+02192
RightArrowBar; U+021E5
RightArrowLeftArrow; U+021C4
rightarrowtail; U+021A3
RightCeiling; U+02309
RightDoubleBracket; U+027E7
RightDownTeeVector; U+0295D
RightDownVector; U+021C2
RightDownVectorBar; U+02955
RightFloor; U+0230B
rightharpoondown; U+021C1
rightharpoonup; U+021C0
rightleftarrows; U+021C4
rightleftharpoons; U+021CC
rightrightarrows; U+021C9
rightsquigarrow; U+0219D
RightTee; U+022A2
RightTeeArrow; U+021A6
RightTeeVector; U+0295B
rightthreetimes; U+022CC
RightTriangle; U+022B3
RightTriangleBar; U+029D0
RightTriangleEqual; U+022B5
RightUpDownVector; U+0294F
RightUpTeeVector; U+0295C
RightUpVector; U+021BE
RightUpVectorBar; U+02954
RightVector; U+021C0
RightVectorBar; U+02953
ring; U+002DA ˚
risingdotseq; U+02253
rlarr; U+021C4
rlhar; U+021CC
rlm; U+0200F
rmoust; U+023B1
rmoustache; U+023B1
rnmid; U+02AEE
roang; U+027ED
roarr; U+021FE
robrk; U+027E7
ropar; U+02986
Ropf; U+0211D
ropf; U+1D563 𝕣
roplus; U+02A2E
rotimes; U+02A35
RoundImplies; U+02970
rpar; U+00029 )
rpargt; U+02994
rppolint; U+02A12
rrarr; U+021C9
Rrightarrow; U+021DB
rsaquo; U+0203A
Rscr; U+0211B
rscr; U+1D4C7 𝓇
Rsh; U+021B1
rsh; U+021B1
rsqb; U+0005D ]
rsquo; U+02019
rsquor; U+02019
rthree; U+022CC
rtimes; U+022CA
rtri; U+025B9
rtrie; U+022B5
rtrif; U+025B8
rtriltri; U+029CE
RuleDelayed; U+029F4
ruluhar; U+02968
rx; U+0211E
Sacute; U+0015A Ś
sacute; U+0015B ś
sbquo; U+0201A
Sc; U+02ABC
sc; U+0227B
scap; U+02AB8
Scaron; U+00160 Š
scaron; U+00161 š
sccue; U+0227D
scE; U+02AB4
sce; U+02AB0
Scedil; U+0015E Ş
scedil; U+0015F ş
Scirc; U+0015C Ŝ
scirc; U+0015D ŝ
scnap; U+02ABA
scnE; U+02AB6
scnsim; U+022E9
scpolint; U+02A13
scsim; U+0227F
Scy; U+00421 С
scy; U+00441 с
sdot; U+022C5
sdotb; U+022A1
sdote; U+02A66
searhk; U+02925
seArr; U+021D8
searr; U+02198
searrow; U+02198
sect; U+000A7 §
sect U+000A7 §
semi; U+0003B ;
seswar; U+02929
setminus; U+02216
setmn; U+02216
sext; U+02736
Sfr; U+1D516 𝔖
sfr; U+1D530 𝔰
sfrown; U+02322
sharp; U+0266F
SHCHcy; U+00429 Щ
shchcy; U+00449 щ
SHcy; U+00428 Ш
shcy; U+00448 ш
ShortDownArrow; U+02193
ShortLeftArrow; U+02190
shortmid; U+02223
shortparallel; U+02225
ShortRightArrow; U+02192
ShortUpArrow; U+02191
shy; U+000AD ­
shy U+000AD ­
Sigma; U+003A3 Σ
sigma; U+003C3 σ
sigmaf; U+003C2 ς
sigmav; U+003C2 ς
sim; U+0223C
simdot; U+02A6A
sime; U+02243
simeq; U+02243
simg; U+02A9E
simgE; U+02AA0
siml; U+02A9D
simlE; U+02A9F
simne; U+02246
simplus; U+02A24
simrarr; U+02972
slarr; U+02190
SmallCircle; U+02218
smallsetminus; U+02216
smashp; U+02A33
smeparsl; U+029E4
smid; U+02223
smile; U+02323
smt; U+02AAA
smte; U+02AAC
smtes; U+02AAC U+0FE00 ⪬︀
SOFTcy; U+0042C Ь
softcy; U+0044C ь
sol; U+0002F /
solb; U+029C4
solbar; U+0233F
Sopf; U+1D54A 𝕊
sopf; U+1D564 𝕤
spades; U+02660
spadesuit; U+02660
spar; U+02225
sqcap; U+02293
sqcaps; U+02293 U+0FE00 ⊓︀
sqcup; U+02294
sqcups; U+02294 U+0FE00 ⊔︀
Sqrt; U+0221A
sqsub; U+0228F
sqsube; U+02291
sqsubset; U+0228F
sqsubseteq; U+02291
sqsup; U+02290
sqsupe; U+02292
sqsupset; U+02290
sqsupseteq; U+02292
squ; U+025A1
Square; U+025A1
square; U+025A1
SquareIntersection; U+02293
SquareSubset; U+0228F
SquareSubsetEqual; U+02291
SquareSuperset; U+02290
SquareSupersetEqual; U+02292
SquareUnion; U+02294
squarf; U+025AA
squf; U+025AA
srarr; U+02192
Sscr; U+1D4AE 𝒮
sscr; U+1D4C8 𝓈
ssetmn; U+02216
ssmile; U+02323
sstarf; U+022C6
Star; U+022C6
star; U+02606
starf; U+02605
straightepsilon; U+003F5 ϵ
straightphi; U+003D5 ϕ
strns; U+000AF ¯
Sub; U+022D0
sub; U+02282
subdot; U+02ABD
subE; U+02AC5
sube; U+02286
subedot; U+02AC3
submult; U+02AC1
subnE; U+02ACB
subne; U+0228A
subplus; U+02ABF ⪿
subrarr; U+02979
Subset; U+022D0
subset; U+02282
subseteq; U+02286
subseteqq; U+02AC5
SubsetEqual; U+02286
subsetneq; U+0228A
subsetneqq; U+02ACB
subsim; U+02AC7
subsub; U+02AD5
subsup; U+02AD3
succ; U+0227B
succapprox; U+02AB8
succcurlyeq; U+0227D
Succeeds; U+0227B
SucceedsEqual; U+02AB0
SucceedsSlantEqual; U+0227D
SucceedsTilde; U+0227F
succeq; U+02AB0
succnapprox; U+02ABA
succneqq; U+02AB6
succnsim; U+022E9
succsim; U+0227F
SuchThat; U+0220B
Sum; U+02211
sum; U+02211
sung; U+0266A
Sup; U+022D1
sup; U+02283
sup1; U+000B9 ¹
sup1 U+000B9 ¹
sup2; U+000B2 ²
sup2 U+000B2 ²
sup3; U+000B3 ³
sup3 U+000B3 ³
supdot; U+02ABE
supdsub; U+02AD8
supE; U+02AC6
supe; U+02287
supedot; U+02AC4
Superset; U+02283
SupersetEqual; U+02287
suphsol; U+027C9
suphsub; U+02AD7
suplarr; U+0297B
supmult; U+02AC2
supnE; U+02ACC
supne; U+0228B
supplus; U+02AC0
Supset; U+022D1
supset; U+02283
supseteq; U+02287
supseteqq; U+02AC6
supsetneq; U+0228B
supsetneqq; U+02ACC
supsim; U+02AC8
supsub; U+02AD4
supsup; U+02AD6
swarhk; U+02926
swArr; U+021D9
swarr; U+02199
swarrow; U+02199
swnwar; U+0292A
szlig; U+000DF ß
szlig U+000DF ß
Tab; U+00009
target; U+02316
Tau; U+003A4 Τ
tau; U+003C4 τ
tbrk; U+023B4
Tcaron; U+00164 Ť
tcaron; U+00165 ť
Tcedil; U+00162 Ţ
tcedil; U+00163 ţ
Tcy; U+00422 Т
tcy; U+00442 т
tdot; U+020DB ◌⃛
telrec; U+02315
Tfr; U+1D517 𝔗
tfr; U+1D531 𝔱
there4; U+02234
Therefore; U+02234
therefore; U+02234
Theta; U+00398 Θ
theta; U+003B8 θ
thetasym; U+003D1 ϑ
thetav; U+003D1 ϑ
thickapprox; U+02248
thicksim; U+0223C
ThickSpace; U+0205F U+0200A   
thinsp; U+02009
ThinSpace; U+02009
thkap; U+02248
thksim; U+0223C
THORN; U+000DE Þ
THORN U+000DE Þ
thorn; U+000FE þ
thorn U+000FE þ
Tilde; U+0223C
tilde; U+002DC ˜
TildeEqual; U+02243
TildeFullEqual; U+02245
TildeTilde; U+02248
times; U+000D7 ×
times U+000D7 ×
timesb; U+022A0
timesbar; U+02A31
timesd; U+02A30
tint; U+0222D
toea; U+02928
top; U+022A4
topbot; U+02336
topcir; U+02AF1
Topf; U+1D54B 𝕋
topf; U+1D565 𝕥
topfork; U+02ADA
tosa; U+02929
tprime; U+02034
TRADE; U+02122
trade; U+02122
triangle; U+025B5
triangledown; U+025BF
triangleleft; U+025C3
trianglelefteq; U+022B4
triangleq; U+0225C
triangleright; U+025B9
trianglerighteq; U+022B5
tridot; U+025EC
trie; U+0225C
triminus; U+02A3A
TripleDot; U+020DB ◌⃛
triplus; U+02A39
trisb; U+029CD
tritime; U+02A3B
trpezium; U+023E2
Tscr; U+1D4AF 𝒯
tscr; U+1D4C9 𝓉
TScy; U+00426 Ц
tscy; U+00446 ц
TSHcy; U+0040B Ћ
tshcy; U+0045B ћ
Tstrok; U+00166 Ŧ
tstrok; U+00167 ŧ
twixt; U+0226C
twoheadleftarrow; U+0219E
twoheadrightarrow; U+021A0
Uacute; U+000DA Ú
Uacute U+000DA Ú
uacute; U+000FA ú
uacute U+000FA ú
Uarr; U+0219F
uArr; U+021D1
uarr; U+02191
Uarrocir; U+02949
Ubrcy; U+0040E Ў
ubrcy; U+0045E ў
Ubreve; U+0016C Ŭ
ubreve; U+0016D ŭ
Ucirc; U+000DB Û
Ucirc U+000DB Û
ucirc; U+000FB û
ucirc U+000FB û
Ucy; U+00423 У
ucy; U+00443 у
udarr; U+021C5
Udblac; U+00170 Ű
udblac; U+00171 ű
udhar; U+0296E
ufisht; U+0297E
Ufr; U+1D518 𝔘
ufr; U+1D532 𝔲
Ugrave; U+000D9 Ù
Ugrave U+000D9 Ù
ugrave; U+000F9 ù
ugrave U+000F9 ù
uHar; U+02963
uharl; U+021BF
uharr; U+021BE
uhblk; U+02580
ulcorn; U+0231C
ulcorner; U+0231C
ulcrop; U+0230F
ultri; U+025F8
Umacr; U+0016A Ū
umacr; U+0016B ū
uml; U+000A8 ¨
uml U+000A8 ¨
UnderBar; U+0005F _
UnderBrace; U+023DF
UnderBracket; U+023B5
UnderParenthesis; U+023DD
Union; U+022C3
UnionPlus; U+0228E
Uogon; U+00172 Ų
uogon; U+00173 ų
Uopf; U+1D54C 𝕌
uopf; U+1D566 𝕦
UpArrow; U+02191
Uparrow; U+021D1
uparrow; U+02191
UpArrowBar; U+02912
UpArrowDownArrow; U+021C5
UpDownArrow; U+02195
Updownarrow; U+021D5
updownarrow; U+02195
UpEquilibrium; U+0296E
upharpoonleft; U+021BF
upharpoonright; U+021BE
uplus; U+0228E
UpperLeftArrow; U+02196
UpperRightArrow; U+02197
Upsi; U+003D2 ϒ
upsi; U+003C5 υ
upsih; U+003D2 ϒ
Upsilon; U+003A5 Υ
upsilon; U+003C5 υ
UpTee; U+022A5
UpTeeArrow; U+021A5
upuparrows; U+021C8
urcorn; U+0231D
urcorner; U+0231D
urcrop; U+0230E
Uring; U+0016E Ů
uring; U+0016F ů
urtri; U+025F9
Uscr; U+1D4B0 𝒰
uscr; U+1D4CA 𝓊
utdot; U+022F0
Utilde; U+00168 Ũ
utilde; U+00169 ũ
utri; U+025B5
utrif; U+025B4
uuarr; U+021C8
Uuml; U+000DC Ü
Uuml U+000DC Ü
uuml; U+000FC ü
uuml U+000FC ü
uwangle; U+029A7
vangrt; U+0299C
varepsilon; U+003F5 ϵ
varkappa; U+003F0 ϰ
varnothing; U+02205
varphi; U+003D5 ϕ
varpi; U+003D6 ϖ
varpropto; U+0221D
vArr; U+021D5
varr; U+02195
varrho; U+003F1 ϱ
varsigma; U+003C2 ς
varsubsetneq; U+0228A U+0FE00 ⊊︀
varsubsetneqq; U+02ACB U+0FE00 ⫋︀
varsupsetneq; U+0228B U+0FE00 ⊋︀
varsupsetneqq; U+02ACC U+0FE00 ⫌︀
vartheta; U+003D1 ϑ
vartriangleleft; U+022B2
vartriangleright; U+022B3
Vbar; U+02AEB
vBar; U+02AE8
vBarv; U+02AE9
Vcy; U+00412 В
vcy; U+00432 в
VDash; U+022AB
Vdash; U+022A9
vDash; U+022A8
vdash; U+022A2
Vdashl; U+02AE6
Vee; U+022C1
vee; U+02228
veebar; U+022BB
veeeq; U+0225A
vellip; U+022EE
Verbar; U+02016
verbar; U+0007C |
Vert; U+02016
vert; U+0007C |
VerticalBar; U+02223
VerticalLine; U+0007C |
VerticalSeparator; U+02758
VerticalTilde; U+02240
VeryThinSpace; U+0200A
Vfr; U+1D519 𝔙
vfr; U+1D533 𝔳
vltri; U+022B2
vnsub; U+02282 U+020D2 ⊂⃒
vnsup; U+02283 U+020D2 ⊃⃒
Vopf; U+1D54D 𝕍
vopf; U+1D567 𝕧
vprop; U+0221D
vrtri; U+022B3
Vscr; U+1D4B1 𝒱
vscr; U+1D4CB 𝓋
vsubnE; U+02ACB U+0FE00 ⫋︀
vsubne; U+0228A U+0FE00 ⊊︀
vsupnE; U+02ACC U+0FE00 ⫌︀
vsupne; U+0228B U+0FE00 ⊋︀
Vvdash; U+022AA
vzigzag; U+0299A
Wcirc; U+00174 Ŵ
wcirc; U+00175 ŵ
wedbar; U+02A5F
Wedge; U+022C0
wedge; U+02227
wedgeq; U+02259
weierp; U+02118
Wfr; U+1D51A 𝔚
wfr; U+1D534 𝔴
Wopf; U+1D54E 𝕎
wopf; U+1D568 𝕨
wp; U+02118
wr; U+02240
wreath; U+02240
Wscr; U+1D4B2 𝒲
wscr; U+1D4CC 𝓌
xcap; U+022C2
xcirc; U+025EF
xcup; U+022C3
xdtri; U+025BD
Xfr; U+1D51B 𝔛
xfr; U+1D535 𝔵
xhArr; U+027FA
xharr; U+027F7
Xi; U+0039E Ξ
xi; U+003BE ξ
xlArr; U+027F8
xlarr; U+027F5
xmap; U+027FC
xnis; U+022FB
xodot; U+02A00
Xopf; U+1D54F 𝕏
xopf; U+1D569 𝕩
xoplus; U+02A01
xotime; U+02A02
xrArr; U+027F9
xrarr; U+027F6
Xscr; U+1D4B3 𝒳
xscr; U+1D4CD 𝓍
xsqcup; U+02A06
xuplus; U+02A04
xutri; U+025B3
xvee; U+022C1
xwedge; U+022C0
Yacute; U+000DD Ý
Yacute U+000DD Ý
yacute; U+000FD ý
yacute U+000FD ý
YAcy; U+0042F Я
yacy; U+0044F я
Ycirc; U+00176 Ŷ
ycirc; U+00177 ŷ
Ycy; U+0042B Ы
ycy; U+0044B ы
yen; U+000A5 ¥
yen U+000A5 ¥
Yfr; U+1D51C 𝔜
yfr; U+1D536 𝔶
YIcy; U+00407 Ї
yicy; U+00457 ї
Yopf; U+1D550 𝕐
yopf; U+1D56A 𝕪
Yscr; U+1D4B4 𝒴
yscr; U+1D4CE 𝓎
YUcy; U+0042E Ю
yucy; U+0044E ю
Yuml; U+00178 Ÿ
yuml; U+000FF ÿ
yuml U+000FF ÿ
Zacute; U+00179 Ź
zacute; U+0017A ź
Zcaron; U+0017D Ž
zcaron; U+0017E ž
Zcy; U+00417 З
zcy; U+00437 з
Zdot; U+0017B Ż
zdot; U+0017C ż
zeetrf; U+02128
ZeroWidthSpace; U+0200B
Zeta; U+00396 Ζ
zeta; U+003B6 ζ
Zfr; U+02128
zfr; U+1D537 𝔷
ZHcy; U+00416 Ж
zhcy; U+00436 ж
zigrarr; U+021DD
Zopf; U+02124
zopf; U+1D56B 𝕫
Zscr; U+1D4B5 𝒵
zscr; U+1D4CF 𝓏
zwj; U+0200D
zwnj; U+0200C

This data is also available as a JSON file.

The glyphs displayed above are non-normative. Refer to Unicode for formal definitions of the characters listed above.

The character reference names originate from XML Entity Definitions for Characters, though only the above is considered normative. [XMLENTITY]

This list is static and will not be expanded or changed in the future.

14 The XML syntax

HTML/XHTML

Support in all current engines.

Firefox2+Safari3.1+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android2+Samsung Internet1.0+Opera Android10.1+

This section only describes the rules for XML resources. Rules for text/html resources are discussed in the section above entitled "The HTML syntax".

14.1 Writing documents in the XML syntax

The XML syntax for HTML was formerly referred to as "XHTML", but this specification does not use that term (among other reasons, because no such term is used for the HTML syntaxes of MathML and SVG).

The syntax for XML is defined in XML and Namespaces in XML. [XML] [XMLNS]

This specification does not define any syntax-level requirements beyond those defined for XML proper.

XML documents may contain a DOCTYPE if desired, but this is not required to conform to this specification. This specification does not define a public or system identifier, nor provide a formal DTD.

According to XML, XML processors are not guaranteed to process the external DTD subset referenced in the DOCTYPE. This means, for example, that using entity references for characters in XML documents is unsafe if they are defined in an external file (except for &lt;, &gt;, &amp;, &quot;, and &apos;).

14.2 Parsing XML documents

This section describes the relationship between XML and the DOM, with a particular emphasis on how this interacts with HTML.

An XML parser, for the purposes of this specification, is a construct that follows the rules given in XML to map a string of bytes or characters into a Document object.

At the time of writing, no such rules actually exist.

An XML parser is either associated with a Document object when it is created, or creates one implicitly.

This Document must then be populated with DOM nodes that represent the tree structure of the input passed to the parser, as defined by XML, Namespaces in XML, and DOM. When creating DOM nodes representing elements, the create an element for a token algorithm or some equivalent that operates on appropriate XML data structures must be used, to ensure the proper element interfaces are created and that custom elements are set up correctly.

DOM mutation events must not fire for the operations that the XML parser performs on the Document's tree, but the user agent must act as if elements and attributes were individually appended and set respectively so as to trigger rules in this specification regarding what happens when an element is inserted into a document or has its attributes set, and DOM's requirements regarding mutation observers mean that mutation observers are fired (unlike mutation events). [XML] [XMLNS] [DOM] [UIEVENTS]

Between the time an element's start tag is parsed and the time either the element's end tag is parsed or the parser detects a well-formedness error, the user agent must act as if the element was in a stack of open elements.

This is used by various elements to only start certain processes once they are popped off of the stack of open elements.

This specification provides the following additional information that user agents should use when retrieving an external entity: the public identifiers given in the following list all correspond to the URL given by this link. (This URL is a DTD containing the entity declarations for the names listed in the named character references section.) [XML]

Furthermore, user agents should attempt to retrieve the above external entity's content when one of the above public identifiers is used, and should not attempt to retrieve any other external entity's content.

This is not strictly a violation of XML, but it does contradict the spirit of XML's requirements. This is motivated by a desire for user agents to all handle entities in an interoperable fashion without requiring any network access for handling external subsets. [XML]

XML parsers can be invoked with XML scripting support enabled or XML scripting support disabled. Except where otherwise specified, XML parsers are invoked with XML scripting support enabled.

When an XML parser with XML scripting support enabled creates a script element, it must have its parser document set and its force async set to false. If the parser was created as part of the XML fragment parsing algorithm, then the element's already started must be set to true. When the element's end tag is subsequently parsed, the user agent must perform a microtask checkpoint, and then prepare the script element. If this causes there to be a pending parsing-blocking script, then the user agent must run the following steps:

  1. Block this instance of the XML parser, such that the event loop will not run tasks that invoke it.

  2. Spin the event loop until the parser's Document has no style sheet that is blocking scripts and the pending parsing-blocking script's ready to be parser-executed is true.

  3. Unblock this instance of the XML parser, such that tasks that invoke it can again be run.

  4. Execute the script element given by the pending parsing-blocking script.

  5. Set the pending parsing-blocking script to null.

Since the document.write() API is not available for XML documents, much of the complexity in the HTML parser is not needed in the XML parser.

When the XML parser has XML scripting support disabled, none of this happens.

When an XML parser would append a node to a template element, it must instead append it to the template element's template contents (a DocumentFragment node).

This is a willful violation of XML; unfortunately, XML is not formally extensible in the manner that is needed for template processing. [XML]

When an XML parser creates a Node object, its node document must be set to the node document of the node into which the newly created node is to be inserted.

Certain algorithms in this specification spoon-feed the parser characters one string at a time. In such cases, the XML parser must act as it would have if faced with a single string consisting of the concatenation of all those characters.

When an XML parser reaches the end of its input, it must stop parsing, following the same rules as the HTML parser. An XML parser can also be aborted, which must again be done in the same way as for an HTML parser.

For the purposes of conformance checkers, if a resource is determined to be in the XML syntax, then it is an XML document.

14.3 Serializing XML fragments

The XML fragment serialization algorithm for a Document or Element node either returns a fragment of XML that represents that node or throws an exception.

For Documents, the algorithm must return a string in the form of a document entity, if none of the error cases below apply.

For Elements, the algorithm must return a string in the form of an internal general parsed entity, if none of the error cases below apply.

In both cases, the string returned must be XML namespace-well-formed and must be an isomorphic serialization of all of that node's relevant child nodes, in tree order. User agents may adjust prefixes and namespace declarations in the serialization (and indeed might be forced to do so in some cases to obtain namespace-well-formed XML). User agents may use a combination of regular text and character references to represent Text nodes in the DOM.

A node's relevant child nodes are those that apply given the following rules:

For template elements
The relevant child nodes are the child nodes of the template element's template contents, if any.
For all other nodes
The relevant child nodes are the child nodes of node itself, if any.

For Elements, if any of the elements in the serialization are in no namespace, the default namespace in scope for those elements must be explicitly declared as the empty string. (This doesn't apply in the Document case.) [XML] [XMLNS]

For the purposes of this section, an internal general parsed entity is considered XML namespace-well-formed if a document consisting of an element with no namespace declarations whose contents are the internal general parsed entity would itself be XML namespace-well-formed.

If any of the following error cases are found in the DOM subtree being serialized, then the algorithm must throw an "InvalidStateError" DOMException instead of returning a string:

These are the only ways to make a DOM unserialisable. The DOM enforces all the other XML constraints; for example, trying to append two elements to a Document node will throw a "HierarchyRequestError" DOMException.

14.4 Parsing XML fragments

The XML fragment parsing algorithm either returns a Document or throws a "SyntaxError" DOMException. Given a string input and a context element context, the algorithm is as follows:

  1. Create a new XML parser.

  2. Feed the parser just created the string corresponding to the start tag of the context element, declaring all the namespace prefixes that are in scope on that element in the DOM, as well as declaring the default namespace (if any) that is in scope on that element in the DOM.

    A namespace prefix is in scope if the DOM lookupNamespaceURI() method on the element would return a non-null value for that prefix.

    The default namespace is the namespace for which the DOM isDefaultNamespace() method on the element would return true.

    No DOCTYPE is passed to the parser, and therefore no external subset is referenced, and therefore no entities will be recognized.

  3. Feed the parser just created the string input.

  4. Feed the parser just created the string corresponding to the end tag of the context element.

  5. If there is an XML well-formedness or XML namespace well-formedness error, then throw a "SyntaxError" DOMException.

  6. If the document element of the resulting Document has any sibling nodes, then throw a "SyntaxError" DOMException.

  7. Return the child nodes of the document element of the resulting Document, in tree order.

15 Rendering

User agents are not required to present HTML documents in any particular way. However, this section provides a set of suggestions for rendering HTML documents that, if followed, are likely to lead to a user experience that closely resembles the experience intended by the documents' authors. So as to avoid confusion regarding the normativity of this section, "must" has not been used. Instead, the term "expected" is used to indicate behavior that will lead to this experience. For the purposes of conformance for user agents designated as supporting the suggested default rendering, the term "expected" in this section has the same conformance implications as "must".

15.1 Introduction

The suggestions in this section are generally expressed in CSS terms. User agents are expected to either support CSS, or translate from the CSS rules given in this section to approximations for other presentation mechanisms.

In the absence of style-layer rules to the contrary (e.g. author style sheets), user agents are expected to render an element so that it conveys to the user the meaning that the element represents, as described by this specification.

The suggestions in this section generally assume a visual output medium with a resolution of 96dpi or greater, but HTML is intended to apply to multiple media (it is a media-independent language). User agent implementers are encouraged to adapt the suggestions in this section to their target media.


An element is being rendered if it has any associated CSS layout boxes, SVG layout boxes, or some equivalent in other styling languages.

Just being off-screen does not mean the element is not being rendered. The presence of the hidden attribute normally means the element is not being rendered, though this might be overridden by the style sheets.

The fully active state does not affect whether an element is being rendered or not. Even if a document is not fully active and not shown at all to the user, elements within it can still qualify as "being rendered".

An element is said to intersect the viewport when it is being rendered and its associated CSS layout box intersects the viewport.

Similar to the being rendered state, elements in non-fully active documents can still intersect the viewport. The viewport is not shared between documents and might not always be shown to the user, so an element in a non-fully active document can still intersect the viewport associated with its document.

This specification does not define the precise timing for when the intersection is tested, but it is suggested that the timing match that of the Intersection Observer API. [INTERSECTIONOBSERVER]

An element is delegating its rendering to its children if it is not being rendered but its children (if any) could be rendered, as a result of CSS 'display: contents', or some equivalent in other styling languages. [CSSDISPLAY]


User agents that do not honor author-level CSS style sheets are nonetheless expected to act as if they applied the CSS rules given in these sections in a manner consistent with this specification and the relevant CSS and Unicode specifications. [CSS] [UNICODE] [BIDI]

This is especially important for issues relating to the 'display', 'unicode-bidi', and 'direction' properties.

15.2 The CSS user agent style sheet and presentational hints

The CSS rules given in these subsections are, except where otherwise specified, expected to be used as part of the user-agent level style sheet defaults for all documents that contain HTML elements.

Some rules are intended for the author-level zero-specificity presentational hints part of the CSS cascade; these are explicitly called out as presentational hints.


When the text below says that an attribute attribute on an element element maps to the pixel length property (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the parsed value as a pixel length for a presentational hint for properties.

When the text below says that an attribute attribute on an element element maps to the dimension property (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute's value using the rules for parsing dimension values doesn't generate an error, then the user agent is expected to use the parsed dimension as the value for a presentational hint for properties, with the value given as a pixel length if the dimension was a length, and with the value given as a percentage if the dimension was a percentage.

When the text below says that an attribute attribute on an element element maps to the dimension property (ignoring zero) (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute's value using the rules for parsing nonzero dimension values doesn't generate an error, then the user agent is expected to use the parsed dimension as the value for a presentational hint for properties, with the value given as a pixel length if the dimension was a length, and with the value given as a percentage if the dimension was a percentage.

When the text below says that a pair of attributes w and h on an element element map to the aspect-ratio property, it means that if element has both attributes w and h, and parsing those attributes' values using the rules for parsing non-negative integers doesn't generate an error for either, then the user agent is expected to use the parsed integers as a presentational hint for the 'aspect-ratio' property of the form auto w / h.

When the text below says that a pair of attributes w and h on an element element map to the aspect-ratio property (using dimension rules), it means that if element has both attributes w and h, and parsing those attributes' values using the rules for parsing dimension values doesn't generate an error or return a percentage for either, then the user agent is expected to use the parsed dimensions as a presentational hint for the 'aspect-ratio' property of the form auto w / h.

When a user agent is to align descendants of a node, the user agent is expected to align only those descendants that have both their 'margin-inline-start' and 'margin-inline-end' properties computing to a value other than 'auto', that are over-constrained and that have one of those two margins with a used value forced to a greater value, and that do not themselves have an applicable align attribute. When multiple elements are to align a particular descendant, the most deeply nested such element is expected to override the others. Aligned elements are expected to be aligned by having the used values of their margins on the line-left and line-right sides be set accordingly. [CSSLOGICAL] [CSSWM]

15.3 Non-replaced elements

15.3.1 Hidden elements

@namespace "http://www.w3.org/1999/xhtml";

area, base, basefont, datalist, head, link, meta, noembed,
noframes, param, rp, script, style, template, title {
  display: none;
}

[hidden]:not([hidden=until-found i]):not(embed) {
  display: none;
}

[hidden=until-found i]:not(embed) {
  content-visibility: hidden;
}

embed[hidden] { display: inline; height: 0; width: 0; } 

input[type=hidden i] { display: none !important; }

@media (scripting) {
  noscript { display: none !important; }
}

15.3.2 The page

@namespace "http://www.w3.org/1999/xhtml";

html, body { display: block; }

For each property in the table below, given a body element, the first attribute that exists maps to the pixel length property on the body element. If none of the attributes for a property are found, or if the value of the attribute that was found cannot be parsed successfully, then a default value of 8px is expected to be used for that property instead.

Property Source
'margin-top' The body element's marginheight attribute
The body element's topmargin attribute
The body element's container frame element's marginheight attribute
'margin-right' The body element's marginwidth attribute
The body element's rightmargin attribute
The body element's container frame element's marginwidth attribute
'margin-bottom' The body element's marginheight attribute
The body element's bottommargin attribute
The body element's container frame element's marginheight attribute
'margin-left' The body element's marginwidth attribute
The body element's leftmargin attribute
The body element's container frame element's marginwidth attribute

If the body element's node document's node navigable is a child navigable, and the container of that navigable is a frame or iframe element, then the container frame element of the body element is that frame or iframe element. Otherwise, there is no container frame element.

The above requirements imply that a page can change the margins of another page (including one from another origin) using, for example, an iframe. This is potentially a security risk, as it might in some cases allow an attack to contrive a situation in which a page is rendered not as the author intended, possibly for the purposes of phishing or otherwise misleading the user.


If a Document's node navigable is a child navigable, then it is expected to be positioned and sized to fit inside the content box of the container of that navigable. If the container is not being rendered, the navigable is expected to have a viewport with zero width and zero height.

If a Document's node navigable is a child navigable, the container of that navigable is a frame or iframe element, that element has a scrolling attribute, and that attribute's value is an ASCII case-insensitive match for the string "off", "noscroll", or "no", then the user agent is expected to prevent any scrollbars from being shown for the viewport of the Document's node navigable, regardless of the 'overflow' property that applies to that viewport.


When a body element has a background attribute set to a non-empty value, the new value is expected to be encoding-parsed-and-serialized relative to the element's node document, and if that does not return failure, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-image' property to the return value.

When a body element has a bgcolor attribute set, the new value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-color' property to the resulting color.

When a body element has a text attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'color' property to the resulting color.

When a body element has a link attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the 'color' property of any element in the Document matching the :link pseudo-class to the resulting color.

When a body element has a vlink attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the 'color' property of any element in the Document matching the :visited pseudo-class to the resulting color.

When a body element has an alink attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the 'color' property of any element in the Document matching the :active pseudo-class and either the :link pseudo-class or the :visited pseudo-class to the resulting color.

15.3.3 Flow content

@namespace "http://www.w3.org/1999/xhtml";

address, blockquote, center, dialog, div, figure, figcaption, footer, form,
header, hr, legend, listing, main, p, plaintext, pre, search, xmp {
  display: block;
}

blockquote, figure, listing, p, plaintext, pre, xmp {
  margin-block: 1em;
}

blockquote, figure { margin-inline: 40px; }

address { font-style: italic; }
listing, plaintext, pre, xmp {
  font-family: monospace; white-space: pre;
}

dialog:not([open]) { display: none; }
dialog {
  position: absolute;
  inset-inline-start: 0; inset-inline-end: 0;
  width: fit-content;
  height: fit-content;
  margin: auto;
  border: solid;
  padding: 1em;
  background-color: Canvas;
  color: CanvasText;
}
dialog:modal {
  position: fixed;
  overflow: auto;
  inset-block: 0;
  max-width: calc(100% - 6px - 2em);
  max-height: calc(100% - 6px - 2em);
}
dialog::backdrop {
  background: rgba(0,0,0,0.1);
}

[popover]:not(:popover-open):not(dialog[open]) {
  display:none;
}

dialog:popover-open {
  display:block;
}

[popover] {
  position: fixed;
  inset: 0;
  width: fit-content;
  height: fit-content;
  margin: auto;
  border: solid;
  padding: 0.25em;
  overflow: auto;
  color: CanvasText;
  background-color: Canvas;
}

:popover-open::backdrop {
  position: fixed;
  inset: 0;
  pointer-events: none !important;
  background-color: transparent;
}

slot {
  display: contents;
}

The following rules are also expected to apply, as presentational hints:

@namespace "http://www.w3.org/1999/xhtml";

pre[wrap] { white-space: pre-wrap; }

In quirks mode, the following rules are also expected to apply:

@namespace "http://www.w3.org/1999/xhtml";

form { margin-block-end: 1em; }

The center element, and the div element when it has an align attribute whose value is an ASCII case-insensitive match for either the string "center" or the string "middle", are expected to center text within themselves, as if they had their 'text-align' property set to 'center' in a presentational hint, and to align descendants to the center.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "left", is expected to left-align text within itself, as if it had its 'text-align' property set to 'left' in a presentational hint, and to align descendants to the left.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "right", is expected to right-align text within itself, as if it had its 'text-align' property set to 'right' in a presentational hint, and to align descendants to the right.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "justify", is expected to full-justify text within itself, as if it had its 'text-align' property set to 'justify' in a presentational hint, and to align descendants to the left.

15.3.4 Phrasing content

@namespace "http://www.w3.org/1999/xhtml";

cite, dfn, em, i, var { font-style: italic; }
b, strong { font-weight: bolder; }
code, kbd, samp, tt { font-family: monospace; }
big { font-size: larger; }
small { font-size: smaller; }

sub { vertical-align: sub; }
sup { vertical-align: super; }
sub, sup { line-height: normal; font-size: smaller; }

ruby { display: ruby; }
rt { display: ruby-text; }

:link { color: #0000EE; }
:visited { color: #551A8B; }
:link:active, :visited:active { color: #FF0000; }
:link, :visited { text-decoration: underline; cursor: pointer; }

:focus-visible { outline: auto; }

mark { background: yellow; color: black; } /* this color is just a suggestion and can be changed based on implementation feedback */

abbr[title], acronym[title] { text-decoration: dotted underline; }
ins, u { text-decoration: underline; }
del, s, strike { text-decoration: line-through; }

q::before { content: open-quote; }
q::after { content: close-quote; }

br { display-outside: newline; } /* this also has bidi implications */
nobr { white-space: nowrap; }
wbr { display-outside: break-opportunity; } /* this also has bidi implications */
nobr wbr { white-space: normal; }

The following rules are also expected to apply, as presentational hints:

@namespace "http://www.w3.org/1999/xhtml";

br[clear=left i] { clear: left; }
br[clear=right i] { clear: right; }
br[clear=all i], br[clear=both i] { clear: both; }

For the purposes of the CSS ruby model, runs of children of ruby elements that are not rt or rp elements are expected to be wrapped in anonymous boxes whose 'display' property has the value 'ruby-base'. [CSSRUBY]

When a particular part of a ruby has more than one annotation, the annotations should be distributed on both sides of the base text so as to minimize the stacking of ruby annotations on one side.

When it becomes possible to do so, the preceding requirement will be updated to be expressed in terms of CSS ruby. (Currently, CSS ruby does not handle nested ruby elements or multiple sequential rt elements, which is how this semantic is expressed.)

User agents that do not support correct ruby rendering are expected to render parentheses around the text of rt elements in the absence of rp elements.


User agents are expected to support the 'clear' property on inline elements (in order to render br elements with clear attributes) in the manner described in the non-normative note to this effect in CSS.

The initial value for the 'color' property is expected to be black. The initial value for the 'background-color' property is expected to be 'transparent'. The canvas's background is expected to be white.


When a font element has a color attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'color' property to the resulting color.

When a font element has a face attribute, the user agent is expected to treat the attribute as a presentational hint setting the element's 'font-family' property to the attribute's value.

When a font element has a size attribute, the user agent is expected to use the following steps, known as the rules for parsing a legacy font size, to treat the attribute as a presentational hint setting the element's 'font-size' property:

  1. Let input be the attribute's value.

  2. Let position be a pointer into input, initially pointing at the start of the string.

  3. Skip ASCII whitespace within input given position.

  4. If position is past the end of input, there is no presentational hint. Return.

  5. If the character at position is a U+002B PLUS SIGN character (+), then let mode be relative-plus, and advance position to the next character. Otherwise, if the character at position is a U+002D HYPHEN-MINUS character (-), then let mode be relative-minus, and advance position to the next character. Otherwise, let mode be absolute.

  6. Collect a sequence of code points that are ASCII digits from input given position, and let the resulting sequence be digits.

  7. If digits is the empty string, there is no presentational hint. Return.

  8. Interpret digits as a base-ten integer. Let value be the resulting number.

  9. If mode is relative-plus, then increment value by 3. If mode is relative-minus, then let value be the result of subtracting value from 3.

  10. If value is greater than 7, let it be 7.

  11. If value is less than 1, let it be 1.

  12. Set 'font-size' to the keyword corresponding to the value of value according to the following table:

    value 'font-size' keyword
    1 'x-small'
    2 'small'
    3 'medium'
    4 'large'
    5 'x-large'
    6 'xx-large'
    7 'xxx-large'

15.3.5 Bidirectional text

@namespace "http://www.w3.org/1999/xhtml";

[dir]:dir(ltr), bdi:dir(ltr), input[type=tel i]:dir(ltr) { direction: ltr; }
[dir]:dir(rtl), bdi:dir(rtl) { direction: rtl; }

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp, article, aside, h1, h2,
h3, h4, h5, h6, hgroup, nav, section, search, table, caption, colgroup, col,
thead, tbody, tfoot, tr, td, th, dir, dd, dl, dt, menu, ol, ul, li, bdi, output,
[dir=ltr i], [dir=rtl i], [dir=auto i] {
  unicode-bidi: isolate; 
}

bdo, bdo[dir] { unicode-bidi: isolate-override; } 

input[dir=auto i]:is([type=search i], [type=tel i], [type=url i],
[type=email i]), textarea[dir=auto i], pre[dir=auto i] {
  unicode-bidi: plaintext;
}
/* see prose for input elements whose type attribute is in the Text state */

/* the rules setting the 'content' property on br and wbr elements also has bidi implications */

When an input element's dir attribute is in the auto state and its type attribute is in the Text state, then the user agent is expected to act as if it had a user-agent-level style sheet rule setting the 'unicode-bidi' property to 'plaintext'.

Input fields (i.e. textarea elements, and input elements when their type attribute is in the Text, Search, Telephone, URL, or Email state) are expected to present an editing user interface with a directionality that matches the element's 'direction' property.

When the document's character encoding is ISO-8859-8, the following rules are additionally expected to apply, following those above: [ENCODING]

@namespace "http://www.w3.org/1999/xhtml";

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp, article, aside, h1, h2,
h3, h4, h5, h6, hgroup, nav, section, search, table, caption, colgroup, col,
thead, tbody, tfoot, tr, td, th, dir, dd, dl, dt, menu, ol, ul, li, [dir=ltr i],
[dir=rtl i], [dir=auto i], *|* {
  unicode-bidi: bidi-override;
}
input:not([type=submit i]):not([type=reset i]):not([type=button i]),
textarea {
  unicode-bidi: normal;
}

15.3.6 Sections and headings

@namespace "http://www.w3.org/1999/xhtml";

article, aside, h1, h2, h3, h4, h5, h6, hgroup, nav, section {
  display: block;
}

h1 { margin-block: 0.67em; font-size: 2.00em; font-weight: bold; }
h2 { margin-block: 0.83em; font-size: 1.50em; font-weight: bold; }
h3 { margin-block: 1.00em; font-size: 1.17em; font-weight: bold; }
h4 { margin-block: 1.33em; font-size: 1.00em; font-weight: bold; }
h5 { margin-block: 1.67em; font-size: 0.83em; font-weight: bold; }
h6 { margin-block: 2.33em; font-size: 0.67em; font-weight: bold; }

In the following CSS block, x is shorthand for the following selector: :is(article, aside, nav, section)

@namespace "http://www.w3.org/1999/xhtml";

x h1 { margin-block: 0.83em; font-size: 1.50em; }
x x h1 { margin-block: 1.00em; font-size: 1.17em; }
x x x h1 { margin-block: 1.33em; font-size: 1.00em; }
x x x x h1 { margin-block: 1.67em; font-size: 0.83em; }
x x x x x h1 { margin-block: 2.33em; font-size: 0.67em; }

The shorthand is used to keep this block at least mildly readable.

15.3.7 Lists

@namespace "http://www.w3.org/1999/xhtml";

dir, dd, dl, dt, menu, ol, ul { display: block; }
li { display: list-item; text-align: match-parent; }

dir, dl, menu, ol, ul { margin-block: 1em; }

:is(dir, dl, menu, ol, ul) :is(dir, dl, menu, ol, ul) {
  margin-block: 0;
}

dd { margin-inline-start: 40px; }
dir, menu, ol, ul { padding-inline-start: 40px; }

ol, ul, menu { counter-reset: list-item; }
ol { list-style-type: decimal; }

dir, menu, ul {
  list-style-type: disc;
}
:is(dir, menu, ol, ul) :is(dir, menu, ul) {
  list-style-type: circle;
}
:is(dir, menu, ol, ul) :is(dir, menu, ol, ul) :is(dir, menu, ul) {
  list-style-type: square;
}

The following rules are also expected to apply, as presentational hints:

@namespace "http://www.w3.org/1999/xhtml";

ol[type="1"], li[type="1"] { list-style-type: decimal; }
ol[type=a s], li[type=a s] { list-style-type: lower-alpha; }
ol[type=A s], li[type=A s] { list-style-type: upper-alpha; }
ol[type=i s], li[type=i s] { list-style-type: lower-roman; }
ol[type=I s], li[type=I s] { list-style-type: upper-roman; }
ul[type=none i], li[type=none i] { list-style-type: none; }
ul[type=disc i], li[type=disc i] { list-style-type: disc; }
ul[type=circle i], li[type=circle i] { list-style-type: circle; }
ul[type=square i], li[type=square i] { list-style-type: square; }

When rendering li elements, non-CSS user agents are expected to use the ordinal value of the li element to render the counter in the list item marker.

For CSS user agents, some aspects of rendering list items are defined by the CSS Lists specification. Additionally, the following attribute mappings are expected to apply: [CSSLISTS]

When an li element has a value attribute, and parsing that attribute's value using the rules for parsing integers doesn't generate an error, the user agent is expected to use the parsed value value as a presentational hint for the 'counter-set' property of the form list-item value.

When an ol element has a start attribute or a reversed attribute, or both, the user agent is expected to use the following steps to treat the attributes as a presentational hint for the 'counter-reset' property:

  1. Let value be null.

  2. If the element has a start attribute, then set value to the result of parsing the attribute's value using the rules for parsing integers.

  3. If the element has a reversed attribute, then:

    1. If value is an integer, then increment value by 1 and return reversed(list-item) value.

    2. Otherwise, return reversed(list-item).

      Either the start attribute was absent, or parsing its value resulted in an error.

  4. Otherwise:

    1. If value is an integer, then decrement value by 1 and return list-item value.

    2. Otherwise, there is no presentational hint.

15.3.8 Tables

@namespace "http://www.w3.org/1999/xhtml";

table { display: table; }
caption { display: table-caption; }
colgroup, colgroup[hidden] { display: table-column-group; }
col, col[hidden] { display: table-column; }
thead, thead[hidden] { display: table-header-group; }
tbody, tbody[hidden] { display: table-row-group; }
tfoot, tfoot[hidden] { display: table-footer-group; }
tr, tr[hidden] { display: table-row; }
td, th { display: table-cell; }

colgroup[hidden], col[hidden], thead[hidden], tbody[hidden],
tfoot[hidden], tr[hidden] {
  visibility: collapse;
}

table {
  box-sizing: border-box;
  border-spacing: 2px;
  border-collapse: separate;
  text-indent: initial;
}
td, th { padding: 1px; }
th { font-weight: bold; }

caption { text-align: center; }
thead, tbody, tfoot, table > tr { vertical-align: middle; }
tr, td, th { vertical-align: inherit; }

thead, tbody, tfoot, tr { border-color: inherit; }
table[rules=none i], table[rules=groups i], table[rules=rows i],
table[rules=cols i], table[rules=all i], table[frame=void i],
table[frame=above i], table[frame=below i], table[frame=hsides i],
table[frame=lhs i], table[frame=rhs i], table[frame=vsides i],
table[frame=box i], table[frame=border i],
table[rules=none i] > tr > td, table[rules=none i] > tr > th,
table[rules=groups i] > tr > td, table[rules=groups i] > tr > th,
table[rules=rows i] > tr > td, table[rules=rows i] > tr > th,
table[rules=cols i] > tr > td, table[rules=cols i] > tr > th,
table[rules=all i] > tr > td, table[rules=all i] > tr > th,
table[rules=none i] > thead > tr > td, table[rules=none i] > thead > tr > th,
table[rules=groups i] > thead > tr > td, table[rules=groups i] > thead > tr > th,
table[rules=rows i] > thead > tr > td, table[rules=rows i] > thead > tr > th,
table[rules=cols i] > thead > tr > td, table[rules=cols i] > thead > tr > th,
table[rules=all i] > thead > tr > td, table[rules=all i] > thead > tr > th,
table[rules=none i] > tbody > tr > td, table[rules=none i] > tbody > tr > th,
table[rules=groups i] > tbody > tr > td, table[rules=groups i] > tbody > tr > th,
table[rules=rows i] > tbody > tr > td, table[rules=rows i] > tbody > tr > th,
table[rules=cols i] > tbody > tr > td, table[rules=cols i] > tbody > tr > th,
table[rules=all i] > tbody > tr > td, table[rules=all i] > tbody > tr > th,
table[rules=none i] > tfoot > tr > td, table[rules=none i] > tfoot > tr > th,
table[rules=groups i] > tfoot > tr > td, table[rules=groups i] > tfoot > tr > th,
table[rules=rows i] > tfoot > tr > td, table[rules=rows i] > tfoot > tr > th,
table[rules=cols i] > tfoot > tr > td, table[rules=cols i] > tfoot > tr > th,
table[rules=all i] > tfoot > tr > td, table[rules=all i] > tfoot > tr > th {
  border-color: black;
}

The following rules are also expected to apply, as presentational hints:

@namespace "http://www.w3.org/1999/xhtml";

table[align=left i] { float: left; }
table[align=right i] { float: right; }
table[align=center i] { margin-inline: auto; }
thead[align=absmiddle i], tbody[align=absmiddle i], tfoot[align=absmiddle i],
tr[align=absmiddle i], td[align=absmiddle i], th[align=absmiddle i] {
  text-align: center;
}

caption[align=bottom i] { caption-side: bottom; }
p[align=left i], h1[align=left i], h2[align=left i], h3[align=left i],
h4[align=left i], h5[align=left i], h6[align=left i] {
  text-align: left;
}
p[align=right i], h1[align=right i], h2[align=right i], h3[align=right i],
h4[align=right i], h5[align=right i], h6[align=right i] {
  text-align: right;
}
p[align=center i], h1[align=center i], h2[align=center i], h3[align=center i],
h4[align=center i], h5[align=center i], h6[align=center i] {
  text-align: center;
}
p[align=justify i], h1[align=justify i], h2[align=justify i], h3[align=justify i],
h4[align=justify i], h5[align=justify i], h6[align=justify i] {
  text-align: justify;
}
thead[valign=top i], tbody[valign=top i], tfoot[valign=top i],
tr[valign=top i], td[valign=top i], th[valign=top i] {
  vertical-align: top;
}
thead[valign=middle i], tbody[valign=middle i], tfoot[valign=middle i],
tr[valign=middle i], td[valign=middle i], th[valign=middle i] {
  vertical-align: middle;
}
thead[valign=bottom i], tbody[valign=bottom i], tfoot[valign=bottom i],
tr[valign=bottom i], td[valign=bottom i], th[valign=bottom i] {
  vertical-align: bottom;
}
thead[valign=baseline i], tbody[valign=baseline i], tfoot[valign=baseline i],
tr[valign=baseline i], td[valign=baseline i], th[valign=baseline i] {
  vertical-align: baseline;
}

td[nowrap], th[nowrap] { white-space: nowrap; }

table[rules=none i], table[rules=groups i], table[rules=rows i],
table[rules=cols i], table[rules=all i] {
  border-style: hidden;
  border-collapse: collapse;
}
table[border] { border-style: outset; } /* only if border is not equivalent to zero */
table[frame=void i] { border-style: hidden; }
table[frame=above i] { border-style: outset hidden hidden hidden; }
table[frame=below i] { border-style: hidden hidden outset hidden; }
table[frame=hsides i] { border-style: outset hidden outset hidden; }
table[frame=lhs i] { border-style: hidden hidden hidden outset; }
table[frame=rhs i] { border-style: hidden outset hidden hidden; }
table[frame=vsides i] { border-style: hidden outset; }
table[frame=box i], table[frame=border i] { border-style: outset; }

table[border] > tr > td, table[border] > tr > th,
table[border] > thead > tr > td, table[border] > thead > tr > th,
table[border] > tbody > tr > td, table[border] > tbody > tr > th,
table[border] > tfoot > tr > td, table[border] > tfoot > tr > th {
  /* only if border is not equivalent to zero */
  border-width: 1px;
  border-style: inset;
}
table[rules=none i] > tr > td, table[rules=none i] > tr > th,
table[rules=none i] > thead > tr > td, table[rules=none i] > thead > tr > th,
table[rules=none i] > tbody > tr > td, table[rules=none i] > tbody > tr > th,
table[rules=none i] > tfoot > tr > td, table[rules=none i] > tfoot > tr > th,
table[rules=groups i] > tr > td, table[rules=groups i] > tr > th,
table[rules=groups i] > thead > tr > td, table[rules=groups i] > thead > tr > th,
table[rules=groups i] > tbody > tr > td, table[rules=groups i] > tbody > tr > th,
table[rules=groups i] > tfoot > tr > td, table[rules=groups i] > tfoot > tr > th,
table[rules=rows i] > tr > td, table[rules=rows i] > tr > th,
table[rules=rows i] > thead > tr > td, table[rules=rows i] > thead > tr > th,
table[rules=rows i] > tbody > tr > td, table[rules=rows i] > tbody > tr > th,
table[rules=rows i] > tfoot > tr > td, table[rules=rows i] > tfoot > tr > th {
  border-width: 1px;
  border-style: none;
}
table[rules=cols i] > tr > td, table[rules=cols i] > tr > th,
table[rules=cols i] > thead > tr > td, table[rules=cols i] > thead > tr > th,
table[rules=cols i] > tbody > tr > td, table[rules=cols i] > tbody > tr > th,
table[rules=cols i] > tfoot > tr > td, table[rules=cols i] > tfoot > tr > th {
  border-width: 1px;
  border-block-style: none;
  border-inline-style: solid;
}
table[rules=all i] > tr > td, table[rules=all i] > tr > th,
table[rules=all i] > thead > tr > td, table[rules=all i] > thead > tr > th,
table[rules=all i] > tbody > tr > td, table[rules=all i] > tbody > tr > th,
table[rules=all i] > tfoot > tr > td, table[rules=all i] > tfoot > tr > th {
  border-width: 1px;
  border-style: solid;
}

table[rules=groups i] > colgroup {
  border-inline-width: 1px;
  border-inline-style: solid;
}
table[rules=groups i] > thead,
table[rules=groups i] > tbody,
table[rules=groups i] > tfoot {
  border-block-width: 1px;
  border-block-style: solid;
}

table[rules=rows i] > tr, table[rules=rows i] > thead > tr,
table[rules=rows i] > tbody > tr, table[rules=rows i] > tfoot > tr {
  border-block-width: 1px;
  border-block-style: solid;
}

In quirks mode, the following rules are also expected to apply:

@namespace "http://www.w3.org/1999/xhtml";

table {
  font-weight: initial;
  font-style: initial;
  font-variant: initial;
  font-size: initial;
  line-height: initial;
  white-space: initial;
  text-align: initial;
}

For the purposes of the CSS table model, the col element is expected to be treated as if it was present as many times as its span attribute specifies.

For the purposes of the CSS table model, the colgroup element, if it contains no col element, is expected to be treated as if it had as many such children as its span attribute specifies.

For the purposes of the CSS table model, the colspan and rowspan attributes on td and th elements are expected to provide the special knowledge regarding cells spanning rows and columns.

In HTML documents, the following rules are also expected to apply:

@namespace "http://www.w3.org/1999/xhtml";

:is(table, thead, tbody, tfoot, tr) > form { display: none !important; }

The table element's cellspacing attribute maps to the pixel length property 'border-spacing' on the element.

The table element's cellpadding attribute maps to the pixel length properties 'padding-top', 'padding-right', 'padding-bottom', and 'padding-left' of any td and th elements that have corresponding cells in the table corresponding to the table element.

The table element's height attribute maps to the dimension property 'height' on the table element.

The table element's width attribute maps to the dimension property (ignoring zero) 'width' on the table element.

The col element's width attribute maps to the dimension property 'width' on the col element.

The thead, tbody, and tfoot elements' height attribute maps to the dimension property 'height' on the element.

The tr element's height attribute maps to the dimension property 'height' on the tr element.

The td and th elements' height attributes map to the dimension property (ignoring zero) 'height' on the element.

The td and th elements' width attributes map to the dimension property (ignoring zero) 'width' on the element.


The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for either the string "center" or the string "middle", are expected to center text within themselves, as if they had their 'text-align' property set to 'center' in a presentational hint, and to align descendants to the center.

The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "left", are expected to left-align text within themselves, as if they had their 'text-align' property set to 'left' in a presentational hint, and to align descendants to the left.

The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "right", are expected to right-align text within themselves, as if they had their 'text-align' property set to 'right' in a presentational hint, and to align descendants to the right.

The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "justify", are expected to full-justify text within themselves, as if they had their 'text-align' property set to 'justify' in a presentational hint, and to align descendants to the left.

User agents are expected to have a rule in their user agent style sheet that matches th elements that have a parent node whose computed value for the 'text-align' property is its initial value, whose declaration block consists of just a single declaration that sets the 'text-align' property to the value 'center'.


When a table, thead, tbody, tfoot, tr, td, or th element has a background attribute set to a non-empty value, the new value is expected to be encoding-parsed-and-serialized relative to the element's node document, and if that does not return failure, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-image' property to the return value.

When a table, thead, tbody, tfoot, tr, td, or th element has a bgcolor attribute set, the new value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-color' property to the resulting color.

When a table element has a bordercolor attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'border-top-color', 'border-right-color', 'border-bottom-color', and 'border-left-color' properties to the resulting color.


The table element's border attribute maps to the pixel length properties 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width' on the element. If the attribute is present but parsing the attribute's value using the rules for parsing non-negative integers generates an error, a default value of 1px is expected to be used for that property instead.

Rules marked "only if border is not equivalent to zero" in the CSS block above is expected to only be applied if the border attribute mentioned in the selectors for the rule is not only present but, when parsed using the rules for parsing non-negative integers, is also found to have a value other than zero or to generate an error.


In quirks mode, a td element or a th element that has a nowrap attribute but also has a width attribute whose value, when parsed using the rules for parsing nonzero dimension values, is found to be a length (not an error or a number classified as a percentage), is expected to have a presentational hint setting the element's 'white-space' property to 'normal', overriding the rule in the CSS block above that sets it to 'nowrap'.

15.3.9 Margin collapsing quirks

A node is substantial if it is a text node that is not inter-element whitespace, or if it is an element node.

A node is blank if it is an element that contains no substantial nodes.

The elements with default margins are the following elements: blockquote, dir, dl, h1, h2, h3, h4, h5, h6, listing, menu, ol, p, plaintext, pre, ul, xmp

In quirks mode, any element with default margins that is the child of a body, td, or th element and has no substantial previous siblings is expected to have a user-agent level style sheet rule that sets its 'margin-block-start' property to zero.

In quirks mode, any element with default margins that is the child of a body, td, or th element, has no substantial previous siblings, and is blank, is expected to have a user-agent level style sheet rule that sets its 'margin-block-end' property to zero also.

In quirks mode, any element with default margins that is the child of a td or th element, has no substantial following siblings, and is blank, is expected to have a user-agent level style sheet rule that sets its 'margin-block-start' property to zero.

In quirks mode, any p element that is the child of a td or th element and has no substantial following siblings, is expected to have a user-agent level style sheet rule that sets its 'margin-block-end' property to zero.

15.3.10 Form controls

@namespace "http://www.w3.org/1999/xhtml";

input, select, button, textarea {
  letter-spacing: initial;
  word-spacing: initial;
  line-height: initial;
  text-transform: initial;
  text-indent: initial;
  text-shadow: initial;
  appearance: auto;
}

input:not([type=image i], [type=range i], [type=checkbox i], [type=radio i]) {
  overflow: clip !important;
  overflow-clip-margin: 0 !important;
}

input, select, textarea {
  text-align: initial;
}

:autofill {
  field-sizing: fixed !important;
}

input:is([type=reset i], [type=button i], [type=submit i]), button {
  text-align: center;
}

input, button {
  display: inline-block;
}

input[type=hidden i], input[type=file i], input[type=image i] {
  appearance: none;
}

input:is([type=radio i], [type=checkbox i], [type=reset i], [type=button i],
[type=submit i], [type=color i], [type=search i]), select, button {
  box-sizing: border-box;
}

textarea { white-space: pre-wrap; }

In quirks mode, the following rules are also expected to apply:

@namespace "http://www.w3.org/1999/xhtml";

input:not([type=image i]), textarea { box-sizing: border-box; }

Each kind of form control is also described in the Widgets section, which describes the look and feel of the control.

For input elements where the type attribute is not in the Hidden state or the Image Button state, and that are being rendered, are expected to act as follows:

15.3.11 The hr element

@namespace "http://www.w3.org/1999/xhtml";

hr {
  color: gray;
  border-style: inset;
  border-width: 1px;
  margin-block: 0.5em;
  margin-inline: auto;
  overflow: hidden;
}

The following rules are also expected to apply, as presentational hints:

@namespace "http://www.w3.org/1999/xhtml";

hr[align=left i] { margin-left: 0; margin-right: auto; }
hr[align=right i] { margin-left: auto; margin-right: 0; }
hr[align=center i] { margin-left: auto; margin-right: auto; }
hr[color], hr[noshade] { border-style: solid; }

If an hr element has either a color attribute or a noshade attribute, and furthermore also has a size attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the parsed value divided by two as a pixel length for presentational hints for the properties 'border-top-width', 'border-right-width', 'border-bottom-width', and 'border-left-width' on the element.

Otherwise, if an hr element has neither a color attribute nor a noshade attribute, but does have a size attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then: if the parsed value is one, then the user agent is expected to use the attribute as a presentational hint setting the element's 'border-bottom-width' to 0; otherwise, if the parsed value is greater than one, then the user agent is expected to use the parsed value minus two as a pixel length for presentational hints for the 'height' property on the element.

The width attribute on an hr element maps to the dimension property 'width' on the element.

When an hr element has a color attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'color' property to the resulting color.

15.3.12 The fieldset and legend elements

@namespace "http://www.w3.org/1999/xhtml";

fieldset {
  display: block;
  margin-inline: 2px;
  border: groove 2px ThreeDFace;
  padding-block: 0.35em 0.625em;
  padding-inline: 0.75em;
  min-inline-size: min-content;
}

legend {
  padding-inline: 2px;
}

legend[align=left i] {
  justify-self: left;
}

legend[align=center i] {
  justify-self: center;
}

legend[align=right i] {
  justify-self: right;
}

The fieldset element, when it generates a CSS box, is expected to act as follows:

A fieldset element's rendered legend, if any, is expected to act as follows:

A fieldset element's anonymous fieldset content box is expected to act as follows:

fieldset's margin legend padding legend's margin padding anonymous fieldset content box content
The legend is rendered over the top border, and the top border area reserves vertical space for the legend. The fieldset's top margin starts at the top margin edge of the legend. The legend's horizontal margins, or the 'justify-self' property, gives its horizontal position. The anonymous fieldset content box appears below the legend.

15.4 Replaced elements

The following elements can be replaced elements: audio, canvas, embed, iframe, img, input, object, and video.

15.4.1 Embedded content

The embed, iframe, and video elements are expected to be treated as replaced elements.

A canvas element that represents embedded content is expected to be treated as a replaced element; the contents of such elements are the element's bitmap, if any, or else a transparent black bitmap with the same natural dimensions as the element. Other canvas elements are expected to be treated as ordinary elements in the rendering model.

An object element that represents an image, plugin, or its content navigable is expected to be treated as a replaced element. Other object elements are expected to be treated as ordinary elements in the rendering model.

The audio element, when it is exposing a user interface, is expected to be treated as a replaced element about one line high, as wide as is necessary to expose the user agent's user interface features. When an audio element is not exposing a user interface, the user agent is expected to force its 'display' property to compute to 'none', irrespective of CSS rules.

Whether a video element is exposing a user interface is not expected to affect the size of the rendering; controls are expected to be overlaid above the page content without causing any layout changes, and are expected to disappear when the user does not need them.

When a video element represents a poster frame or frame of video, the poster frame or frame of video is expected to be rendered at the largest size that maintains the aspect ratio of that poster frame or frame of video without being taller or wider than the video element itself, and is expected to be centered in the video element.

Any subtitles or captions are expected to be overlaid directly on top of their video element, as defined by the relevant rendering rules; for WebVTT, those are the rules for updating the display of WebVTT text tracks. [WEBVTT]

When the user agent starts exposing a user interface for a video element, the user agent should run the rules for updating the text track rendering of each of the text tracks in the video element's list of text tracks that are showing and whose text track kind is one of subtitles or captions (e.g., for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks). [WEBVTT]

Resizing video and canvas elements does not interrupt video playback or clear the canvas.


The following CSS rules are expected to apply:

@namespace "http://www.w3.org/1999/xhtml";

iframe { border: 2px inset; }
video { object-fit: contain; }

15.4.2 Images

User agents are expected to render img elements and input elements whose type attributes are in the Image Button state, according to the first applicable rules from the following list:

If the element represents an image
The user agent is expected to treat the element as a replaced element and render the image according to the rules for doing so defined in CSS.
If the element does not represent an image and either:
The user agent is expected to treat the element as a replaced element whose content is the text that the element represents, if any, optionally alongside an icon indicating that the image is being obtained (if applicable). For input elements, the element is expected to appear button-like to indicate that the element is a button.
If the element is an img element that represents some text and the user agent does not expect this to change
The user agent is expected to treat the element as a non-replaced phrasing element whose content is the text, optionally with an icon indicating that an image is missing, so that the user can request the image be displayed or investigate why it is not rendering. In non-graphical contexts, such an icon should be omitted.
If the element is an img element that represents nothing and the user agent does not expect this to change
The user agent is expected to treat the element as a replaced element whose natural dimensions are 0. (In the absence of further styles, this will cause the element to essentially not be rendered.)
If the element is an input element that does not represent an image and the user agent does not expect this to change
The user agent is expected to treat the element as a replaced element consisting of a button whose content is the element's alternative text. The natural dimensions of the button are expected to be about one line in height and whatever width is necessary to render the text on one line.

The icons mentioned above are expected to be relatively small so as not to disrupt most text but be easily clickable. In a visual environment, for instance, icons could be 16 pixels by 16 pixels square, or 1em by 1em if the images are scalable. In an audio environment, the icon could be a short bleep. The icons are intended to indicate to the user that they can be used to get to whatever options the UA provides for images, and, where appropriate, are expected to provide access to the context menu that would have come up if the user interacted with the actual image.


All animated images with the same absolute URL and the same image data are expected to be rendered synchronized to the same timeline as a group, with the timeline starting at the time of the least recent addition to the group.

In other words, when a second image with the same absolute URL and animated image data is inserted into a document, it jumps to the point in the animation cycle that is currently being displayed by the first image.

When a user agent is to restart the animation for an img element showing an animated image, all animated images with the same absolute URL and the same image data in that img element's node document are expected to restart their animation from the beginning.


The following CSS rules are expected to apply:

@namespace "http://www.w3.org/1999/xhtml";

img:is([sizes="auto" i], [sizes^="auto," i]) {
  contain: size !important;
  contain-intrinsic-size: 300px 150px;
}

The following CSS rules are expected to apply when the Document is in quirks mode:

@namespace "http://www.w3.org/1999/xhtml";

img[align=left i] { margin-right: 3px; }
img[align=right i] { margin-left: 3px; }

15.4.3 Attributes for embedded content and images

The following CSS rules are expected to apply as presentational hints:

@namespace "http://www.w3.org/1999/xhtml";

iframe[frameborder='0'], iframe[frameborder=no i] { border: none; }

embed[align=left i], iframe[align=left i], img[align=left i],
input[type=image i][align=left i], object[align=left i] {
  float: left;
}

embed[align=right i], iframe[align=right i], img[align=right i],
input[type=image i][align=right i], object[align=right i] {
  float: right;
}

embed[align=top i], iframe[align=top i], img[align=top i],
input[type=image i][align=top i], object[align=top i] {
  vertical-align: top;
}

embed[align=baseline i], iframe[align=baseline i], img[align=baseline i],
input[type=image i][align=baseline i], object[align=baseline i] {
  vertical-align: baseline;
}

embed[align=texttop i], iframe[align=texttop i], img[align=texttop i],
input[type=image i][align=texttop i], object[align=texttop i] {
  vertical-align: text-top;
}

embed[align=absmiddle i], iframe[align=absmiddle i], img[align=absmiddle i],
input[type=image i][align=absmiddle i], object[align=absmiddle i],
embed[align=abscenter i], iframe[align=abscenter i], img[align=abscenter i],
input[type=image i][align=abscenter i], object[align=abscenter i] {
  vertical-align: middle;
}

embed[align=bottom i], iframe[align=bottom i], img[align=bottom i],
input[type=image i][align=bottom i], object[align=bottom i] {
  vertical-align: bottom;
}

When an embed, iframe, img, or object element, or an input element whose type attribute is in the Image Button state, has an align attribute whose value is an ASCII case-insensitive match for the string "center" or the string "middle", the user agent is expected to act as if the element's 'vertical-align' property was set to a value that aligns the vertical middle of the element with the parent element's baseline.

The hspace attribute of embed, img, or object elements, and input elements with a type attribute in the Image Button state, maps to the dimension properties 'margin-left' and 'margin-right' on the element.

The vspace attribute of embed, img, or object elements, and input elements with a type attribute in the Image Button state, maps to the dimension properties 'margin-top' and 'margin-bottom' on the element.

When an img element, object element, or input element with a type attribute in the Image Button state has a border attribute whose value, when parsed using the rules for parsing non-negative integers, is found to be a number greater than zero, the user agent is expected to use the parsed value for eight presentational hints: four setting the parsed value as a pixel length for the element's 'border-top-width', 'border-right-width', 'border-bottom-width', and 'border-left-width' properties, and four setting the element's 'border-top-style', 'border-right-style', 'border-bottom-style', and 'border-left-style' properties to the value 'solid'.

The width and height attributes on an img element's dimension attribute source map to the dimension properties 'width' and 'height' on the img element respectively. They similarly map to the aspect-ratio property (using dimension rules) of the img element.

The width and height attributes on embed, iframe, object, and video elements, and input elements with a type attribute in the Image Button state and that either represents an image or that the user expects will eventually represent an image, map to the dimension properties 'width' and 'height' on the element respectively.

The width and height attributes map to the aspect-ratio property (using dimension rules) on img and video elements, and input elements with a type attribute in the Image Button state.

The width and height attributes map to the aspect-ratio property on canvas elements.

15.4.4 Image maps

Shapes on an image map are expected to act, for the purpose of the CSS cascade, as elements independent of the original area element that happen to match the same style rules but inherit from the img or object element.

For the purposes of the rendering, only the 'cursor' property is expected to have any effect on the shape.

Thus, for example, if an area element has a style attribute that sets the 'cursor' property to 'help', then when the user designates that shape, the cursor would change to a Help cursor.

Similarly, if an area element had a CSS rule that set its 'cursor' property to 'inherit' (or if no rule setting the 'cursor' property matched the element at all), the shape's cursor would be inherited from the img or object element of the image map, not from the parent of the area element.

15.5 Widgets

15.5.1 Native appearance

The CSS Basic User Interface specification calls elements that can have a native appearance widgets, and defines whether to use that native appearance depending on the 'appearance' property. That logic, in turn, depends on whether on whether each the element is classified as a devolvable widget or non-devolvable widget. This section defines which elements match these concepts for HTML, what their native appearance is, and any particularity of their devolved state or primitive appearance. [CSSUI]

The following elements can have a native appearance for the purpose of the CSS 'appearance' property.

15.5.2 Writing mode

Several widgets have their rendering controlled by the 'writing-mode' CSS property. For the purposes of those widgets, we have the following definitions.

A horizontal writing mode is when resolving the 'writing-mode' property of the control results in a computed value of 'horizontal-tb'.

A vertical writing mode is when resolving the 'writing-mode' property of the control results in a computed value of either 'vertical-rl', 'vertical-lr', 'sideways-rl' or 'sideways-lr'.

15.5.3 Button layout

When an element uses button layout, it is a devolvable widget, and it's native appearance is that of a button.

Button layout is as follows:

Need to define the expected primitive appearance.

15.5.4 The button element

The button element, when it generates a CSS box, is expected to depict a button and to use button layout whose anonymous button content box's contents (if there is an anonymous button content box) are the child boxes the element's box would otherwise have.

15.5.5 The details and summary elements

@namespace "http://www.w3.org/1999/xhtml";

details, summary {
  display: block;
}
details > summary:first-of-type {
  display: list-item;
  counter-increment: list-item 0;
  list-style: disclosure-closed inside;
}
details[open] > summary:first-of-type {
  list-style-type: disclosure-open;
}

The details element is expected to have an internal shadow tree with three child elements:

  1. The first child element is a slot that is expected to take the details element's first summary element child, if any. This element has a single child summary element called the default summary which has text content that is implementation-defined (and probably locale-specific).

    The summary element that this slot represents is expected to allow the user to request the details be shown or hidden.

  2. The second child element is a slot that is expected to take the details element's remaining descendants, if any. This element has no contents.

    This element is expected to match the '::details-content' pseudo-element.

    This element is expected to have its style attribute set to "display: block; content-visibility: hidden;" when the details element does not have an open attribute. When it does have the open attribute, the style attribute is expected to be set to "display: block;".

    Because the slots are hidden inside a shadow tree, this style attribute is not directly visible to author code. Its impacts, however, are visible. Notably, the choice of content-visibility: hidden instead of, e.g., display: none, impacts the results of various APIs that query layout information.

  3. The third child element is either a link or style element with the following styles for the default summary:

    :host summary {
      display: list-item;
      counter-increment: list-item 0;
      list-style: disclosure-closed inside;
    }
    :host([open]) summary {
      list-style-type: disclosure-open;
    }

    The position of this child element relative to the other two is not observable. This means that implementations might have it in a different order relative to its siblings. Implementations might even associate the style with the shadow tree using a mechanism that is not an element.

The structure of this shadow tree is observable through the ways that the children of the details element and the '::details-content' pseudo-element respond to CSS styles.

15.5.6 The input element as a text entry widget

An input element whose type attribute is in the Text, Telephone, URL, or Email state, is a devolvable widget. Its expected native appearance is to render as an 'inline-block' box depicting a one-line text control.

An input element whose type attribute is in the Search state is a devolvable widget. Its expected native appearance is to render as an 'inline-block' box depicting a one-line text control. If the computed value of the element's 'appearance' property is not 'textfield', it may have a distinct style indicating that it is a search field.

An input element whose type attribute is in the Password state is a devolvable widget. Its expected native appearance is to render as an 'inline-block' box depicting a one-line text control that obscures data entry.

For input elements whose type attribute is in one of the above states, the used value of the 'line-height' property must be a length value that is no smaller than what the used value would be for 'line-height: normal'.

The used value will not be the actual keyword 'normal'. Also, this rule does not affect the computed value.

If these text controls provide a text selection, then, when the user changes the current selection, the user agent is expected to queue an element task on the user interaction task source given the input element to fire an event named select at the element, with the bubbles attribute initialized to true.

An input element whose type attribute is in one of the above states is an element with default preferred size, and user agents are expected to apply the 'field-sizing' CSS property to the element. User agents are expected to determine the inline size of its intrinsic size by the following steps:

  1. If the 'field-sizing' property on the element has a computed value of 'content', the inline size is determined by the text which the element shows. The text is either a value or a short hint specified by the placeholder attribute. User agents may take the text caret size into account in the inline size.

  2. If the element has a size attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, return the value obtained from applying the converting a character width to pixels algorithm to the value of the attribute.

  3. Otherwise, return the value obtained from applying the converting a character width to pixels algorithm to the number 20.

The converting a character width to pixels algorithm returns (size-1)×avg + max, where size is the character width to convert, avg is the average character width of the primary font for the element for which the algorithm is being run, in pixels, and max is the maximum character width of that same font, also in pixels. (The element's 'letter-spacing' property does not affect the result.)

These text controls are expected to be scroll containers and support scrolling in the inline axis, but not the block axis.

Need to detail the expected native appearance and primitive appearance.

15.5.7 The input element as domain-specific widgets

An input element whose type attribute is in the Date state is a devolvable widget expected to render as an 'inline-block' box depicting a date control.

An input element whose type attribute is in the Month state is a devolvable widget expected to render as an 'inline-block' box depicting a month control.

An input element whose type attribute is in the Week state is a devolvable widget expected to render as an 'inline-block' box depicting a week control.

An input element whose type attribute is in the Time state is a devolvable widget expected to render as an 'inline-block' box depicting a time control.

An input element whose type attribute is in the Local Date and Time state is a devolvable widget expected to render as an 'inline-block' box depicting a local date and time control.

An input element whose type attribute is in the Number state is a devolvable widget expected to render as an 'inline-block' box depicting a number control.

An input element whose type attribute is in the Number state is an element with default preferred size, and user agents are expected to apply the 'field-sizing' CSS property to the element. The block size of the intrinsic size is about one line high. If the 'field-sizing' property on the element has a computed value of 'content', the inline size of the intrinsic size is expected to be about as wide as necessary to show the current value. Otherwise, the inline size of the intrinsic size is expected to be about as wide as necessary to show the widest possible value.

An input element whose type attribute is in the Date, Month, Week, Time, or Local Date and Time state, is expected to be about one line high, and about as wide as necessary to show the widest possible value.

Need to detail the expected native appearance and primitive appearance.

15.5.8 The input element as a range control

An input element whose type attribute is in the Range state is a non-devolvable widget. Its expected native appearance is to render as an 'inline-block' box depicting a slider control.

When this control has a horizontal writing mode, the control is expected to be a horizontal slider. Its lowest value is on the right if the 'direction' property has a computed value of 'rtl', and on the left otherwise. When this control has a vertical writing mode, it is expected to be a vertical slider. Its lowest value is on the bottom if the 'direction' property has a computed value of 'rtl', and on the top otherwise.

Predefined suggested values (provided by the list attribute) are expected to be shown as tick marks on the slider, which the slider can snap to.

Need to detail the expected primitive appearance.

15.5.9 The input element as a color well

An input element whose type attribute is in the Color state is expected to depict a color well, which, when activated, provides the user with a color picker (e.g. a color wheel or color palette) from which the color can be changed. The element, when it generates a CSS box, is expected to use button layout, that has no child boxes of the anonymous button content box. The anonymous button content box is expected to have a presentational hint setting the 'background-color' property to the element's value.

Predefined suggested values (provided by the list attribute) are expected to be shown in the color picker interface, not on the color well itself.

Need to detail the expected native appearance and primitive appearance.

15.5.10 The input element as a checkbox and radio button widgets

An input element whose type attribute is in the Checkbox state is a non-devolvable widget expected to render as an 'inline-block' box containing a single checkbox control, with no label.

Need to detail the expected native appearance and primitive appearance.

An input element whose type attribute is in the Radio Button state is a non-devolvable widget expected to render as an 'inline-block' box containing a single radio button control, with no label.

Need to detail the expected native appearance and primitive appearance.

15.5.11 The input element as a file upload control

An input element whose type attribute is in the File Upload state, when it generates a CSS box, is expected to render as an 'inline-block' box containing a span of text giving the filename(s) of the selected files, if any, followed by a button that, when activated, provides the user with a file picker from which the selection can be changed. The button is expected to use button layout and match the '::file-selector-button' pseudo-element. The contents of its anonymous button content box are expected to be implementation-defined (and possibly locale-specific) text, for example "Choose file".

User agents may handle an input element whose type attribute is in the File Upload state as an element with default preferred size, and user agents may apply the 'field-sizing' CSS property to the element. If the 'field-sizing' property on the element has a computed value of 'content', the intrinsic size of the element is expected to depend on its content such as the '::file-selector-button' pseudo-element and chosen file names.

15.5.12 The input element as a button

An input element whose type attribute is in the Submit Button, Reset Button, or Button state, when it generates a CSS box, is expected to depict a button and use button layout and the contents of the anonymous button content box are expected to be the text of the element's value attribute, if any, or text derived from the element's type attribute in an implementation-defined (and probably locale-specific) fashion, if not.

15.5.13 The marquee element

@namespace "http://www.w3.org/1999/xhtml";

marquee {
  display: inline-block;
  text-align: initial;
  overflow: hidden !important;
}

The marquee element, while turned on, is expected to render in an animated fashion according to its attributes as follows:

If the element's behavior attribute is in the scroll state

Slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins off the start side of the marquee, and ends flush with the inner end side.

For example, if the direction attribute is left (the default), then the contents would start such that their left edge are off the side of the right edge of the marquee's content area, and the contents would then slide up to the point where the left edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to restart the animation.

If the element's behavior attribute is in the slide state

Slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins off the start side of the marquee, and ends off the end side of the marquee.

For example, if the direction attribute is left (the default), then the contents would start such that their left edge are off the side of the right edge of the marquee's content area, and the contents would then slide up to the point where the right edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to restart the animation.

If the element's behavior attribute is in the alternate state

When the marquee current loop index is even (or zero), slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins flush with the start side of the marquee, and ends flush with the end side of the marquee.

When the marquee current loop index is odd, slide the contents of the element in the opposite direction than that described by the direction attribute as defined below, such that it begins flush with the end side of the marquee, and ends flush with the start side of the marquee.

For example, if the direction attribute is left (the default), then the contents would with their right edge flush with the right inner edge of the marquee's content area, and the contents would then slide up to the point where the left edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to continue the animation.

The direction attribute has the meanings described in the following table:

direction attribute state Direction of animation Start edge End edge Opposite direction
left ← Right to left Right Left → Left to Right
right → Left to Right Left Right ← Right to left
up ↑ Up (Bottom to Top) Bottom Top ↓ Down (Top to Bottom)
down ↓ Down (Top to Bottom) Top Bottom ↑ Up (Bottom to Top)

In any case, the animation should proceed such that there is a delay given by the marquee scroll interval between each frame, and such that the content moves at most the distance given by the marquee scroll distance with each frame.

When a marquee element has a bgcolor attribute set, the value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-color' property to the resulting color.

The width and height attributes on a marquee element map to the dimension properties 'width' and 'height' on the element respectively.

The natural height of a marquee element with its direction attribute in the up or down states is 200 CSS pixels.

The vspace attribute of a marquee element maps to the dimension properties 'margin-top' and 'margin-bottom' on the element. The hspace attribute of a marquee element maps to the dimension properties 'margin-left' and 'margin-right' on the element.

15.5.14 The meter element

@namespace "http://www.w3.org/1999/xhtml";

meter { appearance: auto; }

The meter element is a devolvable widget. Its expected native appearance is to render as an 'inline-block' box with a 'block-size' of '1em' and a 'inline-size' of '5em', a 'vertical-align' of '-0.2em', and with its contents depicting a gauge.

When this element has a horizontal writing mode, the depiction is expected to be of a horizontal gauge. Its minimum value is on the right if the 'direction' property has a computed value of 'rtl', and on the left otherwise. When this element has a vertical writing mode, it is expected to depict a vertical gauge. Its minimum value is on the bottom if the 'direction' property has a computed value of 'rtl', and on the top otherwise.

User agents are expected to use a presentation consistent with platform conventions for gauges, if any.

Requirements for what must be depicted in the gauge are included in the definition of the meter element.

Need to detail the expected primitive appearance.

15.5.15 The progress element

@namespace "http://www.w3.org/1999/xhtml";

progress { appearance: auto; }

The progress element is a devolvable widget. Its expected native appearance is to render as an 'inline-block' box with a 'block-size' of '1em' and a 'inline-size' of '10em', and a 'vertical-align' of '-0.2em'.

When the this element has a horizontal writing mode, the element is expected to be depicted as a horizontal progress bar. The start is on the right and the end is on the left if the 'direction' property on this element has a computed value of 'rtl', and with the start on the left and the end on the right otherwise. When this element has a vertical writing mode, it is expected to be depicted as a vertical progress bar. The start is on the bottom and the end is on the top if the 'direction' property on this element has a computed value of 'rtl', and with the start on the top and the end on the bottom otherwise.

User agents are expected to use a presentation consistent with platform conventions for progress bars. In particular, user agents are expected to use different presentations for determinate and indeterminate progress bars. User agents are also expected to vary the presentation based on the dimensions of the element.

Requirements for how to determine if the progress bar is determinate or indeterminate, and what progress a determinate progress bar is to show, are included in the definition of the progress element.

Need to detail the expected primitive appearance.

15.5.16 The select element

The select element is an element with default preferred size, and user agents are expected to apply the 'field-sizing' CSS property to select elements.

A select element is either a list box or a drop-down box, depending on its attributes.

A select element whose multiple attribute is present is expected to render as a multi-select list box.

A select element whose multiple attribute is absent, and whose display size is greater than 1, is expected to render as a single-select list box.

When the element renders as a list box, it is a devolvable widget expected to render as an 'inline-block' box. The inline size of its intrinsic size is the width of the select's labels plus the width of a scrollbar. The block size of its intrinsic size is determined by the following steps:

  1. If the 'field-sizing' property on the element has a computed value of 'content', return the height necessary to contain all rows for items.

  2. If the size attribute is absent or it has no valid value, return the height necessary to contain four rows.

  3. Otherwise, return the height necessary to contain as many rows for items as given by the element's display size.

A select element whose multiple attribute is absent, and whose display size is 1, is expected to render as an 'inline-block' one-line drop-down box. The inline size of its intrinsic size is the width of the select's labels. If the 'field-sizing' property on the element has a computed value of 'content', the inline size of the intrinsic size depends on the shown text. The shown text is typically the label of an option of which selectedness is set to true.

When the element renders as a drop-down box, it is a devolvable widget. Its appearance in the devolved state, as well as its appearance when the computed value of the element's 'appearance' property is 'menulist-button', is that of a drop-down box, including a "drop-down button", but not necessarily rendered using a native control of the host operating system. In such a state, CSS properties such as 'color', 'background-color', and 'border' should not be disregarded (as is generally permissible when rendering an element according to its native appearance).

In either case (list box or drop-down box), the element's items are expected to be the element's list of options, with the element's optgroup element children providing headers for groups of options where applicable.

An optgroup element is expected to be rendered by displaying the element's label attribute.

An option element is expected to be rendered by displaying the element's label, indented under its optgroup element if it has one.

Each sequence of one or more child hr element siblings may be rendered as a single separator.

The width of the select's labels is the wider of the width necessary to render the widest optgroup, and the width necessary to render the widest option element in the element's list of options (including its indent, if any).

If a select element contains a placeholder label option, the user agent is expected to render that option in a manner that conveys that it is a label, rather than a valid option of the control. This can include preventing the placeholder label option from being explicitly selected by the user. When the placeholder label option's selectedness is true, the control is expected to be displayed in a fashion that indicates that no valid option is currently selected.

User agents are expected to render the labels in a select in such a manner that any alignment remains consistent whether the label is being displayed as part of the page or in a menu control.

Need to detail the expected native appearance and primitive appearance.

15.5.17 The textarea element

The textarea element is a devolvable widget expected to render as an 'inline-block' box depicting a multiline text control. If this multiline text control provides a selection, then, when the user changes the current selection, the user agent is expected to queue an element task on the user interaction task source given the textarea element to fire an event named select at the element, with the bubbles attribute initialized to true.

The textarea element is an element with default preferred size, and user agents are expected to apply the 'field-sizing' CSS property to textarea elements.

If the 'field-sizing' property on the element has a computed value of 'content', the intrinsic size is determined from the text which the element shows. The text is either a raw value or a short hint specified by the placeholder attribute. User agents may take the text caret size into account in the intrinsic size. Otherwise, its intrinsic size is computed from textarea effective width and textarea effective height (as defined below).

The textarea effective width of a textarea element is size×avg + sbw, where size is the element's character width, avg is the average character width of the primary font of the element, in CSS pixels, and sbw is the width of a scrollbar, in CSS pixels. (The element's 'letter-spacing' property does not affect the result.)

The textarea effective height of a textarea element is the height in CSS pixels of the number of lines specified the element's character height, plus the height of a scrollbar in CSS pixels.

User agents are expected to apply the 'white-space' CSS property to textarea elements. For historical reasons, if the element has a wrap attribute whose value is an ASCII case-insensitive match for the string "off", then the user agent is expected to treat the attribute as a presentational hint setting the element's 'white-space' property to 'pre'.

Need to detail the expected native appearance and primitive appearance.

15.6 Frames and framesets

User agents are expected to render frameset elements as a box with the height and width of the viewport, with a surface rendered according to the following layout algorithm:

  1. The cols and rows variables are lists of zero or more pairs consisting of a number and a unit, the unit being one of percentage, relative, and absolute.

    Use the rules for parsing a list of dimensions to parse the value of the element's cols attribute, if there is one. Let cols be the result, or an empty list if there is no such attribute.

    Use the rules for parsing a list of dimensions to parse the value of the element's rows attribute, if there is one. Let rows be the result, or an empty list if there is no such attribute.

  2. For any of the entries in cols or rows that have the number zero and the unit relative, change the entry's number to one.

  3. If cols has no entries, then add a single entry consisting of the value 1 and the unit relative to cols.

    If rows has no entries, then add a single entry consisting of the value 1 and the unit relative to rows.

  4. Invoke the algorithm defined below to convert a list of dimensions to a list of pixel values using cols as the input list, and the width of the surface that the frameset is being rendered into, in CSS pixels, as the input dimension. Let sized cols be the resulting list.

    Invoke the algorithm defined below to convert a list of dimensions to a list of pixel values using rows as the input list, and the height of the surface that the frameset is being rendered into, in CSS pixels, as the input dimension. Let sized rows be the resulting list.

  5. Split the surface into a grid of w×h rectangles, where w is the number of entries in sized cols and h is the number of entries in sized rows.

    Size the columns so that each column in the grid is as many CSS pixels wide as the corresponding entry in the sized cols list.

    Size the rows so that each row in the grid is as many CSS pixels high as the corresponding entry in the sized rows list.

  6. Let children be the list of frame and frameset elements that are children of the frameset element for which the algorithm was invoked.

  7. For each row of the grid of rectangles created in the previous step, from top to bottom, run these substeps:

    1. For each rectangle in the row, from left to right, run these substeps:

      1. If there are any elements left in children, take the first element in the list, and assign it to the rectangle.

        If this is a frameset element, then recurse the entire frameset layout algorithm for that frameset element, with the rectangle as the surface.

        Otherwise, it is a frame element; render its content navigable, positioned and sized to fit the rectangle.

      2. If there are any elements left in children, remove the first element from children.

  8. If the frameset element has a border, draw an outer set of borders around the rectangles, using the element's frame border color.

    For each rectangle, if there is an element assigned to that rectangle, and that element has a border, draw an inner set of borders around that rectangle, using the element's frame border color.

    For each (visible) border that does not abut a rectangle that is assigned a frame element with a noresize attribute (including rectangles in further nested frameset elements), the user agent is expected to allow the user to move the border, resizing the rectangles within, keeping the proportions of any nested frameset grids.

    A frameset or frame element has a border if the following algorithm returns true:

    1. If the element has a frameborder attribute whose value is not the empty string and whose first character is either a U+0031 DIGIT ONE (1) character, a U+0079 LATIN SMALL LETTER Y character (y), or a U+0059 LATIN CAPITAL LETTER Y character (Y), then return true.

    2. Otherwise, if the element has a frameborder attribute, return false.

    3. Otherwise, if the element has a parent element that is a frameset element, then return true if that element has a border, and false if it does not.

    4. Otherwise, return true.

    The frame border color of a frameset or frame element is the color obtained from the following algorithm:

    1. If the element has a bordercolor attribute, and applying the rules for parsing a legacy color value to that attribute's value does not result in an error, then return the color so obtained.

    2. Otherwise, if the element has a parent element that is a frameset element, then return the frame border color of that element.

    3. Otherwise, return gray.

The algorithm to convert a list of dimensions to a list of pixel values consists of the following steps:

  1. Let input list be the list of numbers and units passed to the algorithm.

    Let output list be a list of numbers the same length as input list, all zero.

    Entries in output list correspond to the entries in input list that have the same position.

  2. Let input dimension be the size passed to the algorithm.

  3. Let count percentage be the number of entries in input list whose unit is percentage.

    Let total percentage be the sum of all the numbers in input list whose unit is percentage.

    Let count relative be the number of entries in input list whose unit is relative.

    Let total relative be the sum of all the numbers in input list whose unit is relative.

    Let count absolute be the number of entries in input list whose unit is absolute.

    Let total absolute be the sum of all the numbers in input list whose unit is absolute.

    Let remaining space be the value of input dimension.

  4. If total absolute is greater than remaining space, then for each entry in input list whose unit is absolute, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total absolute. Then, set remaining space to zero.

    Otherwise, for each entry in input list whose unit is absolute, set the corresponding value in output list to the number of the entry in input list. Then, decrement remaining space by total absolute.

  5. If total percentage multiplied by the input dimension and divided by 100 is greater than remaining space, then for each entry in input list whose unit is percentage, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total percentage. Then, set remaining space to zero.

    Otherwise, for each entry in input list whose unit is percentage, set the corresponding value in output list to the number of the entry in input list multiplied by the input dimension and divided by 100. Then, decrement remaining space by total percentage multiplied by the input dimension and divided by 100.

  6. For each entry in input list whose unit is relative, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total relative.

  7. Return output list.

User agents working with integer values for frame widths (as opposed to user agents that can lay frames out with subpixel accuracy) are expected to distribute the remainder first to the last entry whose unit is relative, then equally (not proportionally) to each entry whose unit is percentage, then equally (not proportionally) to each entry whose unit is absolute, and finally, failing all else, to the last entry.


The contents of a frame element that does not have a frameset parent are expected to be rendered as transparent black; the user agent is expected to not render its content navigable in this case, and its content navigable is expected to have a viewport with zero width and zero height.

15.7 Interactive media

15.7.1 Links, forms, and navigation

User agents are expected to allow the user to control aspects of hyperlink activation and form submission, such as which navigable is to be used for the subsequent navigation.

User agents are expected to allow users to discover the destination of hyperlinks and of forms before triggering their navigation.

User agents are expected to inform the user of whether a hyperlink includes hyperlink auditing, and to let them know at a minimum which domains will be contacted as part of such auditing.

User agents may allow users to navigate navigables to the URLs indicated by the cite attributes on q, blockquote, ins, and del elements.

User agents may surface hyperlinks created by link elements in their user interface, as discussed previously.

15.7.2 The title attribute

User agents are expected to expose the advisory information of elements upon user request, and to make the user aware of the presence of such information.

On interactive graphical systems where the user can use a pointing device, this could take the form of a tooltip. When the user is unable to use a pointing device, then the user agent is expected to make the content available in some other fashion, e.g. by making the element a focusable area and always displaying the advisory information of the currently focused element, or by showing the advisory information of the elements under the user's finger on a touch device as the user pans around the screen.

U+000A LINE FEED (LF) characters are expected to cause line breaks in the tooltip; U+0009 CHARACTER TABULATION (tab) characters are expected to render as a nonzero horizontal shift that lines up the next glyph with the next tab stop, with tab stops occurring at points that are multiples of 8 times the width of a U+0020 SPACE character.

For example, a visual user agent could make elements with a title attribute focusable, and could make any focused element with a title attribute show its tooltip under the element while the element has focus. This would allow a user to tab around the document to find all the advisory text.

As another example, a screen reader could provide an audio cue when reading an element with a tooltip, with an associated key to read the last tooltip for which a cue was played.

15.7.3 Editing hosts

The current text editing caret (i.e. the active range, if it is empty and in an editing host), if any, is expected to act like an inline replaced element with the vertical dimensions of the caret and with zero width for the purposes of the CSS rendering model.

This means that even an empty block can have the caret inside it, and that when the caret is in such an element, it prevents margins from collapsing through the element.

15.7.4 Text rendered in native user interfaces

User agents are expected to honor the Unicode semantics of text that is exposed in user interfaces, for example supporting the bidirectional algorithm in text shown in dialogs, title bars, popup menus, and tooltips. Text from the contents of elements is expected to be rendered in a manner that honors the directionality of the element from which the text was obtained. Text from attributes is expected to be rendered in a manner that honours the directionality of the attribute.

Consider the following markup, which has Hebrew text asking for a programming language, the languages being text for which a left-to-right direction is important given the punctuation in some of their names:

<p dir="rtl" lang="he">
 <label>
  בחר שפת תכנות:
  <select>
   <option dir="ltr">C++</option>
   <option dir="ltr">C#</option>
   <option dir="ltr">FreePascal</option>
   <option dir="ltr">F#</option>
  </select>
 </label>
</p>

If the select element was rendered as a drop down box, a correct rendering would ensure that the punctuation was the same both in the drop down, and in the box showing the current selection.

The directionality of attributes depends on the attribute and on the element's dir attribute, as the following example demonstrates. Consider this markup:

<table>
 <tr>
  <th abbr="(א" dir=ltr>A
  <th abbr="(א" dir=rtl>A
  <th abbr="(א" dir=auto>A
</table>

If the abbr attributes are rendered, e.g. in a tooltip or other user interface, the first will have a left parenthesis (because the direction is 'ltr'), the second will have a right parenthesis (because the direction is 'rtl'), and the third will have a right parenthesis (because the direction is determined from the attribute value to be 'rtl').

However, if instead the attribute was not a directionality-capable attribute, the results would be different:

<table>
 <tr>
  <th data-abbr="(א" dir=ltr>A
  <th data-abbr="(א" dir=rtl>A
  <th data-abbr="(א" dir=auto>A
</table>

In this case, if the user agent were to expose the data-abbr attribute in the user interface (e.g. in a debugging environment), the last case would be rendered with a left parenthesis, because the direction would be determined from the element's contents.

A string provided by a script (e.g. the argument to window.alert()) is expected to be treated as an independent set of one or more bidirectional algorithm paragraphs when displayed, as defined by the bidirectional algorithm, including, for instance, supporting the paragraph-breaking behavior of U+000A LINE FEED (LF) characters. For the purposes of determining the paragraph level of such text in the bidirectional algorithm, this specification does not provide a higher-level override of rules P2 and P3. [BIDI]

When necessary, authors can enforce a particular direction for a given paragraph by starting it with the Unicode U+200E LEFT-TO-RIGHT MARK or U+200F RIGHT-TO-LEFT MARK characters.

Thus, the following script:

alert('\u05DC\u05DE\u05D3 HTML \u05D4\u05D9\u05D5\u05DD!')

...would always result in a message reading "למד LMTH היום!" (not "דמל HTML םויה!"), regardless of the language of the user agent interface or the direction of the page or any of its elements.

For a more complex example, consider the following script:

/* Warning: this script does not handle right-to-left scripts correctly */
var s;
if (s = prompt('What is your name?')) {
  alert(s + '! Ok, Fred, ' + s + ', and Wilma will get the car.');
}

When the user enters "Kitty", the user agent would alert "Kitty! Ok, Fred, Kitty, and Wilma will get the car.". However, if the user enters "لا أفهم", then the bidirectional algorithm will determine that the direction of the paragraph is right-to-left, and so the output will be the following unintended mess: "لا أفهم! derF ,kO, لا أفهم, rac eht teg lliw amliW dna."

To force an alert that starts with user-provided text (or other text of unknown directionality) to render left-to-right, the string can be prefixed with a U+200E LEFT-TO-RIGHT MARK character:

var s;
if (s = prompt('What is your name?')) {
  alert('\u200E' + s + '! Ok, Fred, ' + s + ', and Wilma will get the car.');
}

User agents are expected to allow the user to request the opportunity to obtain a physical form (or a representation of a physical form) of a Document. For example, selecting the option to print a page or convert it to PDF format. [PDF]

When the user actually obtains a physical form (or a representation of a physical form) of a Document, the user agent is expected to create a new rendering of the Document for the print media.

15.9 Unstyled XML documents

HTML user agents may, in certain circumstances, find themselves rendering non-HTML documents that use vocabularies for which they lack any built-in knowledge. This section provides for a way for user agents to handle such documents in a somewhat useful manner.

While a Document is an unstyled document, the user agent is expected to render an unstyled document view.

A Document is an unstyled document while it matches the following conditions:

An unstyled document view is one where the DOM is not rendered according to CSS (which would, since there are no applicable styles in this context, just result in a wall of text), but is instead rendered in a manner that is useful for a developer. This could consist of just showing the Document object's source, maybe with syntax highlighting, or it could consist of displaying just the DOM tree, or simply a message saying that the page is not a styled document.

If a Document stops being an unstyled document, then the conditions above stop applying, and thus a user agent following these requirements will switch to using the regular CSS rendering.

16 Obsolete features

16.1 Obsolete but conforming features

Features listed in this section will trigger warnings in conformance checkers.

Authors should not specify a border attribute on an img element. If the attribute is present, its value must be the string "0". CSS should be used instead.

Authors should not specify a charset attribute on a script element. If the attribute is present, its value must be an ASCII case-insensitive match for "utf-8". (This has no effect in a document that conforms to the requirements elsewhere in this standard of being encoded as UTF-8.)

Authors should not specify a language attribute on a script element. If the attribute is present, its value must be an ASCII case-insensitive match for the string "JavaScript" and either the type attribute must be omitted or its value must be an ASCII case-insensitive match for the string "text/javascript". The attribute should be entirely omitted instead (with the value "JavaScript", it has no effect), or replaced with use of the type attribute.

Authors should not specify a value for the type attribute on script elements that is the empty string or a JavaScript MIME type essence match. Instead, they should omit the attribute, which has the same effect.

Authors should not specify a type attribute on a style element. If the attribute is present, its value must be an ASCII case-insensitive match for "text/css".

Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's tree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's tree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragments in URLs. The id attribute should be used instead.

Authors should not, but may despite requirements to the contrary elsewhere in this specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes regardless is to help legacy user agents that do not support input elements with type="number" to still render the text control with a useful width.

16.1.1 Warnings for obsolete but conforming features

To ease the transition from HTML4 Transitional documents to the language defined in this specification, and to discourage certain features that are only allowed in very few circumstances, conformance checkers must warn the user when the following features are used in a document. These are generally old obsolete features that have no effect, and are allowed only to distinguish between likely mistakes (regular conformance errors) and mere vestigial markup or unusual and discouraged practices (these warnings).

The following features must be categorized as described above:

Conformance checkers must distinguish between pages that have no conformance errors and have none of these obsolete features, and pages that have no conformance errors but do have some of these obsolete features.

For example, a validator could report some pages as "Valid HTML" and others as "Valid HTML with warnings".

16.2 Non-conforming features

Elements in the following list are entirely obsolete, and must not be used by authors:

applet

Use embed or object instead.

acronym

Use abbr instead.

bgsound

Use audio instead.

dir

Use ul instead.

frame
frameset
noframes

Either use iframe and CSS instead, or use server-side includes to generate complete pages with the various invariant parts merged in.

isindex

Use an explicit form and text control combination instead.

keygen

For enterprise device management use cases, use native on-device management capabilities.

For certificate enrollment use cases, use the Web Cryptography API to generate a keypair for the certificate, and then export the certificate and key to allow the user to install them manually. [WEBCRYPTO]

listing

Use pre and code instead.

menuitem

To implement a custom context menu, use script to handle the contextmenu event.

nextid

Use GUIDs instead.

noembed

Use object instead of embed when fallback is necessary.

param

Use the data attribute of the object element to set the URL of the external resource.

plaintext

Use the "text/plain" MIME type instead.

rb
rtc

Providing the ruby base directly inside the ruby element or using nested ruby elements is sufficient.

strike

Use del instead if the element is marking an edit, otherwise use s instead.

xmp

Use pre and code instead, and escape "<" and "&" characters as "&lt;" and "&amp;" respectively.

basefont
big
blink
center
font
marquee
multicol
nobr
spacer
tt

Use appropriate elements or CSS instead.

Where the tt element would have been used for marking up keyboard input, consider the kbd element; for variables, consider the var element; for computer code, consider the code element; and for computer output, consider the samp element.

Similarly, if the big element is being used to denote a heading, consider using the h1 element; if it is being used for marking up important passages, consider the strong element; and if it is being used for highlighting text for reference purposes, consider the mark element.

See also the text-level semantics usage summary for more suggestions with examples.


The following attributes are obsolete (though the elements are still part of the language), and must not be used by authors:

charset on a elements
charset on link elements

Use an HTTP `Content-Type` header on the linked resource instead.

charset on script elements (except as noted in the previous section)

Omit the attribute. Both documents and scripts are required to use UTF-8, so it is redundant to specify it on the script element since it inherits from the document.

coords on a elements
shape on a elements

Use area instead of a for image maps.

methods on a elements
methods on link elements

Use the HTTP OPTIONS feature instead.

name on a elements (except as noted in the previous section)
name on embed elements
name on img elements
name on option elements

Use the id attribute instead.

rev on a elements
rev on link elements

Use the rel attribute instead, with an opposite term. (For example, instead of rev="made", use rel="author".)

urn on a elements
urn on link elements

Specify the preferred persistent identifier using the href attribute instead.

accept on form elements

Use the accept attribute directly on the input elements instead.

hreflang on area elements
type on area elements

These attributes do not do anything useful, and for historical reasons there are no corresponding IDL attributes on area elements. Omit them altogether.

nohref on area elements

Omitting the href attribute is sufficient; the nohref attribute is unnecessary. Omit it altogether.

profile on head elements

Unnecessary. Omit it altogether.

manifest on html elements

Use service workers instead. [SW]

version on html elements

Unnecessary. Omit it altogether.

ismap on input elements

Unnecessary. Omit it altogether. All input elements with a type attribute in the Image Button state are processed as server-side image maps.

usemap on input elements
usemap on object elements

Use the img element for image maps.

longdesc on iframe elements
longdesc on img elements

Use a regular a element to link to the description, or (in the case of images) use an image map to provide a link from the image to the image's description.

lowsrc on img elements

Use a progressive JPEG image (given in the src attribute), instead of using two separate images.

target on link elements

Unnecessary. Omit it altogether.

type on menu elements

To implement a custom context menu, use script to handle the contextmenu event. For toolbar menus, omit the attribute.

label on menu elements
contextmenu on all elements
onshow on all elements

To implement a custom context menu, use script to handle the contextmenu event.

scheme on meta elements

Use only one scheme per field, or make the scheme declaration part of the value.

archive on object elements
classid on object elements
code on object elements
codebase on object elements
codetype on object elements

Use the data and type attributes to invoke plugins.

declare on object elements

Repeat the object element completely each time the resource is to be reused.

standby on object elements

Optimize the linked resource so that it loads quickly or, at least, incrementally.

typemustmatch on object elements

Avoid using object elements with untrusted resources.

language on script elements (except as noted in the previous section)

Omit the attribute for JavaScript; for data blocks, use the type attribute instead.

event on script elements
for on script elements

Use DOM events mechanisms to register event listeners. [DOM]

type on style elements (except as noted in the previous section)

Omit the attribute for CSS; for data blocks, use script as the container instead of style.

datapagesize on table elements

Unnecessary. Omit it altogether.

summary on table elements

Use one of the techniques for describing tables given in the table section instead.

abbr on td elements

Use text that begins in an unambiguous and terse manner, and include any more elaborate text after that. The title attribute can also be useful in including more detailed text, so that the cell's contents can be made terse. If it's a heading, use th (which has an abbr attribute).

axis on td and th elements

Use the scope attribute on the relevant th.

scope on td elements

Use th elements for heading cells.

datasrc on a, button, div, frame, iframe, img, input, label, legend, marquee, object, option, select, span, table, and textarea elements
datafld on a, button, div, fieldset, frame, iframe, img, input, label, legend, marquee, object, select, span, and textarea elements
dataformatas on button, div, input, label, legend, marquee, object, option, select, span, and table elements

Use script and a mechanism such as XMLHttpRequest to populate the page dynamically. [XHR]

dropzone on all elements

Use script to handle the dragenter and dragover events instead.

alink on body elements
bgcolor on body elements
bottommargin on body elements
leftmargin on body elements
link on body elements
marginheight on body elements
marginwidth on body elements
rightmargin on body elements
text on body elements
topmargin on body elements
vlink on body elements
clear on br elements
align on caption elements
align on col elements
char on col elements
charoff on col elements
valign on col elements
width on col elements
align on div elements
compact on dl elements
align on embed elements
hspace on embed elements
vspace on embed elements
align on hr elements
color on hr elements
noshade on hr elements
size on hr elements
width on hr elements
align on h1h6 elements
align on iframe elements
allowtransparency on iframe elements
frameborder on iframe elements
framespacing on iframe elements
hspace on iframe elements
marginheight on iframe elements
marginwidth on iframe elements
scrolling on iframe elements
vspace on iframe elements
align on input elements
border on input elements
hspace on input elements
vspace on input elements
align on img elements
border on img elements (except as noted in the previous section)
hspace on img elements
vspace on img elements
align on legend elements
type on li elements
compact on menu elements
align on object elements
border on object elements
hspace on object elements
vspace on object elements
compact on ol elements
align on p elements
width on pre elements
align on table elements
bgcolor on table elements
border on table elements
bordercolor on table elements
cellpadding on table elements
cellspacing on table elements
frame on table elements
height on table elements
rules on table elements
width on table elements
align on tbody, thead, and tfoot elements
char on tbody, thead, and tfoot elements
charoff on tbody, thead, and tfoot elements
height on thead, tbody, and tfoot elements
valign on tbody, thead, and tfoot elements
align on td and th elements
bgcolor on td and th elements
char on td and th elements
charoff on td and th elements
height on td and th elements
nowrap on td and th elements
valign on td and th elements
width on td and th elements
align on tr elements
bgcolor on tr elements
char on tr elements
charoff on tr elements
height on tr elements
valign on tr elements
compact on ul elements
type on ul elements
background on body, table, thead, tbody, tfoot, tr, td, and th elements

Use CSS instead.

16.3 Requirements for implementations

16.3.1 The marquee element

The marquee element is a presentational element that animates content. CSS transitions and animations are a more appropriate mechanism. [CSSANIMATIONS] [CSSTRANSITIONS]

The marquee element must implement the HTMLMarqueeElement interface.

[Exposed=Window]
interface HTMLMarqueeElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString behavior;
  [CEReactions] attribute DOMString bgColor;
  [CEReactions] attribute DOMString direction;
  [CEReactions] attribute DOMString height;
  [CEReactions] attribute unsigned long hspace;
  [CEReactions] attribute long loop;
  [CEReactions] attribute unsigned long scrollAmount;
  [CEReactions] attribute unsigned long scrollDelay;
  [CEReactions] attribute boolean trueSpeed;
  [CEReactions] attribute unsigned long vspace;
  [CEReactions] attribute DOMString width;

  undefined start();
  undefined stop();
};

A marquee element can be turned on or turned off. When it is created, it is turned on.

When the start() method is called, the marquee element must be turned on.

When the stop() method is called, the marquee element must be turned off.


The behavior content attribute on marquee elements is an enumerated attribute with the following keywords and states (all non-conforming):

Keyword State
scroll scroll
slide slide
alternate alternate

The attribute's missing value default and invalid value default are both the scroll state.


The direction content attribute on marquee elements is an enumerated attribute with the following keywords and states (all non-conforming):

Keyword State
left left
right right
up up
down down

The attribute's missing value default and invalid value default are both the left state.


The truespeed content attribute on marquee elements is a boolean attribute.


A marquee element has a marquee scroll interval, which is obtained as follows:

  1. If the element has a scrolldelay attribute, and parsing its value using the rules for parsing non-negative integers does not return an error, then let delay be the parsed value. Otherwise, let delay be 85.

  2. If the element does not have a truespeed attribute, and the delay value is less than 60, then let delay be 60 instead.

  3. The marquee scroll interval is delay, interpreted in milliseconds.


A marquee element has a marquee scroll distance, which, if the element has a scrollamount attribute, and parsing its value using the rules for parsing non-negative integers does not return an error, is the parsed value interpreted in CSS pixels, and otherwise is 6 CSS pixels.


A marquee element has a marquee loop count, which, if the element has a loop attribute, and parsing its value using the rules for parsing integers does not return an error or a number less than 1, is the parsed value, and otherwise is −1.

The loop IDL attribute, on getting, must return the element's marquee loop count; and on setting, if the new value is different than the element's marquee loop count and either greater than zero or equal to −1, must set the element's loop content attribute (adding it if necessary) to the valid integer that represents the new value. (Other values are ignored.)

A marquee element also has a marquee current loop index, which is zero when the element is created.

The rendering layer will occasionally increment the marquee current loop index, which must cause the following steps to be run:

  1. If the marquee loop count is −1, then return.

  2. Increment the marquee current loop index by one.

  3. If the marquee current loop index is now greater than or equal to the element's marquee loop count, turn off the marquee element.


The behavior, direction, height, hspace, vspace, and width IDL attributes must reflect the respective content attributes of the same name.

The bgColor IDL attribute must reflect the bgcolor content attribute.

The scrollAmount IDL attribute must reflect the scrollamount content attribute. The default value is 6.

The scrollDelay IDL attribute must reflect the scrolldelay content attribute. The default value is 85.

The trueSpeed IDL attribute must reflect the truespeed content attribute.

16.3.2 Frames

The frameset element acts as the body element in documents that use frames.

The frameset element must implement the HTMLFrameSetElement interface.

[Exposed=Window]
interface HTMLFrameSetElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString cols;
  [CEReactions] attribute DOMString rows;
};
HTMLFrameSetElement includes WindowEventHandlers;

The cols and rows IDL attributes of the frameset element must reflect the respective content attributes of the same name.

The frameset element exposes as event handler content attributes a number of the event handlers of the Window object. It also mirrors their event handler IDL attributes.

The event handlers of the Window object named by the Window-reflecting body element event handler set, exposed on the frameset element, replace the generic event handlers with the same names normally supported by HTML elements.


The frame element has a content navigable similar to the iframe element, but rendered within a frameset element.

The frame HTML element insertion steps, given insertedNode, are:

  1. If insertedNode is not in a document tree, then return.

  2. If insertedNode's root's browsing context is null, then return.

  3. Create a new child navigable for insertedNode.

  4. Process the frame attributes for insertedNode, with initialInsertion set to true.

The frame HTML element removing steps, given removedNode, are to destroy a child navigable given removedNode.

Whenever a frame element with a non-null content navigable has its src attribute set, changed, or removed, the user agent must process the frame attributes.

To process the frame attributes for an element element, with an optional boolean initialInsertion:

  1. Let url be the result of running the shared attribute processing steps for iframe and frame elements given element and initialInsertion.

  2. If url is null, then return.

  3. If url matches about:blank and initialInsertion is true, then:

    1. Fire an event named load at element.

    2. Return.

  4. Navigate an iframe or frame given element, url, and the empty string.

The frame element potentially delays the load event.

The frame element must implement the HTMLFrameElement interface.

[Exposed=Window]
interface HTMLFrameElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString scrolling;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString frameBorder;
  [CEReactions] attribute USVString longDesc;
  [CEReactions] attribute boolean noResize;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginHeight;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginWidth;
};

The name, scrolling, and src IDL attributes of the frame element must reflect the respective content attributes of the same name. For the purposes of reflection, the frame element's src content attribute is defined as containing a URL.

The frameBorder IDL attribute of the frame element must reflect the element's frameborder content attribute.

The longDesc IDL attribute of the frame element must reflect the element's longdesc content attribute, which for the purposes of reflection is defined as containing a URL.

The noResize IDL attribute of the frame element must reflect the element's noresize content attribute.

The marginHeight IDL attribute of the frame element must reflect the element's marginheight content attribute.

The marginWidth IDL attribute of the frame element must reflect the element's marginwidth content attribute.

The contentDocument getter steps are to return this's content document.

The contentWindow getter steps are to return this's content window.

16.3.3 Other elements, attributes and APIs

User agents must treat acronym elements in a manner equivalent to abbr elements in terms of semantics and for purposes of rendering.


partial interface HTMLAnchorElement {
  [CEReactions] attribute DOMString coords;
  [CEReactions] attribute DOMString charset;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString rev;
  [CEReactions] attribute DOMString shape;
};

The coords, charset, name, rev, and shape IDL attributes of the a element must reflect the respective content attributes of the same name.


partial interface HTMLAreaElement {
  [CEReactions] attribute boolean noHref;
};

The noHref IDL attribute of the area element must reflect the element's nohref content attribute.


partial interface HTMLBodyElement {
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString text;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString link;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString vLink;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString aLink;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
  [CEReactions] attribute DOMString background;
};

The text IDL attribute of the body element must reflect the element's text content attribute.

The link IDL attribute of the body element must reflect the element's link content attribute.

The aLink IDL attribute of the body element must reflect the element's alink content attribute.

The vLink IDL attribute of the body element must reflect the element's vlink content attribute.

The bgColor IDL attribute of the body element must reflect the element's bgcolor content attribute.

The background IDL attribute of the body element must reflect the element's background content attribute. (The background content is not defined to contain a URL, despite rules regarding its handling in the Rendering section above.)


partial interface HTMLBRElement {
  [CEReactions] attribute DOMString clear;
};

The clear IDL attribute of the br element must reflect the content attribute of the same name.


partial interface HTMLTableCaptionElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the caption element must reflect the content attribute of the same name.


partial interface HTMLTableColElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute DOMString vAlign;
  [CEReactions] attribute DOMString width;
};

The align and width IDL attributes of the col element must reflect the respective content attributes of the same name.

The ch IDL attribute of the col element must reflect the element's char content attribute.

The chOff IDL attribute of the col element must reflect the element's charoff content attribute.

The vAlign IDL attribute of the col element must reflect the element's valign content attribute.


User agents must treat dir elements in a manner equivalent to ul elements in terms of semantics and for purposes of rendering.

The dir element must implement the HTMLDirectoryElement interface.

[Exposed=Window]
interface HTMLDirectoryElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the dir element must reflect the content attribute of the same name.


partial interface HTMLDivElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the div element must reflect the content attribute of the same name.


partial interface HTMLDListElement {
  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the dl element must reflect the content attribute of the same name.


partial interface HTMLEmbedElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString name;
};

The name and align IDL attributes of the embed element must reflect the respective content attributes of the same name.


The font element must implement the HTMLFontElement interface.

[Exposed=Window]
interface HTMLFontElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString color;
  [CEReactions] attribute DOMString face;
  [CEReactions] attribute DOMString size; 
};

The color, face, and size IDL attributes of the font element must reflect the respective content attributes of the same name.


partial interface HTMLHeadingElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the h1h6 elements must reflect the content attribute of the same name.


The profile IDL attribute on head elements (with the HTMLHeadElement interface) is intentionally omitted. Unless so required by another applicable specification, implementations would therefore not support this attribute. (It is mentioned here as it was defined in a previous version of DOM.)


partial interface HTMLHRElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString color;
  [CEReactions] attribute boolean noShade;
  [CEReactions] attribute DOMString size;
  [CEReactions] attribute DOMString width;
};

The align, color, size, and width IDL attributes of the hr element must reflect the respective content attributes of the same name.

The noShade IDL attribute of the hr element must reflect the element's noshade content attribute.


partial interface HTMLHtmlElement {
  [CEReactions] attribute DOMString version;
};

The version IDL attribute of the html element must reflect the content attribute of the same name.


partial interface HTMLIFrameElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString scrolling;
  [CEReactions] attribute DOMString frameBorder;
  [CEReactions] attribute USVString longDesc;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginHeight;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginWidth;
};

The align and scrolling IDL attributes of the iframe element must reflect the respective content attributes of the same name.

The frameBorder IDL attribute of the iframe element must reflect the element's frameborder content attribute.

The longDesc IDL attribute of the iframe element must reflect the element's longdesc content attribute, which for the purposes of reflection is defined as containing a URL.

The marginHeight IDL attribute of the iframe element must reflect the element's marginheight content attribute.

The marginWidth IDL attribute of the iframe element must reflect the element's marginwidth content attribute.


partial interface HTMLImageElement {
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute USVString lowsrc;
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute unsigned long hspace;
  [CEReactions] attribute unsigned long vspace;
  [CEReactions] attribute USVString longDesc;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString border;
};

The name, align, border, hspace, and vspace IDL attributes of the img element must reflect the respective content attributes of the same name.

The longDesc IDL attribute of the img element must reflect the element's longdesc content attribute, which for the purposes of reflection is defined as containing a URL.

The lowsrc IDL attribute of the img element must reflect the element's lowsrc content attribute, which for the purposes of reflection is defined as containing a URL.


partial interface HTMLInputElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString useMap;
};

The align IDL attribute of the input element must reflect the content attribute of the same name.

The useMap IDL attribute of the input element must reflect the element's usemap content attribute.


partial interface HTMLLegendElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the legend element must reflect the content attribute of the same name.


partial interface HTMLLIElement {
  [CEReactions] attribute DOMString type;
};

The type IDL attribute of the li element must reflect the content attribute of the same name.


partial interface HTMLLinkElement {
  [CEReactions] attribute DOMString charset;
  [CEReactions] attribute DOMString rev;
  [CEReactions] attribute DOMString target;
};

The charset, rev, and target IDL attributes of the link element must reflect the respective content attributes of the same name.


User agents must treat listing elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering.


partial interface HTMLMenuElement {
  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the menu element must reflect the content attribute of the same name.


partial interface HTMLMetaElement {
  [CEReactions] attribute DOMString scheme;
};

User agents may treat the scheme content attribute on the meta element as an extension of the element's name content attribute when processing a meta element with a name attribute whose value is one that the user agent recognizes as supporting the scheme attribute.

User agents are encouraged to ignore the scheme attribute and instead process the value given to the metadata name as if it had been specified for each expected value of the scheme attribute.

For example, if the user agent acts on meta elements with name attributes having the value "eGMS.subject.keyword", and knows that the scheme attribute is used with this metadata name, then it could take the scheme attribute into account, acting as if it was an extension of the name attribute. Thus the following two meta elements could be treated as two elements giving values for two different metadata names, one consisting of a combination of "eGMS.subject.keyword" and "LGCL", and the other consisting of a combination of "eGMS.subject.keyword" and "ORLY":

<!-- this markup is invalid -->
<meta name="eGMS.subject.keyword" scheme="LGCL" content="Abandoned vehicles">
<meta name="eGMS.subject.keyword" scheme="ORLY" content="Mah car: kthxbye">

The suggested processing of this markup, however, would be equivalent to the following:

<meta name="eGMS.subject.keyword" content="Abandoned vehicles">
<meta name="eGMS.subject.keyword" content="Mah car: kthxbye">

The scheme IDL attribute of the meta element must reflect the content attribute of the same name.


partial interface HTMLObjectElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString archive;
  [CEReactions] attribute DOMString code;
  [CEReactions] attribute boolean declare;
  [CEReactions] attribute unsigned long hspace;
  [CEReactions] attribute DOMString standby;
  [CEReactions] attribute unsigned long vspace;
  [CEReactions] attribute DOMString codeBase;
  [CEReactions] attribute DOMString codeType;
  [CEReactions] attribute DOMString useMap;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString border;
};

The align, archive, border, code, declare, hspace, standby, and vspace IDL attributes of the object element must reflect the respective content attributes of the same name.

The codeBase IDL attribute of the object element must reflect the element's codebase content attribute, which for the purposes of reflection is defined as containing a URL.

The codeType IDL attribute of the object element must reflect the element's codetype content attribute.

HTMLObjectElement/useMap

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

The useMap IDL attribute must reflect the usemap content attribute.


partial interface HTMLOListElement {
  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the ol element must reflect the content attribute of the same name.


partial interface HTMLParagraphElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the p element must reflect the content attribute of the same name.


The param element must implement the HTMLParamElement interface.

[Exposed=Window]
interface HTMLParamElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString value;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString valueType;
};

The name, value, and type IDL attributes of the param element must reflect the respective content attributes of the same name.

The valueType IDL attribute of the param element must reflect the element's valuetype content attribute.


User agents must treat plaintext elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering. (The parser has special behavior for this element, though.)


partial interface HTMLPreElement {
  [CEReactions] attribute long width;
};

The width IDL attribute of the pre element must reflect the content attribute of the same name.


partial interface HTMLStyleElement {
  [CEReactions] attribute DOMString type;
};

The type IDL attribute of the style element must reflect the element's type content attribute.


partial interface HTMLScriptElement {
  [CEReactions] attribute DOMString charset;
  [CEReactions] attribute DOMString event;
  [CEReactions] attribute DOMString htmlFor;
};

The charset and event IDL attributes of the script element must reflect the respective content attributes of the same name.

The htmlFor IDL attribute of the script element must reflect the element's for content attribute.


partial interface HTMLTableElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString border;
  [CEReactions] attribute DOMString frame;
  [CEReactions] attribute DOMString rules;
  [CEReactions] attribute DOMString summary;
  [CEReactions] attribute DOMString width;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString cellPadding;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString cellSpacing;
};

The align, border, frame, summary, rules, and width, IDL attributes of the table element must reflect the respective content attributes of the same name.

The bgColor IDL attribute of the table element must reflect the element's bgcolor content attribute.

The cellPadding IDL attribute of the table element must reflect the element's cellpadding content attribute.

The cellSpacing IDL attribute of the table element must reflect the element's cellspacing content attribute.


partial interface HTMLTableSectionElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute DOMString vAlign;
};

The align IDL attribute of the tbody, thead, and tfoot elements must reflect the content attribute of the same name.

The ch IDL attribute of the tbody, thead, and tfoot elements must reflect the elements' char content attributes.

The chOff IDL attribute of the tbody, thead, and tfoot elements must reflect the elements' charoff content attributes.

The vAlign IDL attribute of the tbody, thead, and tfoot element must reflect the elements' valign content attributes.


partial interface HTMLTableCellElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString axis;
  [CEReactions] attribute DOMString height;
  [CEReactions] attribute DOMString width;

  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute boolean noWrap;
  [CEReactions] attribute DOMString vAlign;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
};

The align, axis, height, and width IDL attributes of the td and th elements must reflect the respective content attributes of the same name.

The ch IDL attribute of the td and th elements must reflect the elements' char content attributes.

The chOff IDL attribute of the td and th elements must reflect the elements' charoff content attributes.

The noWrap IDL attribute of the td and th elements must reflect the elements' nowrap content attributes.

The vAlign IDL attribute of the td and th elements must reflect the elements' valign content attributes.

The bgColor IDL attribute of the td and th elements must reflect the elements' bgcolor content attributes.


partial interface HTMLTableRowElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute DOMString vAlign;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
};

The align IDL attribute of the tr element must reflect the content attribute of the same name.

The ch IDL attribute of the tr element must reflect the element's char content attribute.

The chOff IDL attribute of the tr element must reflect the element's charoff content attribute.

The vAlign IDL attribute of the tr element must reflect the element's valign content attribute.

The bgColor IDL attribute of the tr element must reflect the element's bgcolor content attribute.


partial interface HTMLUListElement {
  [CEReactions] attribute boolean compact;
  [CEReactions] attribute DOMString type;
};

The compact and type IDL attributes of the ul element must reflect the respective content attributes of the same name.


User agents must treat xmp elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering. (The parser has special behavior for this element though.)


partial interface Document {
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString fgColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString linkColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString vlinkColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString alinkColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;

  [SameObject] readonly attribute HTMLCollection anchors;
  [SameObject] readonly attribute HTMLCollection applets;

  undefined clear();
  undefined captureEvents();
  undefined releaseEvents();

  [SameObject] readonly attribute HTMLAllCollection all;
};

The attributes of the Document object listed in the first column of the following table must reflect the content attribute on the body element with the name given in the corresponding cell in the second column on the same row, if the body element is a body element (as opposed to a frameset element). When there is no body element or if it is a frameset element, the attributes must instead return the empty string on getting and do nothing on setting.

IDL attribute Content attribute
fgColor text
linkColor link
vlinkColor vlink
alinkColor alink
bgColor bgcolor

The anchors attribute must return an HTMLCollection rooted at the Document node, whose filter matches only a elements with name attributes.

The applets attribute must return an HTMLCollection rooted at the Document node, whose filter matches nothing. (It exists for historical reasons.)

The clear(), captureEvents(), and releaseEvents() methods must do nothing.


The all attribute must return an HTMLAllCollection rooted at the Document node, whose filter matches all elements.


partial interface Window {
  undefined captureEvents();
  undefined releaseEvents();

  [Replaceable, SameObject] readonly attribute External external;
};

The captureEvents() and releaseEvents() methods must do nothing.

The external attribute of the Window interface must return an instance of the External interface:

[Exposed=Window]
interface External {
  undefined AddSearchProvider();
  undefined IsSearchProviderInstalled();
};

The AddSearchProvider() and IsSearchProviderInstalled() methods must do nothing.

17 IANA considerations

17.1 text/html

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
text
Subtype name:
html
Required parameters:
No required parameters
Optional parameters:
charset

The charset parameter may be provided to specify the document's character encoding, overriding any character encoding declarations in the document other than a Byte Order Mark (BOM). The parameter's value must be an ASCII case-insensitive match for the string "utf-8". [ENCODING]

Encoding considerations:
8bit (see the section on character encoding declarations)
Security considerations:

Entire novels have been written about the security considerations that apply to HTML documents. Many are listed in this document, to which the reader is referred for more details. Some general concerns bear mentioning here, however:

HTML is scripted language, and has a large number of APIs (some of which are described in this document). Script can expose the user to potential risks of information leakage, credential leakage, cross-site scripting attacks, cross-site request forgeries, and a host of other problems. While the designs in this specification are intended to be safe if implemented correctly, a full implementation is a massive undertaking and, as with any software, user agents are likely to have security bugs.

Even without scripting, there are specific features in HTML which, for historical reasons, are required for broad compatibility with legacy content but that expose the user to unfortunate security problems. In particular, the img element can be used in conjunction with some other features as a way to effect a port scan from the user's location on the Internet. This can expose local network topologies that the attacker would otherwise not be able to determine.

HTML relies on a compartmentalization scheme sometimes known as the same-origin policy. An origin in most cases consists of all the pages served from the same host, on the same port, using the same protocol.

It is critical, therefore, to ensure that any untrusted content that forms part of a site be hosted on a different origin than any sensitive content on that site. Untrusted content can easily spoof any other page on the same origin, read data from that origin, cause scripts in that origin to execute, submit forms to and from that origin even if they are protected from cross-site request forgery attacks by unique tokens, and make use of any third-party resources exposed to or rights granted to that origin.

Interoperability considerations:
Rules for processing both conforming and non-conforming content are defined in this specification.
Published specification:
This document is the relevant specification. Labeling a resource with the text/html type asserts that the resource is an HTML document using the HTML syntax.
Applications that use this media type:
Web browsers, tools for processing web content, HTML authoring tools, search engines, validators.
Additional information:
Magic number(s):
No sequence of bytes can uniquely identify an HTML document. More information on detecting HTML documents is available in MIME Sniffing. [MIMESNIFF]
File extension(s):
"html" and "htm" are commonly, but certainly not exclusively, used as the extension for HTML documents.
Macintosh file type code(s):
TEXT
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
No restrictions apply.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments used with text/html resources either refer to the indicated part of the corresponding Document, or provide state information for in-page scripts.

17.2 multipart/x-mixed-replace

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
multipart
Subtype name:
x-mixed-replace
Required parameters:
Optional parameters:
No optional parameters.
Encoding considerations:
binary
Security considerations:
Subresources of a multipart/x-mixed-replace resource can be of any type, including types with non-trivial security implications such as text/html.
Interoperability considerations:
None.
Published specification:
This specification describes processing rules for web browsers. Conformance requirements for generating resources with this type are the same as for multipart/mixed. [RFC2046]
Applications that use this media type:
This type is intended to be used in resources generated by web servers, for consumption by web browsers.
Additional information:
Magic number(s):
No sequence of bytes can uniquely identify a multipart/x-mixed-replace resource.
File extension(s):
No specific file extensions are recommended for this type.
Macintosh file type code(s):
No specific Macintosh file type codes are recommended for this type.
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
No restrictions apply.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments used with multipart/x-mixed-replace resources apply to each body part as defined by the type used by that body part.

17.3 application/xhtml+xml

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
application
Subtype name:
xhtml+xml
Required parameters:
Same as for application/xml [RFC7303]
Optional parameters:
Same as for application/xml [RFC7303]
Encoding considerations:
Same as for application/xml [RFC7303]
Security considerations:
Same as for application/xml [RFC7303]
Interoperability considerations:
Same as for application/xml [RFC7303]
Published specification:
Labeling a resource with the application/xhtml+xml type asserts that the resource is an XML document that likely has a document element from the HTML namespace. Thus, the relevant specifications are XML, Namespaces in XML, and this specification. [XML] [XMLNS]
Applications that use this media type:
Same as for application/xml [RFC7303]
Additional information:
Magic number(s):
Same as for application/xml [RFC7303]
File extension(s):
"xhtml" and "xht" are sometimes used as extensions for XML resources that have a document element from the HTML namespace.
Macintosh file type code(s):
TEXT
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
No restrictions apply.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments used with application/xhtml+xml resources have the same semantics as with any XML MIME type. [RFC7303]

17.4 text/ping

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
text
Subtype name:
ping
Required parameters:
No parameters
Optional parameters:
charset

The charset parameter may be provided. The parameter's value must be "utf-8". This parameter serves no purpose; it is only allowed for compatibility with legacy servers.

Encoding considerations:
Not applicable.
Security considerations:

If used exclusively in the fashion described in the context of hyperlink auditing, this type introduces no new security concerns.

Interoperability considerations:
Rules applicable to this type are defined in this specification.
Published specification:
This document is the relevant specification.
Applications that use this media type:
Web browsers.
Additional information:
Magic number(s):
text/ping resources always consist of the four bytes 0x50 0x49 0x4E 0x47 (`PING`).
File extension(s):
No specific file extension is recommended for this type.
Macintosh file type code(s):
No specific Macintosh file type codes are recommended for this type.
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
Only intended for use with HTTP POST requests generated as part of a web browser's processing of the ping attribute.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments have no meaning with text/ping resources.

17.5 application/microdata+json

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
application
Subtype name:
microdata+json
Required parameters:
Same as for application/json [JSON]
Optional parameters:
Same as for application/json [JSON]
Encoding considerations:
8bit (always UTF-8)
Security considerations:
Same as for application/json [JSON]
Interoperability considerations:
Same as for application/json [JSON]
Published specification:
Labeling a resource with the application/microdata+json type asserts that the resource is a JSON text that consists of an object with a single entry called "items" consisting of an array of entries, each of which consists of an object with an entry called "id" whose value is a string, an entry called "type" whose value is another string, and an entry called "properties" whose value is an object whose entries each have a value consisting of an array of either objects or strings, the objects being of the same form as the objects in the aforementioned "items" entry. Thus, the relevant specifications are JSON and this specification. [JSON]
Applications that use this media type:

Applications that transfer data intended for use with HTML's microdata feature, especially in the context of drag-and-drop, are the primary application class for this type.

Additional information:
Magic number(s):
Same as for application/json [JSON]
File extension(s):
Same as for application/json [JSON]
Macintosh file type code(s):
Same as for application/json [JSON]
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
No restrictions apply.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments used with application/microdata+json resources have the same semantics as when used with application/json (namely, at the time of writing, no semantics at all). [JSON]

17.6 text/event-stream

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
text
Subtype name:
event-stream
Required parameters:
No parameters
Optional parameters:
charset

The charset parameter may be provided. The parameter's value must be "utf-8". This parameter serves no purpose; it is only allowed for compatibility with legacy servers.

Encoding considerations:
8bit (always UTF-8)
Security considerations:

An event stream from an origin distinct from the origin of the content consuming the event stream can result in information leakage. To avoid this, user agents are required to apply CORS semantics. [FETCH]

Event streams can overwhelm a user agent; a user agent is expected to apply suitable restrictions to avoid depleting local resources because of an overabundance of information from an event stream.

Servers can be overwhelmed if a situation develops in which the server is causing clients to reconnect rapidly. Servers should use a 5xx status code to indicate capacity problems, as this will prevent conforming clients from reconnecting automatically.

Interoperability considerations:
Rules for processing both conforming and non-conforming content are defined in this specification.
Published specification:
This document is the relevant specification.
Applications that use this media type:
Web browsers and tools using web services.
Additional information:
Magic number(s):
No sequence of bytes can uniquely identify an event stream.
File extension(s):
No specific file extensions are recommended for this type.
Macintosh file type code(s):
No specific Macintosh file type codes are recommended for this type.
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
This format is only expected to be used by dynamic open-ended streams served using HTTP or a similar protocol. Finite resources are not expected to be labeled with this type.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments have no meaning with text/event-stream resources.

17.7 web+ scheme prefix

This section describes a convention for use with the IANA URI scheme registry. It does not itself register a specific scheme. [RFC7595]

Scheme name:
Schemes starting with the four characters "web+" followed by one or more letters in the range a-z.
Status:
Permanent
Scheme syntax:
Scheme-specific.
Scheme semantics:
Scheme-specific.
Encoding considerations:
All "web+" schemes should use UTF-8 encodings where relevant.
Applications/protocols that use this scheme name:
Scheme-specific.
Interoperability considerations:
The scheme is expected to be used in the context of web applications.
Security considerations:
Any web page is able to register a handler for all "web+" schemes. As such, these schemes must not be used for features intended to be core platform features (e.g., HTTP). Similarly, such schemes must not store confidential information in their URLs, such as usernames, passwords, personal information, or confidential project names.
Contact:
Ian Hickson <ian@hixie.ch>
Change controller:
Ian Hickson <ian@hixie.ch>
References:
Custom scheme handlers, HTML Living Standard: https://html.spec.whatwg.org/#custom-handlers

Index

The following sections only cover conforming elements and features.

Elements

This section is non-normative.

List of elements
Element Description Categories Parents† Children Attributes Interface
a Hyperlink flow; phrasing*; interactive; palpable phrasing transparent* globals; href; target; download; ping; rel; hreflang; type; referrerpolicy HTMLAnchorElement
abbr Abbreviation flow; phrasing; palpable phrasing phrasing globals HTMLElement
address Contact information for a page or article element flow; palpable flow flow* globals HTMLElement
area Hyperlink or dead area on an image map flow; phrasing phrasing* empty globals; alt; coords; shape; href; target; download; ping; rel; referrerpolicy HTMLAreaElement
article Self-contained syndicatable or reusable composition flow; sectioning; palpable flow flow globals HTMLElement
aside Sidebar for tangentially related content flow; sectioning; palpable flow flow globals HTMLElement
audio Audio player flow; phrasing; embedded; interactive; palpable* phrasing source*; track*; transparent* globals; src; crossorigin; preload; autoplay; loop; muted; controls HTMLAudioElement
b Keywords flow; phrasing; palpable phrasing phrasing globals HTMLElement
base Base URL and default target navigable for hyperlinks and forms metadata head empty globals; href; target HTMLBaseElement
bdi Text directionality isolation flow; phrasing; palpable phrasing phrasing globals HTMLElement
bdo Text directionality formatting flow; phrasing; palpable phrasing phrasing globals HTMLElement
blockquote A section quoted from another source flow; palpable flow flow globals; cite HTMLQuoteElement
body Document body none html flow globals; onafterprint; onbeforeprint; onbeforeunload; onhashchange; onlanguagechange; onmessage; onmessageerror; onoffline; ononline; onpageswap; onpagehide; onpagereveal; onpageshow; onpopstate; onrejectionhandled; onstorage; onunhandledrejection; onunload HTMLBodyElement
br Line break, e.g. in poem or postal address flow; phrasing phrasing empty globals HTMLBRElement
button Button control flow; phrasing; interactive; listed; labelable; submittable; form-associated; palpable phrasing phrasing* globals; disabled; form; formaction; formenctype; formmethod; formnovalidate; formtarget; name; popovertarget; popovertargetaction; type; value HTMLButtonElement
canvas Scriptable bitmap canvas flow; phrasing; embedded; palpable phrasing transparent globals; width; height HTMLCanvasElement
caption Table caption none table flow* globals HTMLTableCaptionElement
cite Title of a work flow; phrasing; palpable phrasing phrasing globals HTMLElement
code Computer code flow; phrasing; palpable phrasing phrasing globals HTMLElement
col Table column none colgroup empty globals; span HTMLTableColElement
colgroup Group of columns in a table none table col*; template* globals; span HTMLTableColElement
data Machine-readable equivalent flow; phrasing; palpable phrasing phrasing globals; value HTMLDataElement
datalist Container for options for combo box control flow; phrasing phrasing phrasing*; option*; script-supporting elements* globals HTMLDataListElement
dd Content for corresponding dt element(s) none dl; div* flow globals HTMLElement
del A removal from the document flow; phrasing*; palpable phrasing transparent globals; cite; datetime HTMLModElement
details Disclosure control for hiding details flow; interactive; palpable flow summary*; flow globals; name; open HTMLDetailsElement
dfn Defining instance flow; phrasing; palpable phrasing phrasing* globals HTMLElement
dialog Dialog box or window flow flow flow globals; open HTMLDialogElement
div Generic flow container, or container for name-value groups in dl elements flow; palpable flow; dl flow globals HTMLDivElement
dl Association list consisting of zero or more name-value groups flow; palpable flow dt*; dd*; div*; script-supporting elements globals HTMLDListElement
dt Legend for corresponding dd element(s) none dl; div* flow* globals HTMLElement
em Stress emphasis flow; phrasing; palpable phrasing phrasing globals HTMLElement
embed Plugin flow; phrasing; embedded; interactive; palpable phrasing empty globals; src; type; width; height; any* HTMLEmbedElement
fieldset Group of form controls flow; listed; form-associated; palpable flow legend*; flow globals; disabled; form; name HTMLFieldSetElement
figcaption Caption for figure none figure flow globals HTMLElement
figure Figure with optional caption flow; palpable flow figcaption*; flow globals HTMLElement
footer Footer for a page or section flow; palpable flow flow* globals HTMLElement
form User-submittable form flow; palpable flow flow* globals; accept-charset; action; autocomplete; enctype; method; name; novalidate; rel; target HTMLFormElement
h1, h2, h3, h4, h5, h6 Heading flow; heading; palpable legend; summary; flow phrasing globals HTMLHeadingElement
head Container for document metadata none html metadata content* globals HTMLHeadElement
header Introductory or navigational aids for a page or section flow; palpable flow flow* globals HTMLElement
hgroup Heading container flow; palpable legend; summary; flow h1; h2; h3; h4; h5; h6; script-supporting elements globals HTMLElement
hr Thematic break flow flow empty globals HTMLHRElement
html Root element none none* head*; body* globals; manifest HTMLHtmlElement
i Alternate voice flow; phrasing; palpable phrasing phrasing globals HTMLElement
iframe Child navigable flow; phrasing; embedded; interactive; palpable phrasing empty globals; src; srcdoc; name; sandbox; allow; allowfullscreen; width; height; referrerpolicy; loading HTMLIFrameElement
img Image flow; phrasing; embedded; interactive*; form-associated; palpable phrasing; picture empty globals; alt; src; srcset; sizes; crossorigin; usemap; ismap; width; height; referrerpolicy; decoding; loading; fetchpriority HTMLImageElement
input Form control flow; phrasing; interactive*; listed; labelable; submittable; resettable; form-associated; palpable* phrasing empty globals; accept; alt; autocomplete; checked; dirname; disabled; form; formaction; formenctype; formmethod; formnovalidate; formtarget; height; list; max; maxlength; min; minlength; multiple; name; pattern; placeholder; popovertarget; popovertargetaction; readonly; required; size; src; step; type; value; width HTMLInputElement
ins An addition to the document flow; phrasing*; palpable phrasing transparent globals; cite; datetime HTMLModElement
kbd User input flow; phrasing; palpable phrasing phrasing globals HTMLElement
label Caption for a form control flow; phrasing; interactive; palpable phrasing phrasing* globals; for HTMLLabelElement
legend Caption for fieldset none fieldset phrasing; heading content globals HTMLLegendElement
li List item none ol; ul; menu* flow globals; value* HTMLLIElement
link Link metadata metadata; flow*; phrasing* head; noscript*; phrasing* empty globals; href; crossorigin; rel; as; media; hreflang; type; sizes; imagesrcset; imagesizes; referrerpolicy; integrity; blocking; color; disabled; fetchpriority HTMLLinkElement
main Container for the dominant contents of the document flow; palpable flow* flow globals HTMLElement
map Image map flow; phrasing*; palpable phrasing transparent; area* globals; name HTMLMapElement
mark Highlight flow; phrasing; palpable phrasing phrasing globals HTMLElement
MathML math MathML root flow; phrasing; embedded; palpable phrasing per [MATHML] per [MATHML] Element
menu Menu of commands flow; palpable* flow li; script-supporting elements globals HTMLMenuElement
meta Text metadata metadata; flow*; phrasing* head; noscript*; phrasing* empty globals; name; http-equiv; content; charset; media HTMLMetaElement
meter Gauge flow; phrasing; labelable; palpable phrasing phrasing* globals; value; min; max; low; high; optimum HTMLMeterElement
nav Section with navigational links flow; sectioning; palpable flow flow globals HTMLElement
noscript Fallback content for script metadata; flow; phrasing head*; phrasing* varies* globals HTMLElement
object Image, child navigable, or plugin flow; phrasing; embedded; interactive*; listed; form-associated; palpable phrasing transparent globals; data; type; name; form; width; height HTMLObjectElement
ol Ordered list flow; palpable* flow li; script-supporting elements globals; reversed; start; type HTMLOListElement
optgroup Group of options in a list box none select option; script-supporting elements globals; disabled; label HTMLOptGroupElement
option Option in a list box or combo box control none select; datalist; optgroup text* globals; disabled; label; selected; value HTMLOptionElement
output Calculated output value flow; phrasing; listed; labelable; resettable; form-associated; palpable phrasing phrasing globals; for; form; name HTMLOutputElement
p Paragraph flow; palpable flow phrasing globals HTMLParagraphElement
picture Image flow; phrasing; embedded; palpable phrasing source*; one img; script-supporting elements globals HTMLPictureElement
pre Block of preformatted text flow; palpable flow phrasing globals HTMLPreElement
progress Progress bar flow; phrasing; labelable; palpable phrasing phrasing* globals; value; max HTMLProgressElement
q Quotation flow; phrasing; palpable phrasing phrasing globals; cite HTMLQuoteElement
rp Parenthesis for ruby annotation text none ruby text globals HTMLElement
rt Ruby annotation text none ruby phrasing globals HTMLElement
ruby Ruby annotation(s) flow; phrasing; palpable phrasing phrasing; rt; rp* globals HTMLElement
s Inaccurate text flow; phrasing; palpable phrasing phrasing globals HTMLElement
samp Computer output flow; phrasing; palpable phrasing phrasing globals HTMLElement
script Embedded script metadata; flow; phrasing; script-supporting head; phrasing; script-supporting script, data, or script documentation* globals; src; type; nomodule; async; defer; crossorigin; integrity; referrerpolicy; blocking; fetchpriority HTMLScriptElement
search Container for search controls flow; palpable flow flow globals HTMLElement
section Generic document or application section flow; sectioning; palpable flow flow globals HTMLElement
select List box control flow; phrasing; interactive; listed; labelable; submittable; resettable; form-associated; palpable phrasing option; optgroup; script-supporting elements globals; autocomplete; disabled; form; multiple; name; required; size HTMLSelectElement
slot Shadow tree slot flow; phrasing phrasing transparent globals; name HTMLSlotElement
small Side comment flow; phrasing; palpable phrasing phrasing globals HTMLElement
source Image source for img or media source for video or audio none picture; video; audio empty globals; type; media; src; srcset; sizes; width; height HTMLSourceElement
span Generic phrasing container flow; phrasing; palpable phrasing phrasing globals HTMLSpanElement
strong Importance flow; phrasing; palpable phrasing phrasing globals HTMLElement
style Embedded styling information metadata head; noscript* text* globals; media; blocking HTMLStyleElement
sub Subscript flow; phrasing; palpable phrasing phrasing globals HTMLElement
summary Caption for details none details phrasing; heading content globals HTMLElement
sup Superscript flow; phrasing; palpable phrasing phrasing globals HTMLElement
SVG svg SVG root flow; phrasing; embedded; palpable phrasing per [SVG] per [SVG] SVGSVGElement
table Table flow; palpable flow caption*; colgroup*; thead*; tbody*; tfoot*; tr*; script-supporting elements globals HTMLTableElement
tbody Group of rows in a table none table tr; script-supporting elements globals HTMLTableSectionElement
td Table cell none tr flow globals; colspan; rowspan; headers HTMLTableCellElement
template Template metadata; flow; phrasing; script-supporting metadata; phrasing; script-supporting; colgroup* empty globals; shadowrootmode; shadowrootdelegatesfocus; shadowrootclonable; shadowrootserializable HTMLTemplateElement
textarea Multiline text controls flow; phrasing; interactive; listed; labelable; submittable; resettable; form-associated; palpable phrasing text globals; autocomplete; cols; dirname; disabled; form; maxlength; minlength; name; placeholder; readonly; required; rows; wrap HTMLTextAreaElement
tfoot Group of footer rows in a table none table tr; script-supporting elements globals HTMLTableSectionElement
th Table header cell interactive* tr flow* globals; colspan; rowspan; headers; scope; abbr HTMLTableCellElement
thead Group of heading rows in a table none table tr; script-supporting elements globals HTMLTableSectionElement
time Machine-readable equivalent of date- or time-related data flow; phrasing; palpable phrasing phrasing globals; datetime HTMLTimeElement
title Document title metadata head text* globals HTMLTitleElement
tr Table row none table; thead; tbody; tfoot th*; td; script-supporting elements globals HTMLTableRowElement
track Timed text track none audio; video empty globals; default; kind; label; src; srclang HTMLTrackElement
u Unarticulated annotation flow; phrasing; palpable phrasing phrasing globals HTMLElement
ul List flow; palpable* flow li; script-supporting elements globals HTMLUListElement
var Variable flow; phrasing; palpable phrasing phrasing globals HTMLElement
video Video player flow; phrasing; embedded; interactive; palpable phrasing source*; track*; transparent* globals; src; crossorigin; poster; preload; autoplay; playsinline; loop; muted; controls; width; height HTMLVideoElement
wbr Line breaking opportunity flow; phrasing phrasing empty globals HTMLElement
autonomous custom elements Author-defined elements flow; phrasing; palpable flow; phrasing transparent globals; any, as decided by the element's author Supplied by the element's author (inherits from HTMLElement)

An asterisk (*) in a cell indicates that the actual rules are more complicated than indicated in the table above.

† Categories in the "Parents" column refer to parents that list the given categories in their content model, not to elements that themselves are in those categories. For example, the a element's "Parents" column says "phrasing", so any element whose content model contains the "phrasing" category could be a parent of an a element. Since the "flow" category includes all the "phrasing" elements, that means the th element could be a parent to an a element.

Element content categories

This section is non-normative.

List of element content categories
Category Elements Elements with exceptions
Metadata content base; link; meta; noscript; script; style; template; title
Flow content a; abbr; address; article; aside; audio; b; bdi; bdo; blockquote; br; button; canvas; cite; code; data; datalist; del; details; dfn; dialog; div; dl; em; embed; fieldset; figure; footer; form; h1; h2; h3; h4; h5; h6; header; hgroup; hr; i; iframe; img; input; ins; kbd; label; map; mark; MathML math; menu; meter; nav; noscript; object; ol; output; p; picture; pre; progress; q; ruby; s; samp; script; search; section; select; slot; small; span; strong; sub; sup; SVG svg; table; template; textarea; time; u; ul; var; video; wbr; autonomous custom elements; Text area (if it is a descendant of a map element); link (if it is allowed in the body); main (if it is a hierarchically correct main element); meta (if the itemprop attribute is present)
Sectioning content article; aside; nav; section
Heading content h1; h2; h3; h4; h5; h6; hgroup
Phrasing content a; abbr; audio; b; bdi; bdo; br; button; canvas; cite; code; data; datalist; del; dfn; em; embed; i; iframe; img; input; ins; kbd; label; map; mark; MathML math; meter; noscript; object; output; picture; progress; q; ruby; s; samp; script; select; slot; small; span; strong; sub; sup; SVG svg; template; textarea; time; u; var; video; wbr; autonomous custom elements; Text area (if it is a descendant of a map element); link (if it is allowed in the body); meta (if the itemprop attribute is present)
Embedded content audio; canvas; embed; iframe; img; MathML math; object; picture; SVG svg; video
Interactive content button; details; embed; iframe; label; select; textarea a (if the href attribute is present); audio (if the controls attribute is present); img (if the usemap attribute is present); input (if the type attribute is not in the Hidden state); video (if the controls attribute is present)
Form-associated elements button; fieldset; input; label; object; output; select; textarea; img; form-associated custom elements
Listed elements button; fieldset; input; object; output; select; textarea; form-associated custom elements
Submittable elements button; input; select; textarea; form-associated custom elements
Resettable elements input; output; select; textarea; form-associated custom elements
Autocapitalize-inheriting elements button; fieldset; input; output; select; textarea
Labelable elements button; input; meter; output; progress; select; textarea; form-associated custom elements
Palpable content a; abbr; address; article; aside; b; bdi; bdo; blockquote; button; canvas; cite; code; data; del; details; dfn; div; em; embed; fieldset; figure; footer; form; h1; h2; h3; h4; h5; h6; header; hgroup; i; iframe; img; ins; kbd; label; main; map; mark; MathML math; meter; nav; object; output; p; picture; pre; progress; q; ruby; s; samp; search; section; select; small; span; strong; sub; sup; SVG svg; table; textarea; time; u; var; video; autonomous custom elements audio (if the controls attribute is present); dl (if the element's children include at least one name-value group); input (if the type attribute is not in the Hidden state); menu (if the element's children include at least one li element); ol (if the element's children include at least one li element); ul (if the element's children include at least one li element); Text that is not inter-element whitespace
Script-supporting elements script; template

Attributes

This section is non-normative.

List of attributes (excluding event handler content attributes)
Attribute Element(s) Description Value
abbr th Alternative label to use for the header cell when referencing the cell in other contexts Text*
accept input Hint for expected file type in file upload controls Set of comma-separated tokens* consisting of valid MIME type strings with no parameters or audio/*, video/*, or image/*
accept-charset form Character encodings to use for form submission ASCII case-insensitive match for "UTF-8"
accesskey HTML elements Keyboard shortcut to activate or focus element Ordered set of unique space-separated tokens, none of which are identical to another, each consisting of one code point in length
action form URL to use for form submission Valid non-empty URL potentially surrounded by spaces
allow iframe Permissions policy to be applied to the iframe's contents Serialized permissions policy
allowfullscreen iframe Whether to allow the iframe's contents to use requestFullscreen() Boolean attribute
alt area; img; input Replacement text for use when images are not available Text*
as link Potential destination for a preload request (for rel="preload" and rel="modulepreload") Potential destination, for rel="preload"; script-like destination, for rel="modulepreload"
async script Execute script when available, without blocking while fetching Boolean attribute
autocapitalize HTML elements Recommended autocapitalization behavior (for supported input methods) "on"; "off"; "none"; "sentences"; "words"; "characters"
autocomplete form Default setting for autofill feature for controls in the form "on"; "off"
autocomplete input; select; textarea Hint for form autofill feature Autofill field name and related tokens*
autofocus HTML elements Automatically focus the element when the page is loaded Boolean attribute
autoplay audio; video Hint that the media resource can be started automatically when the page is loaded Boolean attribute
blocking link; script; style Whether the element is potentially render-blocking Unordered set of unique space-separated tokens*
charset meta Character encoding declaration "utf-8"
checked input Whether the control is checked Boolean attribute
cite blockquote; del; ins; q Link to the source of the quotation or more information about the edit Valid URL potentially surrounded by spaces
class HTML elements Classes to which the element belongs Set of space-separated tokens
color link Color to use when customizing a site's icon (for rel="mask-icon") CSS <color>
cols textarea Maximum number of characters per line Valid non-negative integer greater than zero
colspan td; th Number of columns that the cell is to span Valid non-negative integer greater than zero
content meta Value of the element Text*
contenteditable HTML elements Whether the element is editable "true"; "plaintext-only"; "false"
controls audio; video Show user agent controls Boolean attribute
coords area Coordinates for the shape to be created in an image map Valid list of floating-point numbers*
crossorigin audio; img; link; script; video How the element handles crossorigin requests "anonymous"; "use-credentials"
data object Address of the resource Valid non-empty URL potentially surrounded by spaces
datetime del; ins Date and (optionally) time of the change Valid date string with optional time
datetime time Machine-readable value Valid month string, valid date string, valid yearless date string, valid time string, valid local date and time string, valid time-zone offset string, valid global date and time string, valid week string, valid non-negative integer, or valid duration string
decoding img Decoding hint to use when processing this image for presentation "sync"; "async"; "auto"
default track Enable the track if no other text track is more suitable Boolean attribute
defer script Defer script execution Boolean attribute
dir HTML elements The text directionality of the element "ltr"; "rtl"; "auto"
dir bdo The text directionality of the element "ltr"; "rtl"
dirname input; textarea Name of form control to use for sending the element's directionality in form submission Text*
disabled button; input; optgroup; option; select; textarea; form-associated custom elements Whether the form control is disabled Boolean attribute
disabled fieldset Whether the descendant form controls, except any inside legend, are disabled Boolean attribute
disabled link Whether the link is disabled Boolean attribute
download a; area Whether to download the resource instead of navigating to it, and its filename if so Text
draggable HTML elements Whether the element is draggable "true"; "false"
enctype form Entry list encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
enterkeyhint HTML elements Hint for selecting an enter key action "enter"; "done"; "go"; "next"; "previous"; "search"; "send"
fetchpriority img; link; script Sets the priority for fetches initiated by the element "auto"; "high"; "low"
for label Associate the label with form control ID*
for output Specifies controls from which the output was calculated Unordered set of unique space-separated tokens consisting of IDs*
form button; fieldset; input; object; output; select; textarea; form-associated custom elements Associates the element with a form element ID*
formaction button; input URL to use for form submission Valid non-empty URL potentially surrounded by spaces
formenctype button; input Entry list encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
formmethod button; input Variant to use for form submission "GET"; "POST"; "dialog"
formnovalidate button; input Bypass form control validation for form submission Boolean attribute
formtarget button; input Navigable for form submission Valid navigable target name or keyword
headers td; th The header cells for this cell Unordered set of unique space-separated tokens consisting of IDs*
height canvas; embed; iframe; img; input; object; source (in picture); video Vertical dimension Valid non-negative integer
hidden HTML elements Whether the element is relevant "until-found"; "hidden"; the empty string
high meter Low limit of high range Valid floating-point number*
href a; area Address of the hyperlink Valid URL potentially surrounded by spaces
href link Address of the hyperlink Valid non-empty URL potentially surrounded by spaces
href base Document base URL Valid URL potentially surrounded by spaces
hreflang a; link Language of the linked resource Valid BCP 47 language tag
http-equiv meta Pragma directive "content-type"; "default-style"; "refresh"; "x-ua-compatible"; "content-security-policy"
id HTML elements The element's ID Text*
imagesizes link Image sizes for different page layouts (for rel="preload") Valid source size list
imagesrcset link Images to use in different situations, e.g., high-resolution displays, small monitors, etc. (for rel="preload") Comma-separated list of image candidate strings
inert HTML elements Whether the element is inert. Boolean attribute
inputmode HTML elements Hint for selecting an input modality "none"; "text"; "tel"; "email"; "url"; "numeric"; "decimal"; "search"
integrity link; script Integrity metadata used in Subresource Integrity checks [SRI] Text
is HTML elements Creates a customized built-in element Valid custom element name of a defined customized built-in element
ismap img Whether the image is a server-side image map Boolean attribute
itemid HTML elements Global identifier for a microdata item Valid URL potentially surrounded by spaces
itemprop HTML elements Property names of a microdata item Unordered set of unique space-separated tokens consisting of valid absolute URLs, defined property names, or text*
itemref HTML elements Referenced elements Unordered set of unique space-separated tokens consisting of IDs*
itemscope HTML elements Introduces a microdata item Boolean attribute
itemtype HTML elements Item types of a microdata item Unordered set of unique space-separated tokens consisting of valid absolute URLs*
kind track The type of text track "subtitles"; "captions"; "descriptions"; "chapters"; "metadata"
label optgroup; option; track User-visible label Text
lang HTML elements Language of the element Valid BCP 47 language tag or the empty string
list input List of autocomplete options ID*
loading iframe; img Used when determining loading deferral "lazy"; "eager"
loop audio; video Whether to loop the media resource Boolean attribute
low meter High limit of low range Valid floating-point number*
max input Maximum value Varies*
max meter; progress Upper bound of range Valid floating-point number*
maxlength input; textarea Maximum length of value Valid non-negative integer
media link; meta; source; style Applicable media Valid media query list
method form Variant to use for form submission "GET"; "POST"; "dialog"
min input Minimum value Varies*
min meter Lower bound of range Valid floating-point number*
minlength input; textarea Minimum length of value Valid non-negative integer
multiple input; select Whether to allow multiple values Boolean attribute
muted audio; video Whether to mute the media resource by default Boolean attribute
name button; fieldset; input; output; select; textarea; form-associated custom elements Name of the element to use for form submission and in the form.elements API Text*
name details Name of group of mutually-exclusive details elements Text*
name form Name of form to use in the document.forms API Text*
name iframe; object Name of content navigable Valid navigable target name or keyword
name map Name of image map to reference from the usemap attribute Text*
name meta Metadata name Text*
name slot Name of shadow tree slot Text
nomodule script Prevents execution in user agents that support module scripts Boolean attribute
nonce HTML elements Cryptographic nonce used in Content Security Policy checks [CSP] Text
novalidate form Bypass form control validation for form submission Boolean attribute
open details Whether the details are visible Boolean attribute
open dialog Whether the dialog box is showing Boolean attribute
optimum meter Optimum value in gauge Valid floating-point number*
pattern input Pattern to be matched by the form control's value Regular expression matching the JavaScript Pattern production
ping a; area URLs to ping Set of space-separated tokens consisting of valid non-empty URLs
placeholder input; textarea User-visible label to be placed within the form control Text*
playsinline video Encourage the user agent to display video content within the element's playback area Boolean attribute
popover HTML elements Makes the element a popover element "auto"; "manual";
popovertarget button; input Targets a popover element to toggle, show, or hide ID*
popovertargetaction button; input Indicates whether a targeted popover element is to be toggled, shown, or hidden "toggle"; "show"; "hide"
poster video Poster frame to show prior to video playback Valid non-empty URL potentially surrounded by spaces
preload audio; video Hints how much buffering the media resource will likely need "none"; "metadata"; "auto"
readonly input; textarea Whether to allow the value to be edited by the user Boolean attribute
readonly form-associated custom elements Affects willValidate, plus any behavior added by the custom element author Boolean attribute
referrerpolicy a; area; iframe; img; link; script Referrer policy for fetches initiated by the element Referrer policy
rel a; area Relationship between the location in the document containing the hyperlink and the destination resource Unordered set of unique space-separated tokens*
rel link Relationship between the document containing the hyperlink and the destination resource Unordered set of unique space-separated tokens*
required input; select; textarea Whether the control is required for form submission Boolean attribute
reversed ol Number the list backwards Boolean attribute
rows textarea Number of lines to show Valid non-negative integer greater than zero
rowspan td; th Number of rows that the cell is to span Valid non-negative integer
sandbox iframe Security rules for nested content Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of
scope th Specifies which cells the header cell applies to "row"; "col"; "rowgroup"; "colgroup"
selected option Whether the option is selected by default Boolean attribute
shadowrootclonable template Sets clonable on a declarative shadow root Boolean attribute
shadowrootdelegatesfocus template Sets delegates focus on a declarative shadow root Boolean attribute
shadowrootmode template Enables streaming declarative shadow roots "open"; "closed"
shadowrootserializable template Sets serializable on a declarative shadow root Boolean attribute
shape area The kind of shape to be created in an image map "circle"; "default"; "poly"; "rect"
size input; select Size of the control Valid non-negative integer greater than zero
sizes link Sizes of the icons (for rel="icon") Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of sizes*
sizes img; source Image sizes for different page layouts Valid source size list
slot HTML elements The element's desired slot Text
span col; colgroup Number of columns spanned by the element Valid non-negative integer greater than zero
spellcheck HTML elements Whether the element is to have its spelling and grammar checked "true"; "false"; the empty string
src audio; embed; iframe; img; input; script; source (in video or audio); track; video Address of the resource Valid non-empty URL potentially surrounded by spaces
srcdoc iframe A document to render in the iframe The source of an iframe srcdoc document*
srclang track Language of the text track Valid BCP 47 language tag
srcset img; source Images to use in different situations, e.g., high-resolution displays, small monitors, etc. Comma-separated list of image candidate strings
start ol Starting value of the list Valid integer
step input Granularity to be matched by the form control's value Valid floating-point number greater than zero, or "any"
style HTML elements Presentational and formatting instructions CSS declarations*
tabindex HTML elements Whether the element is focusable and sequentially focusable, and the relative order of the element for the purposes of sequential focus navigation Valid integer
target a; area Navigable for hyperlink navigation Valid navigable target name or keyword
target base Default navigable for hyperlink navigation and form submission Valid navigable target name or keyword
target form Navigable for form submission Valid navigable target name or keyword
title HTML elements Advisory information for the element Text
title abbr; dfn Full term or expansion of abbreviation Text
title input Description of pattern (when used with pattern attribute) Text
title link Title of the link Text
title link; style CSS style sheet set name Text
translate HTML elements Whether the element is to be translated when the page is localized "yes"; "no"
type a; link Hint for the type of the referenced resource Valid MIME type string
type button Type of button "submit"; "reset"; "button"
type embed; object; source Type of embedded resource Valid MIME type string
type input Type of form control input type keyword
type ol Kind of list marker "1"; "a"; "A"; "i"; "I"
type script Type of script "module"; a valid MIME type string that is not a JavaScript MIME type essence match
usemap img Name of image map to use Valid hash-name reference*
value button; option Value to be used for form submission Text
value data Machine-readable value Text*
value input Value of the form control Varies*
value li Ordinal value of the list item Valid integer
value meter; progress Current value of the element Valid floating-point number
width canvas; embed; iframe; img; input; object; source (in picture); video Horizontal dimension Valid non-negative integer
wrap textarea How the value of the form control is to be wrapped for form submission "soft"; "hard"
writingsuggestions HTML elements Whether the element can offer writing suggestions or not. "true"; "false"; the empty string

An asterisk (*) in a cell indicates that the actual rules are more complicated than indicated in the table above.


HTMLElement/drag_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

HTMLElement/dragend_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

HTMLElement/dragenter_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

HTMLElement/dragleave_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

HTMLElement/dragover_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

HTMLElement/dragstart_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+

HTMLElement/drop_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12+
List of event handler content attributes
Attribute Element(s) Description Value
onafterprint body afterprint event handler for Window object Event handler content attribute
onauxclick HTML elements auxclick event handler Event handler content attribute
onbeforeinput HTML elements beforeinput event handler Event handler content attribute
onbeforematch HTML elements beforematch event handler Event handler content attribute
onbeforeprint body beforeprint event handler for Window object Event handler content attribute
onbeforeunload body beforeunload event handler for Window object Event handler content attribute
onbeforetoggle HTML elements beforetoggle event handler Event handler content attribute
onblur HTML elements blur event handler Event handler content attribute
oncancel HTML elements cancel event handler Event handler content attribute
oncanplay HTML elements canplay event handler Event handler content attribute
oncanplaythrough HTML elements canplaythrough event handler Event handler content attribute
onchange HTML elements change event handler Event handler content attribute
onclick HTML elements click event handler Event handler content attribute
onclose HTML elements close event handler Event handler content attribute
oncontextlost HTML elements contextlost event handler Event handler content attribute
oncontextmenu HTML elements contextmenu event handler Event handler content attribute
oncontextrestored HTML elements contextrestored event handler Event handler content attribute
oncopy HTML elements copy event handler Event handler content attribute
oncuechange HTML elements cuechange event handler Event handler content attribute
oncut HTML elements cut event handler Event handler content attribute
ondblclick HTML elements dblclick event handler Event handler content attribute
ondrag HTML elements drag event handler Event handler content attribute
ondragend HTML elements dragend event handler Event handler content attribute
ondragenter HTML elements dragenter event handler Event handler content attribute
ondragleave HTML elements dragleave event handler Event handler content attribute
ondragover HTML elements dragover event handler Event handler content attribute
ondragstart HTML elements dragstart event handler Event handler content attribute
ondrop HTML elements drop event handler Event handler content attribute
ondurationchange HTML elements durationchange event handler Event handler content attribute
onemptied HTML elements emptied event handler Event handler content attribute
onended HTML elements ended event handler Event handler content attribute
onerror HTML elements error event handler Event handler content attribute
onfocus HTML elements focus event handler Event handler content attribute
onformdata HTML elements formdata event handler Event handler content attribute
onhashchange body hashchange event handler for Window object Event handler content attribute
oninput HTML elements input event handler Event handler content attribute
oninvalid HTML elements invalid event handler Event handler content attribute
onkeydown HTML elements keydown event handler Event handler content attribute
onkeypress HTML elements keypress event handler Event handler content attribute
onkeyup HTML elements keyup event handler Event handler content attribute
onlanguagechange body languagechange event handler for Window object Event handler content attribute
onload HTML elements load event handler Event handler content attribute
onloadeddata HTML elements loadeddata event handler Event handler content attribute
onloadedmetadata HTML elements loadedmetadata event handler Event handler content attribute
onloadstart HTML elements loadstart event handler Event handler content attribute
onmessage body message event handler for Window object Event handler content attribute
onmessageerror body messageerror event handler for Window object Event handler content attribute
onmousedown HTML elements mousedown event handler Event handler content attribute
onmouseenter HTML elements mouseenter event handler Event handler content attribute
onmouseleave HTML elements mouseleave event handler Event handler content attribute
onmousemove HTML elements mousemove event handler Event handler content attribute
onmouseout HTML elements mouseout event handler Event handler content attribute
onmouseover HTML elements mouseover event handler Event handler content attribute
onmouseup HTML elements mouseup event handler Event handler content attribute
onoffline body offline event handler for Window object Event handler content attribute
ononline body online event handler for Window object Event handler content attribute
onpagehide body pagehide event handler for Window object Event handler content attribute
onpagereveal body pagereveal event handler for Window object Event handler content attribute
onpageshow body pageshow event handler for Window object Event handler content attribute
onpageswap body pageswap event handler for Window object Event handler content attribute
onpaste HTML elements paste event handler Event handler content attribute
onpause HTML elements pause event handler Event handler content attribute
onplay HTML elements play event handler Event handler content attribute
onplaying HTML elements playing event handler Event handler content attribute
onpopstate body popstate event handler for Window object Event handler content attribute
onprogress HTML elements progress event handler Event handler content attribute
onratechange HTML elements ratechange event handler Event handler content attribute
onreset HTML elements reset event handler Event handler content attribute
onresize HTML elements resize event handler Event handler content attribute
onrejectionhandled body rejectionhandled event handler for Window object Event handler content attribute
onscroll HTML elements scroll event handler Event handler content attribute
onscrollend HTML elements scrollend event handler Event handler content attribute
onsecuritypolicyviolation HTML elements securitypolicyviolation event handler Event handler content attribute
onseeked HTML elements seeked event handler Event handler content attribute
onseeking HTML elements seeking event handler Event handler content attribute
onselect HTML elements select event handler Event handler content attribute
onslotchange HTML elements slotchange event handler Event handler content attribute
onstalled HTML elements stalled event handler Event handler content attribute
onstorage body storage event handler for Window object Event handler content attribute
onsubmit HTML elements submit event handler Event handler content attribute
onsuspend HTML elements suspend event handler Event handler content attribute
ontimeupdate HTML elements timeupdate event handler Event handler content attribute
ontoggle HTML elements toggle event handler Event handler content attribute
onunhandledrejection body unhandledrejection event handler for Window object Event handler content attribute
onunload body unload event handler for Window object Event handler content attribute
onvolumechange HTML elements volumechange event handler Event handler content attribute
onwaiting HTML elements waiting event handler Event handler content attribute
onwheel HTML elements wheel event handler Event handler content attribute

Element interfaces

This section is non-normative.

List of interfaces for elements
Element(s) Interface(s)
a HTMLAnchorElement : HTMLElement
abbr HTMLElement
address HTMLElement
area HTMLAreaElement : HTMLElement
article HTMLElement
aside HTMLElement
audio HTMLAudioElement : HTMLMediaElement : HTMLElement
b HTMLElement
base HTMLBaseElement : HTMLElement
bdi HTMLElement
bdo HTMLElement
blockquote HTMLQuoteElement : HTMLElement
body HTMLBodyElement : HTMLElement
br HTMLBRElement : HTMLElement
button HTMLButtonElement : HTMLElement
canvas HTMLCanvasElement : HTMLElement
caption HTMLTableCaptionElement : HTMLElement
cite HTMLElement
code HTMLElement
col HTMLTableColElement : HTMLElement
colgroup HTMLTableColElement : HTMLElement
data HTMLDataElement : HTMLElement
datalist HTMLDataListElement : HTMLElement
dd HTMLElement
del HTMLModElement : HTMLElement
details HTMLDetailsElement : HTMLElement
dfn HTMLElement
dialog HTMLDialogElement : HTMLElement
div HTMLDivElement : HTMLElement
dl HTMLDListElement : HTMLElement
dt HTMLElement
em HTMLElement
embed HTMLEmbedElement : HTMLElement
fieldset HTMLFieldSetElement : HTMLElement
figcaption HTMLElement
figure HTMLElement
footer HTMLElement
form HTMLFormElement : HTMLElement
h1 HTMLHeadingElement : HTMLElement
h2 HTMLHeadingElement : HTMLElement
h3 HTMLHeadingElement : HTMLElement
h4 HTMLHeadingElement : HTMLElement
h5 HTMLHeadingElement : HTMLElement
h6 HTMLHeadingElement : HTMLElement
head HTMLHeadElement : HTMLElement
header HTMLElement
hgroup HTMLElement
hr HTMLHRElement : HTMLElement
html HTMLHtmlElement : HTMLElement
i HTMLElement
iframe HTMLIFrameElement : HTMLElement
img HTMLImageElement : HTMLElement
input HTMLInputElement : HTMLElement
ins HTMLModElement : HTMLElement
kbd HTMLElement
label HTMLLabelElement : HTMLElement
legend HTMLLegendElement : HTMLElement
li HTMLLIElement : HTMLElement
link HTMLLinkElement : HTMLElement
main HTMLElement
map HTMLMapElement : HTMLElement
mark HTMLElement
menu HTMLMenuElement : HTMLElement
meta HTMLMetaElement : HTMLElement
meter HTMLMeterElement : HTMLElement
nav HTMLElement
noscript HTMLElement
object HTMLObjectElement : HTMLElement
ol HTMLOListElement : HTMLElement
optgroup HTMLOptGroupElement : HTMLElement
option HTMLOptionElement : HTMLElement
output HTMLOutputElement : HTMLElement
p HTMLParagraphElement : HTMLElement
picture HTMLPictureElement : HTMLElement
pre HTMLPreElement : HTMLElement
progress HTMLProgressElement : HTMLElement
q HTMLQuoteElement : HTMLElement
rp HTMLElement
rt HTMLElement
ruby HTMLElement
s HTMLElement
samp HTMLElement
search HTMLElement
script HTMLScriptElement : HTMLElement
section HTMLElement
select HTMLSelectElement : HTMLElement
slot HTMLSlotElement : HTMLElement
small HTMLElement
source HTMLSourceElement : HTMLElement
span HTMLSpanElement : HTMLElement
strong HTMLElement
style HTMLStyleElement : HTMLElement
sub HTMLElement
summary HTMLElement
sup HTMLElement
table HTMLTableElement : HTMLElement
tbody HTMLTableSectionElement : HTMLElement
td HTMLTableCellElement : HTMLElement
template HTMLTemplateElement : HTMLElement
textarea HTMLTextAreaElement : HTMLElement
tfoot HTMLTableSectionElement : HTMLElement
th HTMLTableCellElement : HTMLElement
thead HTMLTableSectionElement : HTMLElement
time HTMLTimeElement : HTMLElement
title HTMLTitleElement : HTMLElement
tr HTMLTableRowElement : HTMLElement
track HTMLTrackElement : HTMLElement
u HTMLElement
ul HTMLUListElement : HTMLElement
var HTMLElement
video HTMLVideoElement : HTMLMediaElement : HTMLElement
wbr HTMLElement
custom elements supplied by the element's author (inherits from HTMLElement)

All interfaces

This section is non-normative.

Events

This section is non-normative.

The following table lists events fired by this document, excluding those already defined in media element events and drag-and-drop events.

List of events
Event Interface Interesting targets Description
DOMContentLoaded

Window/DOMContentLoaded_event

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
Event Document Fired at the Document once the parser has finished
afterprint

Window/afterprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event Window Fired at the Window after printing
beforeprint

Window/beforeprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event Window Fired at the Window before printing
beforematch

Element/beforematch_event

Support in one engine only.

FirefoxNoSafariNoChrome102+
OperaNoEdge102+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event Elements Fired on elements with the hidden=until-found attribute before they are revealed.
beforetoggle

HTMLElement/beforetoggle_event

Support in all current engines.

Firefox🔰 114+Safaripreview+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
ToggleEvent Elements Fired on elements with the popover attribute when they are transitioning between showing and hidden
beforeunload

Window/beforeunload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
BeforeUnloadEvent Window Fired at the Window when the page is about to be unloaded, in case the page would like to show a warning prompt
blur Event Window, elements Fired at nodes when they stop being focused
cancel

HTMLDialogElement/cancel_event

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome AndroidNoWebView Android?Samsung Internet?Opera Android?
Event CloseWatcher, dialog elements, input elements Fired at CloseWatcher objects or dialog elements when they receive a close request, or at input elements in the File state when the user does not change their selection
change

HTMLElement/change_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
Event Form controls Fired at controls when the user commits a value change (see also the input event)
click PointerEvent Elements Normally a mouse event; also synthetically fired at an element before its activation behavior is run, when an element is activated from a non-pointer input device (e.g. a keyboard)
close

HTMLDialogElement/close_event

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event CloseWatcher, dialog elements, MessagePort Fired at CloseWatcher objects or dialog elements when they are closed via a close request or via web developer code, or at MessagePort objects when disentangled
connect

SharedWorkerGlobalScope/connect_event

Support in all current engines.

Firefox29+Safari16+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS16+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
MessageEvent SharedWorkerGlobalScope Fired at a shared worker's global scope when a new client connects
contextlost

HTMLCanvasElement/webglcontextlost_event

Support in one engine only.

FirefoxNoSafariNoChrome98+
Opera?Edge98+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event canvas elements, OffscreenCanvas objects Fired when the corresponding CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D is lost
contextrestored

HTMLCanvasElement/contextrestored_event

Support in one engine only.

FirefoxNoSafariNoChrome98+
Opera?Edge98+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
Event canvas elements, OffscreenCanvas objects Fired when the corresponding CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D is restored after being lost
currententrychange NavigationCurrentEntryChangeEvent Navigation Fired when navigation.currentEntry changes
dispose Event NavigationHistoryEntry Fired when the session history entry corresponding to the NavigationHistoryEntry has been permanently evicted from session history and can no longer be traversed to
error

EventSource/error_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+

Window/error_event

Support in all current engines.

Firefox6+Safari5.1+Chrome10+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
Event or ErrorEvent Global scope objects, Worker objects, elements, networking-related objects Fired when unexpected errors occur (e.g. networking errors, script errors, decoding errors)
focus Event Window, elements Fired at nodes gaining focus
formdata

HTMLFormElement/formdata_event

Support in all current engines.

Firefox72+Safari15+Chrome77+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
FormDataEvent form elements Fired at a form element when it is constructing the entry list
hashchange

Window/hashchange_event

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android11+
HashChangeEvent Window Fired at the Window when the fragment part of the document's URL changes
input Event Elements Fired when the user changes the contenteditable element's content, or the form control's value. See also the change event for form controls.
invalid

HTMLInputElement/invalid_event

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android64+Safari iOS5+Chrome Android?WebView Android4+Samsung Internet4.0+Opera Android12+
Event Form controls Fired at controls during form validation if they do not satisfy their constraints
languagechange

Window/languagechange_event

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet4.0+Opera Android?

WorkerGlobalScope/languagechange_event

Support in all current engines.

Firefox74+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
Event Global scope objects Fired at the global scope object when the user's preferred languages change
load Event Window, elements Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading
message

BroadcastChannel/message_event

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

DedicatedWorkerGlobalScope/message_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+

EventSource/message_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+

MessagePort/message_event

Support in all current engines.

Firefox41+Safari5+Chrome2+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+

Window/message_event

Support in all current engines.

Firefox9+Safari4+Chrome60+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS4+Chrome Android?WebView Android?Samsung Internet?Opera Android47+

Worker/message_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11.5+
MessageEvent Window, EventSource, MessagePort, BroadcastChannel, DedicatedWorkerGlobalScope, Worker, ServiceWorkerContainer Fired at an object when it receives a message
messageerror

BroadcastChannel/messageerror_event

Support in all current engines.

Firefox57+Safari15.4+Chrome60+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

DedicatedWorkerGlobalScope/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

MessagePort/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

Window/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

Worker/messageerror_event

Support in all current engines.

Firefox57+Safari16.4+Chrome60+
Opera?Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+
MessageEvent Window, MessagePort, BroadcastChannel, DedicatedWorkerGlobalScope, Worker, ServiceWorkerContainer Fired at an object when it receives a message that cannot be deserialized
navigate NavigateEvent Navigation Fired before the navigable navigates, reloads, traverses, or otherwise changes its URL
navigateerror ErrorEvent Navigation Fired when a navigation does not complete successfully
navigatesuccess Event Navigation Fired when a navigation completes successfully
offline

Window/offline_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
Event Global scope objects Fired at the global scope object when the network connections fails
online

Window/online_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS3+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
Event Global scope objects Fired at the global scope object when the network connections returns
open

EventSource/open_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android12+
Event EventSource Fired at EventSource objects when a connection is established
pageswap PageSwapEvent Window Fired at the Window right before a document is unloaded as a result of a navigation.
pagehide

Window/pagehide_event

Support in all current engines.

Firefox6+Safari5+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
PageTransitionEvent Window Fired at the Window when the page's session history entry stops being the active entry
pagereveal PageRevealEvent Window Fired at the Window when the page begins to render for the first time after it has been initialized or reactivated
pageshow

Window/pageshow_event

Support in all current engines.

Firefox6+Safari5+Chrome3+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android?
PageTransitionEvent Window Fired at the Window when the page's session history entry becomes the active entry
pointercancel PointerEvent Elements and Text nodes Fired at the source node when the user attempts to initiate a drag-and-drop operation
popstate

Window/popstate_event

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+
PopStateEvent Window Fired at the Window when in some cases of session history traversal
readystatechange

Document/readystatechange_event

Support in all current engines.

Firefox4+Safari5.1+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
Event Document Fired at the Document when it finishes parsing and again when all its subresources have finished loading
rejectionhandled PromiseRejectionEvent Global scope objects Fired at global scope objects when a previously-unhandled promise rejection becomes handled
reset

HTMLFormElement/reset_event

Support in all current engines.

Firefox6+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
Event form elements Fired at a form element when it is reset
select

HTMLInputElement/select_event

Support in all current engines.

Firefox6+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLTextAreaElement/select_event

Support in all current engines.

Firefox6+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
Event Form controls Fired at form controls when their text selection is adjusted (whether by an API or by the user)
storage

Window/storage_event

Support in all current engines.

Firefox45+Safari4+Chrome1+
Opera?Edge79+
Edge (Legacy)15+Internet Explorer9+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
StorageEvent Window Fired at Window event when the corresponding localStorage or sessionStorage storage areas change
submit

HTMLFormElement/submit_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
SubmitEvent form elements Fired at a form element when it is submitted
toggle

HTMLDetailsElement/toggle_event

Support in all current engines.

Firefox49+Safari10.1+Chrome36+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLElement/toggle_event

Support in all current engines.

Firefox🔰 114+Safaripreview+Chrome114+
Opera?Edge114+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
ToggleEvent details and popover elements Fired at details elements when they open or close; fired on elements with the popover attribute when they are transitioning between showing and hidden
unhandledrejection

Window/unhandledrejection_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS11.3+Chrome Android?WebView Android?Samsung Internet?Opera Android?
PromiseRejectionEvent Global scope objects Fired at global scope objects when a promise rejection goes unhandled
unload

Window/unload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
Event Window Fired at the Window object when the page is going away
visibilitychange

Document/visibilitychange_event

Support in all current engines.

Firefox56+Safari14.1+Chrome62+
Opera49+Edge79+
Edge (Legacy)18Internet Explorer🔰 10+
Firefox Android?Safari iOS?Chrome Android?WebView Android62+Samsung Internet?Opera Android46+
Event Document Fired at the Document object when the page becomes visible or hidden to the user

HTTP headers

This section is non-normative.

The following HTTP request headers are defined by this specification:

The following HTTP response headers are defined by this specification:

MIME types

This section is non-normative.

The following MIME types are mentioned in this specification:

application/atom+xml
Atom [ATOM]
application/json
JSON [JSON]
application/octet-stream
Generic binary data [RFC2046]
application/microdata+json
Microdata as JSON
application/rss+xml
RSS
application/x-www-form-urlencoded
Form submission
application/xhtml+xml
HTML
application/xml
XML [XML] [RFC7303]
image/gif
GIF images [GIF]
image/jpeg
JPEG images [JPEG]
image/png
PNG images [PNG]
image/svg+xml
SVG images [SVG]
multipart/form-data
Form submission [RFC7578]
multipart/mixed
Generic mixed content [RFC2046]
multipart/x-mixed-replace
Streaming server push
text/css
CSS [CSS]
text/event-stream
Server-sent event streams
text/javascript
JavaScript [JAVASCRIPT] [RFC9239]
text/json
JSON (legacy type)
text/plain
Generic plain text [RFC2046] [RFC3676]
text/html
HTML
text/ping
Hyperlink auditing
text/uri-list
List of URLs [RFC2483]
text/vcard
vCard [RFC6350]
text/vtt
WebVTT [WEBVTT]
text/xml
XML [XML] [RFC7303]
video/mp4
MPEG-4 video [RFC4337]
video/mpeg
MPEG video [RFC2046]

References

All references are normative unless marked "Non-normative".

[ABNF]
Augmented BNF for Syntax Specifications: ABNF, D. Crocker, P. Overell. IETF.
[ABOUT]
The 'about' URI scheme, S. Moonesamy. IETF.
[APNG]
(Non-normative) APNG Specification. S. Parmenter, V. Vukicevic, A. Smith. Mozilla.
[ARIA]
Accessible Rich Internet Applications (WAI-ARIA), J. Diggs, J. Nurthen, M. Cooper. W3C.
[ARIAHTML]
ARIA in HTML, S. Faulkner, S. O'Hara. W3C.
[ATAG]
(Non-normative) Authoring Tool Accessibility Guidelines (ATAG) 2.0, J. Richards, J. Spellman, J. Treviranus. W3C.
[ATOM]
(Non-normative) The Atom Syndication Format, M. Nottingham, R. Sayre. IETF.
[BATTERY]
(Non-normative) Battery Status API, A. Kostiainen, M. Lamouri. W3C.
[BCP47]
Tags for Identifying Languages; Matching of Language Tags, A. Phillips, M. Davis. IETF.
[BEZIER]
Courbes à poles, P. de Casteljau. INPI, 1959.
[BIDI]
UAX #9: Unicode Bidirectional Algorithm, M. Davis. Unicode Consortium.
[BOCU1]
(Non-normative) UTN #6: BOCU-1: MIME-Compatible Unicode Compression, M. Scherer, M. Davis. Unicode Consortium.
[CESU8]
(Non-normative) UTR #26: Compatibility Encoding Scheme For UTF-16: 8-BIT (CESU-8), T. Phipps. Unicode Consortium.
[CHARMOD]
(Non-normative) Character Model for the World Wide Web 1.0: Fundamentals, M. Dürst, F. Yergeau, R. Ishida, M. Wolf, T. Texin. W3C.
[CHARMODNORM]
(Non-normative) Character Model for the World Wide Web: String Matching, A. Phillips. W3C.
[CLIPBOARD-APIS]
Clipboard API and events, G. Kacmarcik, A. Snigdha. W3C.
[COMPOSITE]
Compositing and Blending, R. Cabanier, N. Andronikos. W3C.
[COMPUTABLE]
(Non-normative) On computable numbers, with an application to the Entscheidungsproblem, A. Turing. In Proceedings of the London Mathematical Society, series 2, volume 42, pages 230-265. London Mathematical Society, 1937.
[COMPUTEPRESSURE]
(Non-normative) Compute Pressure, K. Christiansen, A. Mandy. W3C.
[CONSOLE]
Console, T. Stock, R. Kowalski, D. Farolino. WHATWG.
[COOKIES]
HTTP State Management Mechanism, A. Barth. IETF.
[CREDMAN]
Credential Management, N. Satragno, J. Hodges, M. West. W3C.
[CSP]
Content Security Policy, M. West, D. Veditz. W3C.
[CSS]
Cascading Style Sheets Level 2 Revision 2, B. Bos, T. Çelik, I. Hickson, H. Lie. W3C.
[CSSALIGN]
CSS Box Alignment, E. Etemad, T. Atkins. W3C.
[CSSANIMATIONS]
CSS Animations, D. Jackson, D. Hyatt, C. Marrin, S. Galineau, L. Baron. W3C.
[CSSATTR]
CSS Style Attributes, T. Çelik, E. Etemad. W3C.
[CSSBG]
CSS Backgrounds and Borders, B. Bos, E. Etemad, B. Kemper. W3C.
[CSSBOX]
CSS Box Model, E. Etemad. W3C.
[CSSCASCADE]
CSS Cascading and Inheritance, E. Etemad, T. Atkins. W3C.
[CSSCONTAIN]
CSS Containment, T. Atkins, F. Rivoal, V. Levin. W3C.
[CSSCOLOR]
CSS Color Module, T. Çelik, C. Lilley, L. Baron. W3C.
[CSSCOLORADJUST]
CSS Color Adjustment Module, E. Etemad, R. Atanassov, R. Lillesveen, T. Atkins. W3C.
[CSSDEVICEADAPT]
CSS Device Adaption, F. Rivoal, M. Rakow. W3C.
[CSSDISPLAY]
CSS Display, T. Atkins, E. Etemad. W3C.
[CSSFONTLOAD]
CSS Font Loading, T. Atkins, J. Daggett. W3C.
[CSSFONTS]
CSS Fonts, J. Daggett. W3C.
[CSSFLEXBOX]
CSS Flexible Box Layout, T. Atkins, E. Etemad, R. Atanassov. W3C.
[CSSGC]
CSS Generated Content, H. Lie, E. Etemad, I. Hickson. W3C.
[CSSGRID]
CSS Grid Layout, T. Atkins, E. Etemad, R. Atanassov. W3C.
[CSSIMAGES]
CSS Images Module, E. Etemad, T. Atkins, L. Verou. W3C.
[CSSIMAGES4]
CSS Images Module Level 4, E. Etemad, T. Atkins, L. Verou. W3C.
[CSSINLINE]
CSS Inline Layout, D. Cramer, E. Etemad. W3C.
[CSSLISTS]
CSS Lists and Counters, T. Atkins. W3C.
[CSSLOGICAL]
CSS Logical Properties, R. Atanassov, E. Etemad. W3C.
[CSSMULTICOL]
CSS Multi-column Layout, H. Lie, F. Rivoal, R. Andrew. W3C.
[CSSOM]
Cascading Style Sheets Object Model (CSSOM), S. Pieters, G. Adams. W3C.
[CSSOMVIEW]
CSSOM View Module, S. Pieters, G. Adams. W3C.
[CSSOVERFLOW]
CSS Overflow Module, L. Baron, F. Rivoal. W3C.
[CSSPAINT]
(Non-normative) CSS Painting API, I. Kilpatrick, D. Jackson. W3C.
[CSSPOSITION]
CSS Positioned Layout, R. Atanassov, A. Eicholz. W3C.
[CSSPSEUDO]
CSS Pseudo-Elements, D. Glazman, E. Etemad, A. Stearns. W3C.
[CSSRUBY]
CSS3 Ruby Module, R. Ishida. W3C.
[CSSSCOPING]
CSS Scoping Module, T. Atkins. W3C.
[CSSSIZING]
CSS Box Sizing Module, T. Atkins, E. Etemad. W3C.
[CSSSCROLLANCHORING]
(Non-normative) CSS Scroll Anchoring, T. Atkins-Bittner. W3C.
[CSSSYNTAX]
CSS Syntax, T. Atkins, S. Sapin. W3C.
[CSSTRANSITIONS]
(Non-normative) CSS Transitions, L. Baron, D. Jackson, B. Birtles. W3C.
[CSSTABLE]
CSS Table, F. Remy, G. Whitworth. W3C.
[CSSTEXT]
CSS Text, E. Etemad, K. Ishii. W3C.
[CSSVALUES]
CSS3 Values and Units, H. Lie, T. Atkins, E. Etemad. W3C.
[CSSVIEWTRANSITIONS]
CSS View Transitions, T. Atkins Jr.; J. Archibald; K Sagar. W3C.
[CSSUI]
CSS3 Basic User Interface Module, F. Rivoal. W3C.
[CSSWM]
CSS Writing Modes, E. Etemad, K. Ishii. W3C.
[DASH]
Dynamic adaptive streaming over HTTP (DASH). ISO.
[DEVICEPOSTURE]
(Non-normative) Device Posture API, D. Gonzalez-Zuniga, K. Christiansen. W3C.
[DOM]
DOM, A. van Kesteren, A. Gregor, Ms2ger. WHATWG.
[DOMPARSING]
DOM Parsing and Serialization, T. Leithead. W3C.
[DOT]
(Non-normative) The DOT Language. Graphviz.
[E163]
Recommendation E.163 — Numbering Plan for The International Telephone Service, CCITT Blue Book, Fascicle II.2, pp. 128-134, November 1988.
[ENCODING]
Encoding, A. van Kesteren, J. Bell. WHATWG.
[EXECCOMMAND]
execCommand, J. Wilm, A. Gregor. W3C Editing APIs CG.
[EXIF]
(Non-normative) Exchangeable image file format. JEITA.
[FETCH]
Fetch, A. van Kesteren. WHATWG.
[FILEAPI]
File API, A. Ranganathan. W3C.
[FILTERS]
Filter Effects, D. Schulze, D. Jackson, C. Harrelson. W3C.
[FULLSCREEN]
Fullscreen, A. van Kesteren, T. Çelik. WHATWG.
[GEOMETRY]
Geometry Interfaces. S. Pieters, D. Schulze, R. Cabanier. W3C.
[GIF]
(Non-normative) Graphics Interchange Format. CompuServe.
[GRAPHICS]
(Non-normative) Computer Graphics: Principles and Practice in C, Second Edition, J. Foley, A. van Dam, S. Feiner, J. Hughes. Addison-Wesley. ISBN 0-201-84840-6.
[GREGORIAN]
(Non-normative) Inter Gravissimas, A. Lilius, C. Clavius. Gregory XIII Papal Bull, February 1582.
[HRT]
High Resolution Time, I. Grigorik, J. Simonsen, J. Mann. W3C.
[HTMLAAM]
HTML Accessibility API Mappings 1.0, S. Faulkner, A. Surkov, S. O'Hara. W3C.
[HTTP]
Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing, R. Fielding, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content, R. Fielding, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests, R. Fielding, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Range Requests, R. Fielding, Y. Lafon, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Caching, R. Fielding, M. Nottingham, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Authentication, R. Fielding, J. Reschke. IETF.
[INDEXEDDB]
Indexed Database API, A. Alabbas, J. Bell. W3C.
[INBAND]
Sourcing In-band Media Resource Tracks from Media Containers into HTML, S. Pfeiffer, B. Lund. W3C.
[INFRA]
Infra, A. van Kesteren, D. Denicola. WHATWG.
[INTERSECTIONOBSERVER]
Intersection Observer, S. Zager. W3C.
[RESIZEOBSERVER]
Resize Observer, O. Brufau, E. Álvarez. W3C.
[ISO3166]
ISO 3166: Codes for the representation of names of countries and their subdivisions. ISO.
[ISO4217]
ISO 4217: Codes for the representation of currencies and funds. ISO.
[ISO8601]
(Non-normative) ISO8601: Data elements and interchange formats — Information interchange — Representation of dates and times. ISO.
[JAVASCRIPT]
ECMAScript Language Specification. Ecma International.
[JLREQ]
Requirements for Japanese Text Layout. W3C.
[JPEG]
JPEG File Interchange Format, E. Hamilton.
[JSERRORSTACKS]
(Non-normative) Error Stacks. Ecma International.
[JSDYNAMICCODEBRANDCHECKS]
Dynamic code brand checks. Ecma International.
[JSIMPORTATTRIBUTES]
Import attributes. Ecma International.
[JSJSONMODULES]
JSON Modules. Ecma International.
[JSRESIZABLEBUFFERS]
Resizable ArrayBuffer and growable SharedArrayBuffer. Ecma International.
[JSINTL]
ECMAScript Internationalization API Specification. Ecma International.
[JSON]
The JavaScript Object Notation (JSON) Data Interchange Format, T. Bray. IETF.
[JSTEMPORAL]
Temporal. Ecma International.
[LONGTASKS]
Long Tasks, D. Denicola, I. Grigorik, S. Panicker. W3C.
[LONGANIMATIONFRAMES]
Long Animation Frames, N. Rosenthal. W3C.
[MAILTO]
(Non-normative) The 'mailto' URI scheme, M. Duerst, L. Masinter, J. Zawinski. IETF.
[MANIFEST]
Web App Manifest, M. Caceres, K. Rohde Christiansen, M. Lamouri, A. Kostiainen, M. Giuca, A. Gustafson. W3C.
[MATHMLCORE]
Mathematical Markup Language (MathML), D. Carlisle, Frédéric Wang. W3C.
[MEDIAFRAG]
Media Fragments URI, R. Troncy, E. Mannens, S. Pfeiffer, D. Van Deursen. W3C.
[MEDIASOURCE]
Media Source Extensions, A. Colwell, A. Bateman, M. Watson. W3C.
[MEDIASTREAM]
Media Capture and Streams, D. Burnett, A. Bergkvist, C. Jennings, A. Narayanan. W3C.
[REPORTING]
Reporting, D. Creager, I. Clelland, M. West. W3C.
[MFREL]
Microformats Wiki: existing rel values. Microformats.
[MIMESNIFF]
MIME Sniffing, G. Hemsley. WHATWG.
[MIX]
Mixed Content, M. West. W3C.
[MNG]
MNG (Multiple-image Network Graphics) Format. G. Randers-Pehrson.
[MPEG2]
ISO/IEC 13818-1: Information technology — Generic coding of moving pictures and associated audio information: Systems. ISO/IEC.
[MPEG4]
ISO/IEC 14496-12: ISO base media file format. ISO/IEC.
[MQ]
Media Queries, H. Lie, T. Çelik, D. Glazman, A. van Kesteren. W3C.
[MULTIPLEBUFFERING]
(Non-normative) Multiple buffering. Wikipedia.
[NAVIGATIONTIMING]
Navigation Timing, Y. Weiss. W3C.
[NPAPI]
(Non-normative) Gecko Plugin API Reference. Mozilla.
[OGGSKELETONHEADERS]
SkeletonHeaders. Xiph.Org.
[OPENSEARCH]
Autodiscovery in HTML/XHTML. In OpenSearch 1.1 Draft 6. GitHub.
[ORIGIN]
(Non-normative) The Web Origin Concept, A. Barth. IETF.
[PAINTTIMING]
Paint Timing, S. Panicker. W3C.
[PAYMENTREQUEST]
Payment Request API, M. Cáceres, D. Wang, R. Solomakhin, I. Jacobs. W3C.
[PDF]
(Non-normative) Document management — Portable document format — Part 1: PDF. ISO.
[PERFORMANCETIMELINE]
Performance Timeline, N. Peña Moreno, W3C.
[PERMISSIONSPOLICY]
Permissions Policy, I. Clelland, W3C.
[PICTUREINPICTURE]
(Non-normative) Picture-in-Picture, F. Beaufort, M. Lamouri, W3C
[PINGBACK]
Pingback 1.0, S. Langridge, I. Hickson.
[PNG]
Portable Network Graphics (PNG) Specification, D. Duce. W3C.
[POINTEREVENTS]
Pointer Events, J. Rossi, M. Brubeck, R. Byers, P. H. Lauke. W3C.
[POINTERLOCK]
Pointer Lock, V. Scheib. W3C.
[PPUTF8]
(Non-normative) The Properties and Promises of UTF-8, M. Dürst. University of Zürich. In Proceedings of the 11th International Unicode Conference.
[PRESENTATION]
Presentation API, M. Foltz, D. Röttsches. W3C.
[REFERRERPOLICY]
Referrer Policy, J. Eisinger, E. Stark. W3C.
[REQUESTIDLECALLBACK]
Cooperative Scheduling of Background Tasks, R. McIlroy, I. Grigorik. W3C.
[RESOURCETIMING]
Resource Timing, Yoav Weiss; Noam Rosenthal. W3C.
[RFC1034]
Domain Names - Concepts and Facilities, P. Mockapetris. IETF, November 1987.
[RFC1123]
Requirements for Internet Hosts -- Application and Support, R. Braden. IETF, October 1989.
[RFC2046]
Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein. IETF.
[RFC2397]
The "data" URL scheme, L. Masinter. IETF.
[RFC5545]
Internet Calendaring and Scheduling Core Object Specification (iCalendar), B. Desruisseaux. IETF.
[RFC2483]
URI Resolution Services Necessary for URN Resolution, M. Mealling, R. Daniel. IETF.
[RFC3676]
The Text/Plain Format and DelSp Parameters, R. Gellens. IETF.
[RFC9239]
Updates to ECMAScript Media Types, M. Miller, M. Borins, M. Bynens, B. Farias. IETF.
[RFC4337]
(Non-normative) MIME Type Registration for MPEG-4, Y. Lim, D. Singer. IETF.
[RFC7595]
Guidelines and Registration Procedures for URI Schemes, D. Thaler, T. Hansen, T. Hardie. IETF.
[RFC5322]
Internet Message Format, P. Resnick. IETF.
[RFC6381]
The 'Codecs' and 'Profiles' Parameters for "Bucket" Media Types, R. Gellens, D. Singer, P. Frojdh. IETF.
[RFC6266]
Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP), J. Reschke. IETF.
[RFC6350]
vCard Format Specification, S. Perreault. IETF.
[RFC6596]
The Canonical Link Relation, M. Ohye, J. Kupke. IETF.
[RFC6903]
Additional Link Relation Types, J. Snell. IETF.
[RFC7034]
(Non-normative) HTTP Header Field X-Frame-Options, D. Ross, T. Gondrom. IETF.
[RFC7303]
XML Media Types, H. Thompson, C. Lilley. IETF.
[RFC7578]
Returning Values from Forms: multipart/form-data, L. Masinter. IETF.
[RFC8297]
An HTTP Status Code for Indicating Hints, K. Oku. IETF.
[SCREENORIENTATION]
Screen Orientation, M. Cáceres. W3C.
[SCSU]
(Non-normative) UTR #6: A Standard Compression Scheme For Unicode, M. Wolf, K. Whistler, C. Wicksteed, M. Davis, A. Freytag, M. Scherer. Unicode Consortium.
[SECURE-CONTEXTS]
Secure Contexts, M. West. W3C.
[SELECTION]
Selection API, R. Niwa. W3C.
[SELECTORS]
Selectors, E. Etemad, T. Çelik, D. Glazman, I. Hickson, P. Linss, J. Williams. W3C.
[SMS]
(Non-normative) URI Scheme for Global System for Mobile Communications (GSM) Short Message Service (SMS), E. Wilde, A. Vaha-Sipila. IETF.
[STRUCTURED-FIELDS]
Structured Field Values for HTTP, M. Nottingham, P-H. Kamp. IETF.
[SRI]
Subresource Integrity, D. Akhawe, F. Braun, F. Marier, J. Weinberger. W3C.
[STORAGE]
Storage, A. van Kesteren. WHATWG.
[SVG]
Scalable Vector Graphics (SVG) 2, N Andronikos, R. Atanassov, T. Bah, B. Birtles, B. Brinza, C. Concolato, E. Dahlström, C. Lilley, C. McCormack, D. Schepers, R. Schwerdtfeger, D. Storey, S. Takagi, J. Watt. W3C.
[SW]
Service Workers, A. Russell, J. Song, J. Archibald. W3C.
[TOR]
(Non-normative) Tor.
[TOUCH]
Touch Events, D. Schepers, S. Moon, M. Brubeck, A. Barstow, R. Byers. W3C.
[TRUSTED-TYPES]
Trusted Types, K. Kotowicz, M. West. W3C.
[TZDATABASE]
(Non-normative) Time Zone Database. IANA.
[UAAG]
(Non-normative) User Agent Accessibility Guidelines (UAAG) 2.0, J. Allan, K. Ford, J. Richards, J. Spellman. W3C.
[UIEVENTS]
UI Events Specification, G. Kacmarcik, T. Leithead. W3C.
[UNICODE]
The Unicode Standard. Unicode Consortium.
[UNIVCHARDET]
(Non-normative) A composite approach to language/encoding detection, S. Li, K. Momoi. Netscape. In Proceedings of the 19th International Unicode Conference.
[URL]
URL, A. van Kesteren. WHATWG.
[URN]
URN Syntax, R. Moats. IETF.
[UTF7]
(Non-normative) UTF-7: A Mail-Safe Transformation Format of Unicode, D. Goldsmith, M. Davis. IETF.
[UTF8DET]
(Non-normative) Multilingual form encoding, M. Dürst. W3C.
[UTR36]
(Non-normative) UTR #36: Unicode Security Considerations, M. Davis, M. Suignard. Unicode Consortium.
[WASMJS]
(Non-normative) WebAssembly JavaScript Interface, D. Ehrenberg. W3C.
[WCAG]
(Non-normative) Web Content Accessibility Guidelines (WCAG), A. Kirkpatrick, J. O Connor, A. Campbell, M. Cooper. W3C.
[WEBANIMATIONS]
Web Animations, B. Birtles, S. Stephens, D. Stockwell. W3C.
[WEBAUDIO]
(Non-normative) Web Audio API, P. Adenot, H. Choi. W3C.
[WEBAUTHN]
Web Authentication: An API for accessing Public Key Credentials, M. Jones, A. Kumar, E. Lundberg, D. Balfanz, V. Bharadwaj, A. Birgisson, A. Czeskis, J. Hodges, J.C. Jones, H. Le Van Gong, A. Liao, R. Lindemann, J. Bradley, C. Brand, T. Cappalli, A. Langley, G. Mandyam, M. Miller, N. Satragno, N. Steele, J. Tan, S. Weeden, M. West, J. Yasskin. W3C.
[WEBCODECS]
WebCodecs API, C. Cunningham, P. Adenot, B. Aboba. W3C.
[WEBCRYPTO]
Web Cryptography API, D. Huigens. W3C.
[WEBDRIVER]
WebDriver, S. Stewart, D. Burns. W3C.
[WEBDRIVERBIDI]
WebDriver BiDi. W3C
[WEBGL]
WebGL Specifications, D. Jackson, J. Gilbert. Khronos Group.
[WEBGPU]
WebGPU, D. Malyshau, K. Ninomiya. W3C.
[WEBIDL]
Web IDL, E. Chen, T. Gu. WHATWG.
Web Linking, M. Nottingham. IETF.
[WEBLOCKS]
(Non-normative) Web Locks API, J. Bell, K. Rosylight. W3C.
[WEBMCG]
WebM Container Guidelines. The WebM Project.
[WEBNFC]
(Non-normative) Web NFC, F. Beaufort, K. Christiansen, Z. Kis. W3C.
[WEBRTC]
(Non-normative) Web RTC, C. Jennings, F. Castelli, H. Boström, J. Bruaroey. W3C.
[WEBSOCKETS]
WebSockets, A. Rice. WHATWG.
[WEBTRANSPORT]
WebTransport, B. Aboba, N. Jaju, V. Vasiliev. W3C.
[WEBVTT]
WebVTT, S. Pieters. W3C.
[WHATWGWIKI]
The WHATWG Wiki. WHATWG.
[X121]
Recommendation X.121 — International Numbering Plan for Public Data Networks, CCITT Blue Book, Fascicle VIII.3, pp. 317-332.
[XFN]
XFN 1.1 profile, T. Çelik, M. Mullenweg, E. Meyer. GMPG.
[XHR]
XMLHttpRequest, A. van Kesteren. WHATWG.
[XKCD1288]
(Non-normative) Substitutions, Randall Munroe. xkcd.
[XML]
Extensible Markup Language, T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau. W3C.
[XMLENTITY]
(Non-normative) XML Entity Definitions for Characters, D. Carlisle, P. Ion. W3C.
[XMLNS]
Namespaces in XML, T. Bray, D. Hollander, A. Layman, R. Tobin. W3C.
[XMLSSPI]
Associating Style Sheets with XML documents, J. Clark, S. Pieters, H. Thompson. W3C.
[XPATH10]
XML Path Language (XPath) Version 1.0, J. Clark, S. DeRose. W3C.
[XSLT10]
(Non-normative) XSL Transformations (XSLT) Version 1.0, J. Clark. W3C.
[XSLTP]
(Non-normative) DOM XSLTProcessor, WHATWG Wiki. WHATWG.

Acknowledgments

Thanks to Tim Berners-Lee for inventing HTML, without which none of this would exist.

Thanks to Aankhen, Aaqa Ishtyaq, Aaron Boodman, Aaron Leventhal, Aaron Krajeski, Abhishek Ghaskata, Abhishek Gupta, Adam Barth, Adam de Boor, Adam Hepton, Adam Klein, Adam Rice, Adam Roben, Addison Phillips, Adele Peterson, Adrian Bateman, Adrian Roselli, Adrian Sutton, Agustín Fernández, Aharon (Vladimir) Lanin, Ajai Tirumali, Ajay Poshak, Akatsuki Kitamura, Alan Plum, Alastair Campbell, Alejandro G. Castro, Alex Bishop, Alex Nicolaou, Alex Nozdriukhin, Alex Rousskov, Alex Soncodi, Alexander Farkas, Alexander J. Vincent, Alexander Kalenik, Alexandre Dieulot, Alexandre Morgaut, Alexey Feldgendler, Алексей Проскуряков (Alexey Proskuryakov), Alexey Shvayka, Alexis Deveria, Alfred Agrell, Ali Juma, Alice Boxhall, Alice Wonder, Allan Clements, Allen Wirfs-Brock, Alex Komoroske, Alex Russell, Alphan Chen, Aman Ansari, Ami Fischman, Amos Jeffries, Amos Lim, Anders Carlsson, André Bargull, André E. Veltstra, Andrea Rendine, Andreas, Andreas Deuschlinger, Andreas Farre, Andreas Kling, Andrei Popescu, Andres Gomez, Andres Rios, Andreu Botella, Andrew Barfield, Andrew Clover, Andrew Gove, Andrew Grieve, Andrew Kaster, Andrew Macpherson, Andrew Oakley, Andrew Paseltiner, Andrew Simons, Andrew Smith, Andrew W. Hagen, Andrew Williams, Andrey V. Lukyanov, Andry Rendy, Andy Davies, Andy Earnshaw, Andy Heydon, Andy Paicu, Andy Palay, Anjana Vakil, Ankur Kaushal, Anna Belle Leiserson, Anna Sidwell, Anthony Boyd, Anthony Bryan, Anthony Hickson, Anthony Ramine, Anthony Ricaud, Anton Vayvod, Antonio Sartori, Antti Koivisto, Arfat Salman, Arkadiusz Michalski, Arne Thomassen, Aron Spohr, Arphen Lin, Arthur Hemery, Arthur Sonzogni, Arthur Stolyar, Arun Patole, Aryeh Gregor, Asanka Herath, Asbjørn Ulsberg, Ashley Gullen, Ashley Sheridan, Asumu Takikawa, Atsushi Takayama, Attila Haraszti, Aurelien Levy, Ave Wrigley, Avi Drissman, Axel Dahmen, 방성범 (Bang Seongbeom), Barry Pollard, Ben Boyle, Ben Godfrey, Ben Golightly, Ben Kelly, Ben Lerner, Ben Leslie, Ben Meadowcroft, Ben Millard, Benjamin Carl Wiley Sittler, Benjamin Hawkes-Lewis, Benji Bilheimer, Benoit Ren, Bert Bos, Bijan Parsia, Bil Corry, Bill Mason, Bill McCoy, Billy Wong, Billy Woods, Bjartur Thorlacius, Björn Höhrmann, Blake Frantz, Bob Lund, Bob Owen, Bobby Holley, Boris Zbarsky, Brad Fults, Brad Neuberg, Brad Spencer, Bradley Meck, Brady Eidson, Brandon Jones, Brendan Eich, Brenton Simpson, Brett Wilson, Brett Zamir, Brian Birtles, Brian Blakely, Brian Campbell, Brian Korver, Brian Kuhn, Brian M. Dube, Brian Ryner, Brian Smith, Brian Wilson, Bryan Sullivan, Bruce Bailey, Bruce D'Arcus, Bruce Lawson, Bruce Miller, Bugs Nash, C. Scott Ananian, C. Williams, Cameron McCormack, Cameron Zemek, Cao Yipeng, Carlos Amengual, Carlos Gabriel Cardona, Carlos Ibarra López, Carlos Perelló Marín, Carolyn MacLeod, Casey Leask, Cătălin Badea, Cătălin Mariș, Cem Turesoy, ceving, Chao Cai, 윤석찬 (Channy Yun), Charl van Niekerk, Charlene Wright, Charles Iliya Krempeaux, Charles McCathie Nevile, Charlie Reis, 白丞祐 (Cheng-You Bai), Chris Apers, Chris Cressman, Chris Dumez, Chris Evans, Chris Harrelson, Chris Markiewicz, Chris Morris, Chris Nardi, Chris Needham, Chris Pearce, Chris Peterson, Chris Rebert, Chris Weber, Chris Wilson, Christian Biesinger, Christian Johansen, Christian Schmidt, Christoph Päper, Christophe Dumez, Christopher Aillon, Christopher Cameron, Christopher Ferris, Chriswa, Clark Buehler, Cole Robison, Colin Fine, Collin Jackson, Corey Farwell, Corprew Reed, Craig Cockburn, Csaba Gabor, Csaba Marton, Cynthia Shelly, Cyrille Tuzi, Daksh Shah, Dan Callahan, Dan Yoder, Dane Foster, Daniel Barclay, Daniel Bratell, Daniel Brooks, Daniel Brumbaugh Keeney, Daniel Buchner, Daniel Cheng, Daniel Clark, Daniel Davis, Daniel Ehrenberg, Daniel Glazman, Daniel Holbert, Daniel Peng, Daniel Schattenkirchner, Daniel Spång, Daniel Steinberg, Daniel Tan, Daniel Trebbien, Daniel Vogelheim, Danny Sullivan, Daphne Preston-Kendal, Darien Maillet Valentine, Darin Adler, Darin Fisher, Darxus, Dave Camp, Dave Cramer, Dave Hodder, Dave Lampton, Dave Singer, Dave Tapuska, Dave Townsend, David Baron, David Bloom, David Bokan, David Bruant, David Carlisle, David E. Cleary, David Egan Evans, David Fink, David Flanagan, David Gerard, David Grogan, David Hale, David Håsäther, David Hyatt, David I. Lehn, David John Burrowes, David Matja, David Remahl, David Resseguie, David Smith, David Storey, David Vest, David Woolley, David Zbarsky, Dave Methvin, DeWitt Clinton, Dean Edridge, Dean Edwards, Dean Jackson, Debanjana Sarkar, Debi Orton, Delan Azabani, Derek Featherstone, Derek Guenther, Devarshi Pant, Devdatta, Devin Mullins, Devin Rousso, Di Zhang, Diego Ferreiro Val, Diego González Zúñiga, Diego Ponce de León, Dimitri Glazkov, Dimitry Golubovsky, Dirk Pranke, Dirk Schulze, Dirkjan Ochtman, Divya Manian, Dmitry Lazutkin, Dmitry Titov, dolphinling, Dominic Cooney, Dominic Farolino, Dominique Hazaël-Massieux, Don Brutzman, Donovan Glover, Doron Rosenberg, Doug Kramer, Doug Simpkinson, Drew Wilson, Edgar Chen, Edmund Lai, Eduard Pascual, Eduardo Vela, Edward Welbourne, Edward Z. Yang, Ehsan Akhgari, Eira Monstad, Eitan Adler, Eli Friedman, Eli Grey, Eliot Graff, Elisabeth Robson, Elizabeth Castro, Elliott Sprehn, Elliotte Harold, Emilio Cobos Álvarez, Emily Stark, Eric Carlson, Eric Casler, Eric Lawrence, Eric Portis, Eric Rescorla, Eric Semling, Eric Shepherd, Eric Willigers, Erik Arvidsson, Erik Charlebois, Erik Rose, 栗本 英理子 (Eriko Kurimoto), espretto, Evan Jacobs, Evan Martin, Evan Prodromou, Evan Stade, Evert, Evgeny Kapun, ExE-Boss, Ezequiel Garzón, fantasai, Félix Sanz, Felix Sasaki, Fernando Altomare Serboncini, Forbes Lindesay, Francesco Schwarz, Francis Brosnan Blazquez, Franck 'Shift' Quélain, François Marier, Frank Barchard, Frank Liberato, Franklin Shirley, Frederik Braun, Fredrik Söderquist, 鵜飼文敏 (Fumitoshi Ukai), Futomi Hatano, Gavin Carothers, Gavin Kistner, Gareth Rees, Garrett Smith, Gary Blackwood, Gary Kacmarcik, Gary Katsevman, Geoff Richards, Geoffrey Garen, Georg Neis, George Lund, Gianmarco Armellin, Giovanni Campagna, Giuseppe Pascale, Glenn Adams, Glenn Maynard, Graham Klyne, Greg Botten, Greg Houston, Greg Wilkins, Gregg Tavares, Gregory J. Rosmaita, Gregory Terzian, Grey, Guilherme Johansson Tramontina, guest271314, Gytis Jakutonis, Håkon Wium Lie, Habib Virji, Hajime Morrita, Hallvord Reiar Michaelsen Steen, Hanna Laakso, Hans S. Tømmerhalt, Hans Stimer, Harald Alvestrand, Hayato Ito, 何志翔 (HE Zhixiang), Henri Sivonen, Henrik Lied, Henrik Lievonen, Henry Lewis, Henry Mason, Henry Story, Hermann Donfack Zeufack, 中川博貴 (Hiroki Nakagawa), Hiroshige Hayashizaki, Hiroyuki USHITO, Hitoshi Yoshida, Hongchan Choi, 王华 (Hua Wang), Hugh Bellamy, Hugh Guiney, Hugh Winkler, Ian Bicking, Ian Clelland, Ian Davis, Ian Fette, Ian Henderson, Ian Kilpatrick, Ibrahim Ahmed, Ido Green, Ignacio Javier, Igor Oliveira, 安次嶺 一功 (Ikko Ashimine), Ilya Grigorik, Ingvar Stepanyan, isonmad, Iurii Kucherov, Ivan Enderlin, Ivan Nikulin, Ivan Panchenko, Ivo Emanuel Gonçalves, J. King, J.C. Jones, Jackson Ray Hamilton, Jacob Davies, Jacques Distler, Jake Archibald, Jake Verbaten, Jakub Vrána, Jakub Łopuszański, Jakub Wilk, James Craig, James Graham, James Greene, James Justin Harrell, James Kozianski, James M Snell, James Perrett, James Robinson, Jamie Liu, Jamie Lokier, Jamie Mansfield, Jan Kühle, Jan Miksovsky, Janice Shiu, Janusz Majnert, Jan-Ivar Bruaroey, Jan-Klaas Kollhof, Jared Jacobs, Jason Duell, Jason Kersey, Jason Lustig, Jason Orendorff, Jason White, Jasper Bryant-Greene, Jasper St. Pierre, Jatinder Mann, Jay Henry Kao, Jean-Yves Avenard, Jed Hartman, Jeff Balogh, Jeff Cutsinger, Jeff Gilbert, Jeff "=JeffH" Hodges, Jeff Schiller, Jeff Walden, Jeffrey Yasskin, Jeffrey Zeldman, 胡慧鋒 (Jennifer Braithwaite), Jellybean Stonerfish, Jennifer Apacible, Jens Bannmann, Jens Fendler, Jens Oliver Meiert, Jens Widell, Jer Noble, Jeremey Hustman, Jeremy Keith, Jeremy Orlow, Jeremy Roman, Jeroen van der Meer, Jerry Smith, Jesse Renée Beach, Jessica Jong, jfkthame, Jian Li, Jihye Hong, Jim Jewett, Jim Ley, Jim Meehan, Jim Michaels, Jinho Bang, Jinjiang (勾三股四), Jirka Kosek, Jjgod Jiang, Joaquim Medeiros, João Eiras, Jochen Eisinger, Joe Clark, Joe Gregorio, Joel Spolsky, Joel Verhagen, Joey Arhar, Johan Herland, Johanna Herman, John Boyer, John Bussjaeger, John Carpenter, John Daggett, John Fallows, John Foliot, John Harding, John Keiser, John Law, John Musgrave, John Snyders, John Stockton, John-Mark Bell, Johnny Stenback, Jon Coppeard, Jon Ferraiolo, Jon Gibbins, Jon Jensen, Jon Perlow, Jonas Sicking, Jonathan Cook, Jonathan Kew, Jonathan Neal, Jonathan Oddy, Jonathan Rees, Jonathan Watt, Jonathan Worent, Jonny Axelsson, Joram Schrijver, Jordan Tucker, Jorgen Horstink, Joris van der Wel, Jorunn Danielsen Newth, Joseph Kesselman, Joseph Mansfield, Joseph Pecoraro, Josh Aas, Josh Hart, Josh Juran, Josh Levenberg, Josh Matthews, Joshua Bell, Joshua Chen, Joshua Randall, Juan Olvera, Juanmi Huertas, Jukka K. Korpela, Jules Clément-Ripoche, Julian Reschke, Julio Lopez, 小勝 純 (Jun Kokatsu), Jun Yang (harttle), Jungkee Song, Jürgen Jeka, Justin Lebar, Justin Novosad, Justin Rogers, Justin Schuh, Justin Sinclair, Juuso Lapinlampi, Ka-Sing Chou, Kagami Sascha Rosylight, Kai Hendry, Kamishetty Sreeja, 呂康豪 (KangHao Lu), Karl Dubost, Karl Tomlinson, Kartik Arora, Kartikaya Gupta, Kathy Walton, 河童エクマ(Kawarabe Ecma) Keith Cirkel, Keith Rollin, Keith Yeung, Kelly Ford, Kelly Norton, Ken Russell, Kenji Baheux, Kevin Benson, Kevin Cole, Kevin Gadd, Kevin Venkiteswaran, Khushal Sagar, Kinuko Yasuda, Koji Ishii, Kornél Pál, Kornel Lesinski, 上野 康平 (UENO, Kouhei), Kris Northfield, Kristof Zelechovski, Krzysztof Maczyński, 黒澤剛志 (Kurosawa Takeshi), Kyle Barnhart, Kyle Hofmann, Kyle Huey, Léonard Bouchet, Léonie Watson, Lachlan Hunt, Larry Masinter, Larry Page, Lars Gunther, Lars Solberg, Laura Carlson, Laura Granka, Laura L. Carlson, Laura Wisewell, Laurens Holst, Lawrence Forooghian, Lee Kowalkowski, Leif Halvard Silli, Leif Kornstaedt, Lenny Domnitser, Leonard Rosenthol, Leons Petrazickis, Liviu Tinta, Lobotom Dysmon, Logan, Logan Moore, Loune, Lucas Gadani, Łukasz Pilorz, Luke Kenneth Casson Leighton, Luke Warlow, Luke Wilde, Maciej Stachowiak, Magne Andersson, Magnus Kristiansen, Maik Merten, Majid Valipour, Malcolm Rowe, Manish Goregaokar, Manish Tripathi, Manuel Martinez-Almeida, Manuel Rego Casasnovas, Marc Hoyois, Marc-André Choquette, Marc-André Lafortune, Marco Zehe, Marcus Bointon, Marcus Otterström, Marijn Kruisselbrink, Mark Amery, Mark Birbeck, Mark Davis, Mark Green, Mark Miller, Mark Nottingham, Mark Pilgrim, Mark Rogers, Mark Rowe, Mark Schenk, Mark Vickers, Mark Wilton-Jones, Markus Cadonau, Markus Stange, Martijn van der Ven, Martijn Wargers, Martin Atkins, Martin Chaov, Martin Dürst, Martin Honnen, Martin Janecke, Martin Kutschker, Martin Nilsson, Martin Thomson, Masataka Yakura, Masatoshi Kimura, Mason Freed, Mason Mize, Mathias Bynens, Mathieu Henri, Matias Larsson, Matt Brubeck, Matt Di Pasquale, Matt Falkenhagen, Matt Giuca, Matt Harding, Matt Schmidt, Matt Wright, Matthew Gaudet, Matthew Gregan, Matthew Mastracci, Matthew Noorenberghe, Matthew Raymond, Matthew Thomas, Matthew Tylee Atkinson, Mattias Waldau, Max Romantschuk, Maxim Tsoy, Mayeul Cantan, Menachem Salomon, Menno van Slooten, Micah Dubinko, Micah Nerren, Michael 'Ratt' Iannarelli, Michael A. Nachbaur, Michael A. Puls II, Michael Carter, Michael Daskalov, Michael Day, Michael Dyck, Michael Enright, Michael Gratton, Michael Kohler, Michael McKelvey, Michael Nordman, Michael Powers, Michael Rakowski, Michael(tm) Smith, Michael Walmsley, Michal Zalewski, Michel Buffa, Michel Fortin, Michelangelo De Simone, Michiel van der Blonk, Miguel Casas-Sanchez, Mihai Şucan, Mihai Parparita, Mike Brown, Mike Dierken, Mike Dixon, Mike Hearn, Mike Pennisi, Mike Schinkel, Mike Shaver, Mikko Rantalainen, Mingye Wang, Mirko Brodesser, Mohamed Zergaoui, Mohammad Al Houssami, Mohammad Reza Zakerinasab, Momdo Nakamura, Morten Stenshorne, Mounir Lamouri, Ms2ger, mtrootyy, 邱慕安 (Mu-An Chiou), Mukilan Thiyagarajan, Mustaq Ahmed, Myles Borins, Nadia Heninger, Nate Chapin, NARUSE Yui, Navid Zolghadr, Neil Deakin, Neil Rashbrook, Neil Soiffer, Nereida Rondon, networkException, Nicholas Shanks, Nicholas Stimpson, Nicholas Zakas, Nickolay Ponomarev, Nicolas Gallagher, Nicolas Pena Moreno, Nicolò Ribaudo, Nidhi Jaju, Nikki Bee, Niklas Gögge, Nina Satragno, Noah Mendelsohn, Noah Slater, Noam Rosenthal, Noel Gordon, Nolan Waite, NoozNooz42, Norbert Lindenberg, Oisín Nolan, Ojan Vafai, Olaf Hoffmann, Olav Junker Kjær, Oldřich Vetešník, Oli Studholme, Oliver Hunt, Oliver Rigby, Olivia (Xiaoni) Lai, Olivier Gendrin, Olli Pettay, Ondřej Žára, Ori Avtalion, Oriol Brufau, oSand, Pablo Flouret, Patrick Dark, Patrick Garies, Patrick H. Lauke, Patrik Persson, Paul Adenot, Paul Lewis, Paul Norman, Per-Erik Brodin, 一丝 (percyley), Perry Smith, Peter Beverloo, Peter Karlsson, Peter Kasting, Peter Moulder, Peter Occil, Peter Stark, Peter Van der Beken, Peter van der Zee, Peter-Paul Koch, Phil Pickering, Philip Ahlberg, Philip Brembeck, Philip Taylor, Philip TAYLOR, Philippe De Ryck, Pierre-Arnaud Allumé, Pierre-Marie Dartus, Pierre-Yves Gérardy, Piers Wombwell, Pooja Sanklecha, Prashant Hiremath, Prashanth Chandra, Prateek Rungta, Pravir Gupta, Prayag Verma, 李普君 (Pujun Li), Rachid Finge, Rafael Weinstein, Rafał Miłecki, Rahul Purohit, Raj Doshi, Rajas Moonka, Rakina Zata Amni, Ralf Stoltze, Ralph Giles, Raphael Champeimont, Rebecca Star, Remci Mizkur, Remco, Remy Sharp, Rene Saarsoo, Rene Stach, Ric Hardacre, Rich Clark, Rich Doughty, Richa Rupela, Richard Gibson, Richard Ishida, Ricky Mondello, Rigo Wenning, Rikkert Koppes, Rimantas Liubertas, Riona Macnamara, Rob Buis, Rob Ennals, Rob Jellinghaus, Rob S, Rob Smith, Robert Blaut, Robert Collins, Robert Hogan, Robert Kieffer, Robert Linder, Robert Millan, Robert O'Callahan, Robert Sayre, Robin Berjon, Robin Schaufler, Rodger Combs, Roland Steiner, Roma Matusevich, Romain Deltour, Roman Ivanov, Roy Fielding, Rune Lillesveen, Russell Bicknell, Ruud Steltenpool, Ryan King, Ryan Landay, Ryan Sleevi, Ryo Kajiwara, Ryo Kato, Ryosuke Niwa, S. Mike Dierken, Salvatore Loreto, Sam Dutton, Sam Kuper, Sam Ruby, Sam Sneddon, Sam Weinig, Samikshya Chand, Samuel Bronson, Samy Kamkar, Sander van Lambalgen, Sanjoy Pal, Sanket Joshi, Sarah Gebauer, Sarven Capadisli, Satrujit Behera, Sayan Sivakumaran, Schalk Neethling, Scott Beardsley, Scott González, Scott Hess, Scott Miles, Scott O'Hara, Sean B. Palmer, Sean Feng, Sean Fraser, Sean Hayes, Sean Hogan, Sean Knapp, Sebastian Markbåge, Sebastian Schnitzenbaumer, Sendil Kumar N, Seth Call, Seth Dillingham, Shannon Moeller, Shanti Rao, Shaun Inman, Shiino Yuki, 贺师俊 (HE Shi-Jun), Shiki Okasaka, Shivani Sharma, shreyateeza, Shubheksha Jalan, Sidak Singh Aulakh, Sierk Bornemann, Sigbjørn Finne, Sigbjørn Vik, Silver Ghost, Silvia Pfeiffer, Šime Vidas, Simon Fraser, Simon Montagu, Simon Sapin, Yu Han, Simon Spiegel, Simon Wülker, skeww, Smylers, Srirama Chandra Sekhar Mogali, Stanton McCandlish, stasoid, Stefan Håkansson, Stefan Haustein, Stefan Santesson, Stefan Schumacher, Ştefan Vargyas, Stefan Weiss, Steffen Meschkat, Stephen Ma, Stephen Stewart, Stephen White, Steve Comstock, Steve Faulkner, Steve Fink, Steve Orvell, Steve Runyon, Steven Bennett, Steven Bingler, Steven Garrity, Steven Tate, Stewart Brodie, Stuart Ballard, Stuart Langridge, Stuart Parmenter, Subramanian Peruvemba, Sudhanshu Jaiswal, sudokus999, Sunava Dutta, Surma, Susan Borgrink, Susan Lesch, Sylvain Pasche, T.J. Crowder, Tab Atkins-Bittner, Taiju Tsuiki, Takashi Toyoshima, Takayoshi Kochi, Takeshi Yoshino, Tantek Çelik, 田村健人 (Kent TAMURA), Tawanda Moyo, Taylor Hunt, Ted Mielczarek, Terence Eden, Terrence Wood, Tetsuharu OHZEKI, Theresa O'Connor, Thijs van der Vossen, Thomas Broyer, Thomas Koetter, Thomas O'Connor, Tim Altman, Tim Dresser, Tim Johansson, Tim Nguyen, Tim Perry, Tim van der Lippe, TJ VanToll, Tobias Schneider, Tobie Langel, Toby Inkster, Todd Moody, Tom Baker, Tom Pike, Tom Schuster, Tom ten Thij, Tomasz Jakut, Tomek Wytrębowicz, Tommy Thorsen, Tony Ross, Tooru Fujisawa, Toru Kobayashi, Traian Captan, Travis Leithead, Trevor Rowbotham, Trevor Saunders, Trey Eckels, triple-underscore, Tristan Fraipont, 保呂 毅 (Tsuyoshi Horo), Tyler Close, Valentin Gosu, Vardhan Gupta, Vas Sudanagunta, Veli Şenol, Victor Carbune, Victor Costan, Vipul Snehadeep Chawathe, Vitya Muhachev, Vlad Levin, Vladimir Katardjiev, Vladimir Vukićević, Vyacheslav Aristov, voracity, Walter Steiner, Wakaba, Wayne Carr, Wayne Pollock, Wellington Fernando de Macedo, Weston Ruter, Wilhelm Joys Andersen, Will Levine, Will Ray, William Chen, William Swanson, Willy Martin Aguirre Rodriguez, Wladimir Palant, Wojciech Mach, Wolfram Kriesing, Xan Gregg, xenotheme, XhmikosR, Xida Chen, Xidorn Quan, Xue Fuqiao, Yang Chen, Yao Xiao, Yash Handa, Yay295, Ye-Kui Wang, Yehuda Katz, Yi Xu, Yi-An Huang, Yngve Nysaeter Pettersen, Yoav Weiss, Yonathan Randolph, Yu Huojiang, Yuki Okushi, Yury Delendik, 平野裕 (Yutaka Hirano), Yuzo Fujishima, 西條柚 (Yuzu Saijo), Zhenbin Xu, 张智强 (Zhiqiang Zhang), Zoltan Herczeg, Zyachel, and Øistein E. Andersen, for their useful comments, both large and small, that have led to changes to this specification over the years.

Thanks also to everyone who has ever posted about HTML to their blogs, public mailing lists, or forums, including all the contributors to the various W3C HTML WG lists and the various WHATWG lists.

Special thanks to Richard Williamson for creating the first implementation of canvas in Safari, from which the canvas feature was designed.

Special thanks also to the Microsoft employees who first implemented the event-based drag-and-drop mechanism, contenteditable, and other features first widely deployed by the Windows Internet Explorer browser.

Special thanks and $10,000 to David Hyatt who came up with a broken implementation of the adoption agency algorithm that the editor had to reverse engineer and fix before using it in the parsing section.

Thanks to the participants of the microdata usability study for allowing us to use their mistakes as a guide for designing the microdata feature.

Thanks to the many sources that provided inspiration for the examples used in the specification.

Thanks also to the Microsoft blogging community for some ideas, to the attendees of the W3C Workshop on Web Applications and Compound Documents for inspiration, to the #mrt crew, the #mrt.no crew, and the #whatwg crew, and to Pillar and Hedral for their ideas and support.

Thanks to Igor Zhbanov for generating PDF versions of the specification.

Special thanks to the RICG for developing the picture element and related features; in particular thanks to Adrian Bateman, Bruce Lawson, David Newton, Ilya Grigorik, John Schoenick, Leon de Rijke, Mat Marquis, Marcos Cáceres, Tab Atkins, Theresa O'Connor, and Yoav Weiss for their contributions.

Special thanks to the WPWG for incubating the custom elements feature. In particular, thanks to David Hyatt and Ian Hickson for their influence through the XBL specifications, Dimitri Glazkov for the first draft of the custom elements specification, and to Alex Komoroske, Alex Russell, Andres Rios, Boris Zbarsky, Brian Kardell, Daniel Buchner, Dominic Cooney, Erik Arvidsson, Elliott Sprehn, Hajime Morrita, Hayato Ito, Jan Miksovsky, Jonas Sicking, Olli Pettay, Rafael Weinstein, Roland Steiner, Ryosuke Niwa, Scott Miles, Steve Faulkner, Steve Orvell, Tab Atkins, Theresa O'Connor, Tim Perry, and William Chen for their contributions.

Special thanks to the CSSWG for developing the worklets. In particular, thanks to Ian Kilpatrick for his work as editor of the original worklets specification.

For about ten years starting in 2003, this standard was almost entirely written by Ian Hickson (Google, ian@hixie.ch).

As of 2015, Simon Pieters (Mozilla, zcorpan@gmail.com), Anne van Kesteren (Apple, annevk@annevk.nl), Philip Jägenstedt (Google, philip@foolip.org), and Domenic Denicola (Google, d@domenic.me), all previously long-time contributors, have joined Ian in editing the text directly.

Intellectual property rights

The image in the introduction is based on a photo by Wonderlane. (CC BY 2.0)

The image of the wolf in the embedded content introduction is based on a photo by Barry O'Neill. (Public domain)

The image of the kettlebell swing in the embedded content introduction is based on a photo by kokkarina. (CC0 1.0)

The Blue Robot Player sprite used in the canvas demo is based on a work by JohnColburn. (CC BY-SA 3.0)

The photograph of robot 148 climbing the tower at the FIRST Robotics Competition 2013 Silicon Valley Regional is based on a work by Lenore Edman. (CC BY 2.0)

The diagram showing how async and defer impact script loading is based on a similar diagram from a blog post by Peter Beverloo. (CC0 1.0)

The image decoding demo used to demonstrate module-based workers draws on some example code from a tutorial by Ilmari Heikkinen. (CC BY 3.0)

The <flag-icon> example was inspired by a custom element by Steven Skelton. (MIT)

Part of the revision history of the picture element and related features can be found in the ResponsiveImagesCG/picture-element repository, which is available under the W3C Software and Document License.

Part of the revision history of the theme-color metadata name can be found in the whatwg/meta-theme-color repository, which is available under CC0.

Part of the revision history of the custom elements feature can be found in the w3c/webcomponents repository, which is available under the W3C Software and Document License.

Part of the revision history of the innerText getter and setter can be found in the rocallahan/innerText-spec repository, which is available under CC0.

Part of the revision history of the worklets feature can be found in the w3c/css-houdini-drafts repository, which is available under the W3C Software and Document License.

Part of the revision history of the import maps feature can be found in the WICG/import-maps repository, which is available under the W3C Software and Document License.

Part of the revision history of the navigation API feature can be found in the WICG/navigation-api repository, which is available under the W3C Software and Document License.

Part of the revision history of the Close requests and close watchers section can be found in the WICG/close-watcher repository, which is available under the W3C Software and Document License.

Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License. To the extent portions of it are incorporated into source code, such portions in the source code are licensed under the BSD 3-Clause License instead.

This is the Living Standard. Those interested in the patent-review version should view the Living Standard Review Draft.